import ApplicationServices import CoreGraphics import Foundation /// The Accessibility operations Replace needs, behind a seam for tests. public protocol AccessibilityTextEditing: Sendable { /// Whether the app is trusted for Accessibility. func isTrusted() async -> Bool /// The focused element's selected text, or nil when unsupported. func selectedText(pid: pid_t) async -> String? /// True for a secure/password field. func isSecureField(pid: pid_t) async -> Bool /// Sets the focused selection. Returns false when the app does not accept it. func setSelectedText(pid: pid_t, to text: String) async -> Bool } /// Posts the synthetic paste. Tests replace it with a fake. public protocol EventPosting: Sendable { /// Posts ⌘V to a PID. Returns false when events cannot be created. func postPaste(to pid: pid_t) -> Bool } /// The production Accessibility editor. AX calls run on this actor, never on the main actor. public actor AXTextEditor: AccessibilityTextEditing { /// Creates the editor. public init() {} public func isTrusted() -> Bool { AXIsProcessTrusted() } public func selectedText(pid: pid_t) -> String? { guard let focused = focusedElement(pid: pid) else { return nil } var value: CFTypeRef? guard AXUIElementCopyAttributeValue( focused, kAXSelectedTextAttribute as CFString, &value ) == .success else { return nil } return value as? String } public func isSecureField(pid: pid_t) -> Bool { guard let focused = focusedElement(pid: pid) else { return false } if attribute(focused, kAXSubroleAttribute) == "AXSecureTextField" { return true } return attribute(focused, kAXRoleAttribute) == "AXSecureTextField" } private func attribute(_ element: AXUIElement, _ name: String) -> String? { var value: CFTypeRef? guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { return nil } return value as? String } public func setSelectedText(pid: pid_t, to text: String) async -> Bool { guard let focused = focusedElement(pid: pid) else { return false } return AXUIElementSetAttributeValue( focused, kAXSelectedTextAttribute as CFString, text as CFTypeRef ) == .success } private func focusedElement(pid: pid_t) -> AXUIElement? { let application = AXUIElementCreateApplication(pid) var value: CFTypeRef? guard AXUIElementCopyAttributeValue( application, kAXFocusedUIElementAttribute as CFString, &value ) == .success, let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil } return unsafeDowncast(value, to: AXUIElement.self) } } /// The production ⌘V poster. public struct CGEventPoster: EventPosting { /// Creates a poster. public init() {} public func postPaste(to pid: pid_t) -> Bool { guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true), let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false) else { return false } keyDown.flags = .maskCommand keyUp.flags = .maskCommand keyDown.postToPid(pid) keyUp.postToPid(pid) return true } }