import AppKit @preconcurrency import ApplicationServices import CoreGraphics public enum AccessibilityStatus: Equatable, Sendable { case granted case notGranted /// A previous grant was reported, but the process is not currently trusted. /// This is not proof of a stale system entry; access may also have been revoked. case possiblyStale public static func evaluate(isTrusted: Bool, wasPreviouslyGranted: Bool) -> Self { if isTrusted { return .granted } return wasPreviouslyGranted ? .possiblyStale : .notGranted } } public enum Permissions { public enum SettingsPane: Sendable { case accessibility case inputMonitoring var url: URL? { switch self { case .accessibility: URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") case .inputMonitoring: URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent") } } } public enum PollingError: Error, Equatable, Sendable { case invalidInterval } /// The caller supplies evidence of a previous grant; this does not inspect System Settings. public static func accessibilityStatus(wasPreviouslyGranted: Bool = false) -> AccessibilityStatus { AccessibilityStatus.evaluate( isTrusted: AXIsProcessTrusted(), wasPreviouslyGranted: wasPreviouslyGranted ) } /// Requests the system prompt if needed. The result is the current trust state, not the prompt's outcome. @discardableResult public static func requestAccessibility() -> Bool { let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary return AXIsProcessTrustedWithOptions(options) } /// Waits without prompting until Accessibility is granted or the task is cancelled. public static func waitForAccessibility(pollInterval: Duration = .seconds(1)) async throws { try await waitForAccessibility( pollInterval: pollInterval, isTrusted: { AXIsProcessTrusted() }, sleep: { try await Task.sleep(for: $0) } ) } static func waitForAccessibility( pollInterval: Duration, isTrusted: @Sendable () async -> Bool, sleep: @Sendable (Duration) async throws -> Void ) async throws { guard pollInterval > .zero else { throw PollingError.invalidInterval } while true { try Task.checkCancellation() let trusted = await isTrusted() try Task.checkCancellation() if trusted { return } try await sleep(pollInterval) } } public static func inputMonitoringIsGranted() -> Bool { CGPreflightListenEventAccess() } /// Requests Input Monitoring access and returns the system's current result. @discardableResult public static func requestInputMonitoring() -> Bool { CGRequestListenEventAccess() } /// Returns whether System Settings accepted the request to open the pane. @MainActor @discardableResult public static func openSettings(_ pane: SettingsPane) -> Bool { guard let url = pane.url else { return false } return NSWorkspace.shared.open(url) } }