From 719866a2a7cd50bd74b3f8ec3372b43db1dc5498 Mon Sep 17 00:00:00 2001 From: Yigit BALABAN Date: Fri, 30 Oct 2026 23:06:52 +0300 Subject: [PATCH] Exit when Accessibility is revoked A tap that outlives its Accessibility grant can stall scroll events, and every later click and key queues behind them. When the grant goes, remove the tap, restore the buttons and exit. Assisted-by: Claude Signed-off-by: Yigit BALABAN --- mxd.swift | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) 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