diff --git a/mxd.swift b/mxd.swift index 2d4e34a..a7f903a 100644 --- a/mxd.swift +++ b/mxd.swift @@ -560,6 +560,28 @@ if rc != kIOReturnSuccess { log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc)) } +// A tap that outlives its Accessibility grant can stall scroll events, and every later click and key +// queues behind them. So when the grant goes: remove the tap first, restore the buttons, exit. +// Run under launchd with KeepAlive/SuccessfulExit=false, so exit(0) doesn't restart mxd. +func checkPermission() { + guard let port = tapPort, !AXIsProcessTrusted() else { return } + CGEvent.tapEnable(tap: port, enable: false) + CFMachPortInvalidate(port) + tapPort = nil + log("Accessibility revoked: tap removed, exiting") + devices.values.forEach(undivertAll) + exit(0) +} +// The notification is immediate but can fire just before the new state is readable; the timer is the backstop. +let permissionObserver = DistributedNotificationCenter.default().addObserver( + forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in + checkPermission() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { checkPermission() } +} +let permissionTimer = Timer(timeInterval: 1, repeats: true) { _ in checkPermission() } +permissionTimer.tolerance = 0.2 +RunLoop.main.add(permissionTimer, forMode: .common) + // Clean shutdown: un-divert so buttons work natively again. signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN) let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in