Files
mac_without_borders/Sources/MWBMac/Permissions.swift
T
lucioandClaude Opus 5 fd1ceeac08 input-capture: protocol §10.4, README rewrite, TODO §4 ticked
§10.4 records ten things the lane established from the Windows source
(one-sided hotkey matching, the three meanings of Md.WheelDelta, the
virtual cursor and its primary+-1 clamp, the unconditional relative bias,
SwitchLocation, synthesised LLKHF bits, the eleven ReleaseAllKeys VKs, the
two input counters, monitor enumeration) plus the macOS device masks. The
README's Assumptions and Handshakes now describe what shipped, with the
nine decisions and three deliberate non-ports in the work log.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 02:18:12 -07:00

106 lines
4.2 KiB
Swift

// The one wrapper around the `CGPreflight*EventAccess` / `CGRequest*EventAccess`
// C API (CLAUDE.md, Swift standards: C APIs are wrapped once), plus the health
// check that notices a grant being taken away while we run (contracts C2).
//
// Windows has no equivalent: a low-level hook needs no permission there. On
// macOS the tap simply stops existing, so the app has to watch for it.
//
// CLAUDE.md, Workflow: an agent never grants, requests or scripts these
// permissions. `request()` exists for a button the *user* clicks, and nothing in
// this repository may call it on its own initiative.
import CoreGraphics
import Foundation
import os
/// Which macOS TCC permissions the current process holds.
///
/// `listen` is Input Monitoring (needed to observe key events), `post` is
/// Accessibility (needed to inject events and to run a swallowing tap).
public struct PermissionState: Equatable, Sendable {
/// Input Monitoring granted.
public let listen: Bool
/// Accessibility granted.
public let post: Bool
/// True when both permissions are granted.
public var isComplete: Bool { listen && post }
}
/// Preflight, request and watch the two grants the app needs.
public enum Permissions {
/// How often the health check re-reads the grants (contracts C2).
public static let healthCheckInterval: TimeInterval = 5
/// Reads the current grants without prompting the user.
public static func preflight() -> PermissionState {
PermissionState(
listen: CGPreflightListenEventAccess(),
post: CGPreflightPostEventAccess())
}
/// Asks macOS to show the system prompts for whichever grant is missing.
///
/// **Only ever call this from a control the user clicked.** It shows modal
/// system UI, and macOS shows each prompt once per code signature — spending
/// it unasked leaves the user with a Settings pane and no explanation.
/// Returns the state as macOS reports it immediately afterwards, which is
/// normally still incomplete: the grant lands when the user flips the switch
/// in System Settings, and the health check is what notices.
@discardableResult
public static func request() -> PermissionState {
let state = preflight()
if !state.listen { _ = CGRequestListenEventAccess() }
if !state.post { _ = CGRequestPostEventAccess() }
return preflight()
}
/// Starts re-reading the grants every `interval` seconds and calls `onChange`
/// whenever they differ from the last reading.
///
/// contracts C2: a revoked grant means the tap is dead, so the caller routes
/// control local and shows the state in the menu bar. Keep the returned
/// object alive; dropping it stops the check.
public static func startHealthCheck(
interval: TimeInterval = healthCheckInterval,
onChange: @escaping @Sendable (PermissionState) -> Void
) -> PermissionHealthCheck {
PermissionHealthCheck(interval: interval, onChange: onChange)
}
}
/// A repeating permission check. Cancels itself when released.
///
/// `@unchecked Sendable`: its only stored property is a `DispatchSourceTimer`,
/// which is safe to use from any thread by its own contract.
public final class PermissionHealthCheck: @unchecked Sendable {
private let timer: any DispatchSourceTimer
fileprivate init(interval: TimeInterval, onChange: @escaping @Sendable (PermissionState) -> Void) {
let queue = DispatchQueue(label: "com.mwb-mac.permission-health", qos: .utility)
let timer = DispatchSource.makeTimerSource(queue: queue)
let last = OSAllocatedUnfairLock(initialState: Permissions.preflight())
timer.schedule(deadline: .now() + interval, repeating: interval, leeway: .seconds(1))
timer.setEventHandler {
let current = Permissions.preflight()
let changed = last.withLock { previous -> Bool in
guard previous != current else { return false }
previous = current
return true
}
if changed { onChange(current) }
}
self.timer = timer
timer.resume()
}
/// Stops the check. Idempotent.
public func cancel() {
timer.cancel()
}
deinit {
timer.cancel()
}
}