forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAXNotificationStream.swift
More file actions
171 lines (156 loc) · 6.18 KB
/
AXNotificationStream.swift
File metadata and controls
171 lines (156 loc) · 6.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import AppKit
import ApplicationServices
import Foundation
import Logger
import Preferences
import Status
public final class AXNotificationStream: AsyncSequence {
public typealias Stream = AsyncStream<Element>
public typealias Continuation = Stream.Continuation
public typealias AsyncIterator = Stream.AsyncIterator
public typealias Element = (name: String, element: AXUIElement, info: CFDictionary)
private var continuation: Continuation
private let stream: Stream
private let file: StaticString
private let line: UInt
private let function: StaticString
public func makeAsyncIterator() -> Stream.AsyncIterator {
stream.makeAsyncIterator()
}
deinit {
continuation.finish()
}
public convenience init(
app: NSRunningApplication,
element: AXUIElement? = nil,
notificationNames: String...,
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function
) {
self.init(
app: app,
element: element,
notificationNames: notificationNames,
file: file,
line: line,
function: function
)
}
public init(
app: NSRunningApplication,
element: AXUIElement? = nil,
notificationNames: [String],
file: StaticString = #file,
line: UInt = #line,
function: StaticString = #function
) {
self.file = file
self.line = line
self.function = function
let mode: CFRunLoopMode = UserDefaults.shared
.value(for: \.observeToAXNotificationWithDefaultMode) ? .defaultMode : .commonModes
let runLoop: CFRunLoop = CFRunLoopGetMain()
var cont: Continuation!
stream = Stream { continuation in
cont = continuation
}
continuation = cont
var observer: AXObserver?
func callback(
observer: AXObserver,
element: AXUIElement,
notificationName: CFString,
userInfo: CFDictionary,
pointer: UnsafeMutableRawPointer?
) {
guard let pointer = pointer?.assumingMemoryBound(to: Continuation.self)
else { return }
pointer.pointee.yield((notificationName as String, element, userInfo))
}
_ = AXObserverCreateWithInfoCallback(
app.processIdentifier,
callback,
&observer
)
guard let observer else {
continuation.finish()
return
}
let observingElement = element ?? AXUIElementCreateApplication(app.processIdentifier)
continuation.onTermination = { @Sendable _ in
for name in notificationNames {
AXObserverRemoveNotification(observer, observingElement, name as CFString)
}
CFRunLoopRemoveSource(
runLoop,
AXObserverGetRunLoopSource(observer),
mode
)
}
Task { @MainActor [weak self] in
CFRunLoopAddSource(
runLoop,
AXObserverGetRunLoopSource(observer),
mode
)
var pendingRegistrationNames = Set(notificationNames)
var retry = 0
var shouldLogAXDisabledEvent: Bool = true
while !pendingRegistrationNames.isEmpty, retry < 100 {
guard let self else { return }
retry += 1
for name in notificationNames {
await Task.yield()
let e = withUnsafeMutablePointer(to: &self.continuation) { pointer in
AXObserverAddNotification(
observer,
observingElement,
name as CFString,
pointer
)
}
switch e {
case .success:
shouldLogAXDisabledEvent = true
pendingRegistrationNames.remove(name)
await Status.shared.updateAXStatus(.granted)
case .actionUnsupported:
Logger.service.error("AXObserver: Action unsupported: \(name)")
pendingRegistrationNames.remove(name)
case .apiDisabled:
if shouldLogAXDisabledEvent { // Avoid keeping log AX disabled too many times
shouldLogAXDisabledEvent = false
Logger.service
.error("AXObserver: Accessibility API disabled, will try again later")
}
retry -= 1
await Status.shared.updateAXStatus(.notGranted)
case .invalidUIElement:
Logger.service
.error("AXObserver: Invalid UI element, notification name \(name)")
pendingRegistrationNames.remove(name)
case .invalidUIElementObserver:
Logger.service.error("AXObserver: Invalid UI element observer")
pendingRegistrationNames.remove(name)
case .cannotComplete:
Logger.service
.error("AXObserver: Failed to observe \(name), will try again later")
case .notificationUnsupported:
Logger.service.error("AXObserver: Notification unsupported: \(name)")
pendingRegistrationNames.remove(name)
case .notificationAlreadyRegistered:
Logger.service.info("AXObserver: Notification already registered: \(name)")
pendingRegistrationNames.remove(name)
default:
Logger.service
.error(
"AXObserver: Unrecognized error \(e) when registering \(name), will try again later"
)
}
}
try await Task.sleep(nanoseconds: 1_500_000_000)
}
}
}
}