| 1 | import AppKit |
| 2 | import ApplicationServices |
| 3 | import ScreenCaptureKit |
| 4 | |
| 5 | struct MacInputWindow { |
| 6 | let app: AXUIElement |
| 7 | let focused: AXUIElement |
| 8 | let pid: pid_t |
| 9 | let origin: CGPoint |
| 10 | let extent: CGSize |
| 11 | } |
| 12 | |
| 13 | @MainActor |
| 14 | func checkedMacInputWindow(_ input: Request, window: SCWindow) throws -> MacInputWindow { |
| 15 | guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") } |
| 16 | guard let pid = window.owningApplication?.processID, input.pid == pid, input.window == window.windowID, |
| 17 | NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { throw Failure(7, "window_changed") } |
| 18 | let app = AXUIElementCreateApplication(pid) |
| 19 | AXUIElementSetMessagingTimeout(app, 1) |
| 20 | var value: CFTypeRef? |
| 21 | guard AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute as CFString, &value) == .success, |
| 22 | let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { throw Failure(7, "window_changed") } |
| 23 | let focused = value as! AXUIElement |
| 24 | var position: CFTypeRef?, size: CFTypeRef? |
| 25 | var origin = CGPoint.zero, extent = CGSize.zero |
| 26 | guard AXUIElementCopyAttributeValue(focused, kAXPositionAttribute as CFString, &position) == .success, |
| 27 | AXUIElementCopyAttributeValue(focused, kAXSizeAttribute as CFString, &size) == .success, |
| 28 | let position, let size, CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(size) == AXValueGetTypeID(), |
| 29 | AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent) else { |
| 30 | throw Failure(7, "window_changed") |
| 31 | } |
| 32 | let tolerance: CGFloat = input.action == "project-click" ? 24 : 1 |
| 33 | guard abs(origin.x - window.frame.minX) < tolerance, abs(origin.y - window.frame.minY) < tolerance, |
| 34 | abs(extent.width - window.frame.width) < tolerance, abs(extent.height - window.frame.height) < tolerance else { |
| 35 | throw Failure(7, "window_changed") |
| 36 | } |
| 37 | return MacInputWindow(app: app, focused: focused, pid: pid, origin: origin, extent: extent) |
| 38 | } |
| 39 | |
| 40 | @MainActor |
| 41 | func macPressTarget(_ target: MacInputWindow, point: CGPoint) -> AXUIElement? { |
| 42 | var hit: AXUIElement? |
| 43 | guard AXUIElementCopyElementAtPosition(target.app, Float(point.x), Float(point.y), &hit) == .success else { return nil } |
| 44 | var node = hit |
| 45 | for _ in 0..<8 { |
| 46 | guard let current = node, !CFEqual(current, target.focused) else { break } |
| 47 | func attribute(_ name: String) -> CFTypeRef? { |
| 48 | var value: CFTypeRef? |
| 49 | return AXUIElementCopyAttributeValue(current, name as CFString, &value) == .success ? value : nil |
| 50 | } |
| 51 | var pid: pid_t = 0 |
| 52 | guard AXUIElementGetPid(current, &pid) == .success, pid == target.pid, |
| 53 | let owner = attribute(kAXWindowAttribute), CFEqual(owner, target.focused) else { break } |
| 54 | if let role = attribute(kAXRoleAttribute) as? String, [kAXButtonRole, "AXLink"].contains(role) { |
| 55 | var actions: CFArray? |
| 56 | if AXUIElementCopyActionNames(current, &actions) == .success, |
| 57 | (actions as? [String])?.contains(kAXPressAction) == true { return current } |
| 58 | } |
| 59 | guard let parent = attribute(kAXParentAttribute), CFGetTypeID(parent) == AXUIElementGetTypeID() else { break } |
| 60 | node = (parent as! AXUIElement) |
| 61 | } |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | |
| 66 | @MainActor |
| 67 | final class MacWindowInputSession { |
| 68 | private static var pointerOwner: UUID? |
| 69 | private static var keyOwners: [UInt16: UUID] = [:] |
| 70 | private let id = UUID() |
| 71 | private let source = CGEventSource(stateID: .privateState) |
| 72 | private var keys: [UInt16: (pid_t, CGWindowID)] = [:] |
| 73 | private var pressedCodes: [String: UInt16] = [:] |
| 74 | private var buttons: [Int: (pid_t, CGWindowID, CGPoint, Int)] = [:] |
| 75 | private var press: (element: AXUIElement, down: CGEvent, point: CGPoint, pid: pid_t, window: CGWindowID)? |
| 76 | private var focusedElement: AXUIElement? |
| 77 | private var focusedTarget = "" |
| 78 | private var focusContext = "" |
| 79 | private var composition: (id: String, context: String, sequence: Int, updated: Date)? |
| 80 | |
| 81 | static func requirePointerOwner(_ session: MacWindowInputSession?) throws { |
| 82 | if let owner = pointerOwner, owner != session?.id { throw Failure(8, "input_owned_by_another_view") } |
| 83 | } |
| 84 | |
| 85 | private func flags(_ input: Request) -> CGEventFlags { |
| 86 | var value: CGEventFlags = [] |
| 87 | if input.shift == true { value.insert(.maskShift) } |
| 88 | if input.control == true { value.insert(.maskControl) } |
| 89 | if input.alt == true { value.insert(.maskAlternate) } |
| 90 | if input.command == true { value.insert(.maskCommand) } |
| 91 | return value |
| 92 | } |
| 93 | |
| 94 | func key(_ input: Request, target: MacInputWindow, window: SCWindow) throws { |
| 95 | try Self.requirePointerOwner(self) |
| 96 | if let pending = press { |
| 97 | guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") } |
| 98 | pending.down.postToPid(target.pid) |
| 99 | press = nil |
| 100 | } |
| 101 | guard let down = input.down, let name = input.code, let key = input.key else { throw Failure(8, "invalid_input") } |
| 102 | let mapped = MacKeyboard.virtualKey(code: name, key: key, shortcut: input.command == true || input.control == true || input.alt == true) |
| 103 | guard let code = pressedCodes[name] ?? (down ? mapped : nil) else { |
| 104 | if down { throw Failure(8, "invalid_input") } |
| 105 | return |
| 106 | } |
| 107 | guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") } |
| 108 | if let owner = Self.keyOwners[code], owner != id { throw Failure(8, "input_owned_by_another_view") } |
| 109 | if !down && keys[code] == nil { return } |
| 110 | event.flags = flags(input) |
| 111 | event.setIntegerValueField(.keyboardEventAutorepeat, value: down && keys[code] != nil ? 1 : 0) |
| 112 | if down && input.command != true && input.control != true && key.count == 1 { |
| 113 | let text = Array(key.utf16) |
| 114 | text.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: text.count, unicodeString: $0.baseAddress) } |
| 115 | } |
| 116 | if down { keys[code] = (target.pid, window.windowID); pressedCodes[name] = code; Self.keyOwners[code] = id } |
| 117 | else { keys.removeValue(forKey: code); pressedCodes.removeValue(forKey: name); Self.keyOwners.removeValue(forKey: code) } |
| 118 | event.postToPid(target.pid) |
| 119 | } |
| 120 | |
| 121 | func pointer(_ input: Request, target: MacInputWindow, window: SCWindow, canvas: ClaudeCanvas?) throws { |
| 122 | try Self.requirePointerOwner(self) |
| 123 | guard let phase = input.phase, ["down", "move", "up"].contains(phase), |
| 124 | let x = input.x, let y = input.y, x.isFinite, y.isFinite, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") } |
| 125 | let crop = canvas?.cropTop ?? 0 |
| 126 | let point = CGPoint(x: target.origin.x + target.extent.width * x, y: target.origin.y + crop + (target.extent.height - crop) * y) |
| 127 | let button = phase == "move" ? buttons.keys.sorted().first : input.button |
| 128 | let types: [NSEvent.EventType] |
| 129 | if phase == "move" { types = [.leftMouseDragged, .otherMouseDragged, .rightMouseDragged] } |
| 130 | else if phase == "down" { types = [.leftMouseDown, .otherMouseDown, .rightMouseDown] } |
| 131 | else { types = [.leftMouseUp, .otherMouseUp, .rightMouseUp] } |
| 132 | if phase != "move" && (button == nil || !(0...2).contains(button!) || !(1...3).contains(input.clicks ?? 0)) { throw Failure(8, "invalid_input") } |
| 133 | if phase == "up", let button, buttons[button] == nil { return } |
| 134 | if let pending = press { |
| 135 | guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") } |
| 136 | if phase == "move" && abs(point.x - pending.point.x) < 4 && abs(point.y - pending.point.y) < 4 { return } |
| 137 | press = nil |
| 138 | if phase == "up", button == 0, flags(input).isEmpty, |
| 139 | let hit = macPressTarget(target, point: point), CFEqual(hit, pending.element) { |
| 140 | buttons.removeValue(forKey: 0) |
| 141 | if buttons.isEmpty { Self.pointerOwner = nil } |
| 142 | guard AXUIElementPerformAction(hit, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") } |
| 143 | return |
| 144 | } |
| 145 | pending.down.postToPid(target.pid) |
| 146 | } |
| 147 | let type = button.map { types[$0] } ?? .mouseMoved |
| 148 | let count = input.clicks ?? button.flatMap { buttons[$0]?.3 } ?? 0 |
| 149 | let local = CGPoint(x: point.x - target.origin.x, y: target.extent.height - (point.y - target.origin.y)) |
| 150 | guard let event = NSEvent.mouseEvent(with: type, location: local, modifierFlags: NSEvent.ModifierFlags(rawValue: UInt(flags(input).rawValue)), |
| 151 | timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID), context: nil, |
| 152 | eventNumber: 0, clickCount: count, pressure: phase == "up" ? 0 : 1)?.cgEvent else { throw Failure(8, "input_failed") } |
| 153 | event.location = point |
| 154 | event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID)) |
| 155 | event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID)) |
| 156 | if phase == "down", let button { buttons[button] = (target.pid, window.windowID, point, count); Self.pointerOwner = id } |
| 157 | if phase == "up", let button { buttons.removeValue(forKey: button); if buttons.isEmpty { Self.pointerOwner = nil } } |
| 158 | if phase == "move" { for button in Array(buttons.keys) { buttons[button] = (target.pid, window.windowID, point, count) } } |
| 159 | |
| 160 | |
| 161 | if phase == "down", button == 0, count == 1, buttons.count == 1, flags(input).isEmpty, |
| 162 | let element = macPressTarget(target, point: point) { |
| 163 | press = (element, event, point, target.pid, window.windowID) |
| 164 | return |
| 165 | } |
| 166 | event.postToPid(target.pid) |
| 167 | } |
| 168 | |
| 169 | private func stillOwnsWindow(_ pid: pid_t, _ window: CGWindowID) -> Bool { |
| 170 | guard (try? consoleUser()) != nil else { return false } |
| 171 | let values = CGWindowListCopyWindowInfo(.optionIncludingWindow, window) as? [[String: Any]] |
| 172 | return values?.first?[kCGWindowOwnerPID as String] as? Int32 == pid |
| 173 | } |
| 174 | |
| 175 | func reset() { |
| 176 | for (code, target) in keys { |
| 177 | if stillOwnsWindow(target.0, target.1) { CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: false)?.postToPid(target.0) } |
| 178 | if Self.keyOwners[code] == id { Self.keyOwners.removeValue(forKey: code) } |
| 179 | } |
| 180 | for (button, target) in buttons where !(button == 0 && press != nil) && stillOwnsWindow(target.0, target.1) { |
| 181 | let type: CGEventType = button == 0 ? .leftMouseUp : button == 2 ? .rightMouseUp : .otherMouseUp |
| 182 | let mouse: CGMouseButton = button == 0 ? .left : button == 2 ? .right : .center |
| 183 | if let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: target.2, mouseButton: mouse) { |
| 184 | event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(target.1)) |
| 185 | event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(target.1)) |
| 186 | event.postToPid(target.0) |
| 187 | } |
| 188 | } |
| 189 | keys.removeAll(); pressedCodes.removeAll(); buttons.removeAll(); press = nil; composition = nil |
| 190 | if Self.pointerOwner == id { Self.pointerOwner = nil } |
| 191 | } |
| 192 | |
| 193 | func ime(_ input: Request, window: SCWindow, canvas: ClaudeCanvas?, commit: (String) throws -> Void) throws -> [String: Any] { |
| 194 | let mode = input.mode ?? "" |
| 195 | guard ["status", "begin", "update", "commit", "cancel"].contains(mode) else { throw Failure(8, "input_mode_invalid") } |
| 196 | let token = input.session ?? "", sequence = input.sequence ?? 0 |
| 197 | if mode != "status" && (token.count != 32 || token.range(of: "^[a-f0-9]{32}$", options: .regularExpression) == nil || sequence < 0) { throw Failure(8, "input_session_invalid") } |
| 198 | if mode == "cancel" { |
| 199 | if composition?.id == token && sequence > composition!.sequence { composition = nil } |
| 200 | return ["available": false] |
| 201 | } |
| 202 | let target = try checkedMacInputWindow(input, window: window) |
| 203 | func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { |
| 204 | var value: CFTypeRef? |
| 205 | return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil |
| 206 | } |
| 207 | guard let raw = attribute(target.app, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID() else { |
| 208 | composition = nil; focusedElement = nil; return ["available": false] |
| 209 | } |
| 210 | let element = raw as! AXUIElement |
| 211 | var pid: pid_t = 0 |
| 212 | var valueWritable = DarwinBoolean(false), selectionWritable = DarwinBoolean(false) |
| 213 | _ = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &valueWritable) |
| 214 | _ = AXUIElementIsAttributeSettable(element, kAXSelectedTextAttribute as CFString, &selectionWritable) |
| 215 | guard AXUIElementGetPid(element, &pid) == .success, pid == target.pid, |
| 216 | [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(attribute(element, kAXRoleAttribute) as? String ?? ""), |
| 217 | valueWritable.boolValue || selectionWritable.boolValue, |
| 218 | let owner = attribute(element, kAXWindowAttribute), CFEqual(owner, target.focused), |
| 219 | (attribute(element, kAXEnabledAttribute) as? Bool) != false else { composition = nil; return ["available": false] } |
| 220 | let identity = "\(window.windowID):\(target.pid):\(input.geometry ?? "")" |
| 221 | if focusedElement == nil || !CFEqual(focusedElement!, element) || focusedTarget != identity { |
| 222 | focusedElement = element; focusedTarget = identity; focusContext = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased(); composition = nil |
| 223 | } |
| 224 | var rect = CGRect.zero |
| 225 | var exact = false |
| 226 | if let range = attribute(element, kAXSelectedTextRangeAttribute), CFGetTypeID(range) == AXValueGetTypeID() { |
| 227 | var selected = CFRange() |
| 228 | if AXValueGetValue(range as! AXValue, .cfRange, &selected) { |
| 229 | selected.location += selected.length; selected.length = 0 |
| 230 | var bounds: CFTypeRef? |
| 231 | if let parameter = AXValueCreate(.cfRange, &selected), |
| 232 | AXUIElementCopyParameterizedAttributeValue(element, kAXBoundsForRangeParameterizedAttribute as CFString, parameter, &bounds) == .success, |
| 233 | let bounds, CFGetTypeID(bounds) == AXValueGetTypeID() { exact = AXValueGetValue(bounds as! AXValue, .cgRect, &rect) } |
| 234 | } |
| 235 | } |
| 236 | if !exact || rect.height <= 0 { |
| 237 | var point = CGPoint.zero, size = CGSize.zero |
| 238 | guard let position = attribute(element, kAXPositionAttribute), let extent = attribute(element, kAXSizeAttribute), |
| 239 | CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(), |
| 240 | AXValueGetValue(position as! AXValue, .cgPoint, &point), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return ["available": false] } |
| 241 | rect = CGRect(origin: point, size: CGSize(width: 1, height: min(24, size.height))) |
| 242 | } |
| 243 | if let current = composition, current.context != focusContext || Date().timeIntervalSince(current.updated) > 30 { composition = nil } |
| 244 | let result: [String: Any] = ["available": true, "context": focusContext, "preedit_supported": false, |
| 245 | "password": attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole, |
| 246 | "rect": [rect.minX - target.origin.x, rect.minY - target.origin.y - (canvas?.cropTop ?? 0), max(1, rect.width), max(1, rect.height)], |
| 247 | "width": target.extent.width, "height": target.extent.height - (canvas?.cropTop ?? 0), "caret_exact": exact] |
| 248 | if mode == "status" { |
| 249 | if composition?.id == token { composition?.updated = Date() } |
| 250 | return result |
| 251 | } |
| 252 | if mode == "begin" { |
| 253 | guard input.context == focusContext else { return ["available": false] } |
| 254 | composition = (token, focusContext, sequence, Date()); return result |
| 255 | } |
| 256 | guard let current = composition, current.id == token, sequence > current.sequence else { return ["available": false] } |
| 257 | guard (input.text ?? "").utf8.count <= 8192 else { throw Failure(8, "input_text_limit") } |
| 258 | if mode == "commit" { try commit(input.text ?? ""); composition = nil } |
| 259 | else { composition = (token, focusContext, sequence, Date()) } |
| 260 | return result |
| 261 | } |
| 262 | } |