Files
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

282 lines
11 KiB
Swift

// 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) 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
import MWBCore
import MWBMac
import MWBNet
/// This Mac's name on the wire (README D7).
///
/// Protocol §1.1 gives the field 32 ASCII bytes and the Windows side resolves us
/// by exactly this string (§7), so a name that does not fit, or is not ASCII, is
/// refused up front rather than silently mangled by `Packet.setMachineName`.
enum Hostname {
/// The longest name a `DATA` packet can carry.
static let maximumLength = 32
/// The name, plus a sentence explaining why it is unusable when it is.
static func local() -> (name: String, problem: String?) {
var buffer = [CChar](repeating: 0, count: 256)
guard gethostname(&buffer, buffer.count - 1) == 0 else {
return ("", "gethostname() failed")
}
let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }
let full = String(decoding: bytes, as: UTF8.self)
// `my-mac.local` and `my-mac.example.com` are both `my-mac` on the wire.
let name = full.split(separator: ".").first.map(String.init) ?? full
if name.isEmpty {
return (name, "this Mac has no host name; set one in System Settings > General > Sharing")
}
if !name.allSatisfy(\.isASCII) {
return (name, "host name \"\(name)\" is not ASCII; the protocol allows ASCII only")
}
if name.count > maximumLength {
return (name, "host name \"\(name)\" is longer than \(maximumLength) characters")
}
return (name, nil)
}
}
/// The `flock` that makes a second launch exit instead of fighting over the tap.
///
/// Windows uses a named window title (`MachineStuff.CheckSecondInstance`,
/// `:1052-1062`); a lock file is the boring macOS equivalent and releases itself
/// when the process dies, however it dies.
enum SingleInstance {
/// `~/Library/Application Support/mwb-mac/mwb.pid`.
static func pidFileURL() -> URL {
Settings.defaultURL().deletingLastPathComponent().appendingPathComponent("mwb.pid")
}
/// Takes the lock, returning the descriptor to hold open for the process's
/// lifetime, or `nil` if another copy already holds it.
static func acquire(at url: URL) -> Int32? {
try? FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let descriptor = open(url.path, O_CREAT | O_RDWR, 0o600)
guard descriptor >= 0 else { return nil }
guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
close(descriptor)
return nil
}
ftruncate(descriptor, 0)
let pid = "\(ProcessInfo.processInfo.processIdentifier)\n"
_ = pid.withCString { write(descriptor, $0, strlen($0)) }
return descriptor
}
}
/// The last thing that runs, however the process ends (contracts C2, last row).
///
/// Everything here is **synchronous and never touches the Engine actor**: an
/// `atexit` handler cannot `await`, and a Mac left with held modifiers or a
/// pointer still disassociated from the mouse is exactly the failure CLAUDE.md
/// invariant 3 forbids. `Injector.releaseAll()` and `Cursor.restoreEverything()`
/// are both documented safe from any thread by their own lanes.
final class EmergencyRelease: @unchecked Sendable {
static let shared = EmergencyRelease()
/// How long the signal path gives a queued `ByeBye` to reach the wire — the
/// same wait `Engine.stop()` makes on the graceful path
/// (`InitAndCleanup.cs:192-215`).
static let goodbyeGrace: TimeInterval = 0.15
private let lock = NSLock()
private var injector: Injector?
private var cursor: Cursor?
private var channel: ControlChannel?
private var done = false
/// Hands over the two objects the handlers may touch. Called once, at start.
func arm(injector: Injector, cursor: Cursor) {
lock.lock()
self.injector = injector
self.cursor = cursor
lock.unlock()
}
/// Hands over the channel, so the signal path can keep contracts C2's last
/// row ("sockets send `ByeBye`") without waking the Engine actor.
///
/// `ControlChannel` is `Sendable` and every one of its methods hops to its
/// own serial queue, so this is a reference the handlers may hold and call
/// from any thread — unlike everything else the Engine owns.
func arm(channel: ControlChannel?) {
lock.lock()
self.channel = channel
lock.unlock()
}
/// Best-effort `ByeBye` on the way out: queue it on every trusted
/// connection, then give it `goodbyeGrace` to be written.
///
/// Best effort in the literal sense — the write happens on the channel's
/// queue, so a stuck queue loses the packet and the peer falls back to its
/// own socket-level detection (`SocketStuff.cs:1561-1563`). Blocking the
/// caller for 150 ms is only acceptable because the caller is about to
/// `exit(0)`; the keys and the pointer are already back by then.
func sayGoodbye() {
lock.lock()
let channel = self.channel
lock.unlock()
guard let channel else { return }
channel.sayGoodbye()
Thread.sleep(forTimeInterval: EmergencyRelease.goodbyeGrace)
}
/// Releases every held key and gives the pointer back. Idempotent.
func run() {
lock.lock()
let alreadyDone = done
done = true
let injector = self.injector
let cursor = self.cursor
lock.unlock()
guard !alreadyDone else { return }
cursor?.restoreEverything()
injector?.releaseAll()
}
}
/// The app.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private var engine: Engine?
private var store: SettingsStore?
private var ui: UIBridge?
private var lockDescriptor: Int32?
private var signalSources: [any DispatchSourceSignal] = []
private var terminating = false
func applicationDidFinishLaunching(_ notification: Notification) {
guard let descriptor = SingleInstance.acquire(at: SingleInstance.pidFileURL()) else {
FileHandle.standardError.write(Data("mwb: another instance is already running\n".utf8))
exit(1)
}
lockDescriptor = descriptor
Log.startFileLogging()
Log.app.info("mwb \(MWBVersion.string) starting")
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)")
reportFatal("Mouse Without Borders could not read its settings.", error)
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
guard let engine, !terminating else { return .terminateNow }
terminating = true
Task {
await engine.stop()
NSApp.reply(toApplicationShouldTerminate: true)
}
return .terminateLater
}
func applicationWillTerminate(_ notification: Notification) {
EmergencyRelease.shared.run()
ui?.stop()
Log.stopFileLogging()
}
// MARK: - Startup
private func startEngine() throws {
let store = try SettingsStore()
self.store = store
let host = Hostname.local()
let engine = Engine(store: store, localName: host.name, hostnameProblem: host.problem)
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()
observeWorkspace(engine)
store.onExternalChange { [emit = engine.emit] settings in emit(.settingsChanged(settings)) }
store.startWatching()
// A `@MainActor` class is `Sendable`, so the snapshot callback may hold
// 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 ui.render(snapshot) }
}
await engine.start()
}
}
private func observeWorkspace(_ engine: Engine) {
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didWakeNotification, object: nil, queue: .main
) { [emit = engine.emit] _ in
emit(.systemWoke)
}
}
private func installSignalHandlers() {
// `DispatchSourceSignal` rather than `signal(2)`: the handler then runs
// on an ordinary queue, where posting key-ups and talking to the window
// server are legal, instead of in signal context where they are not.
for number in [SIGTERM, SIGINT, SIGHUP] {
signal(number, SIG_IGN)
let source = DispatchSource.makeSignalSource(signal: number, queue: .main)
source.setEventHandler {
// Keys and pointer first (CLAUDE.md invariant 3), then contracts
// C2's last row: the peers are told we are gone. Neither call
// touches the Engine actor — the channel is its own lock.
EmergencyRelease.shared.run()
EmergencyRelease.shared.sayGoodbye()
exit(0)
}
source.resume()
signalSources.append(source)
}
}
// MARK: - Failure to start
/// 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)
}
}