-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathXcodeAppInstanceInspector.swift
More file actions
494 lines (433 loc) · 17.5 KB
/
XcodeAppInstanceInspector.swift
File metadata and controls
494 lines (433 loc) · 17.5 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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import AppKit
import AsyncPassthroughSubject
import AXExtension
import AXNotificationStream
import Combine
import Foundation
import Status
public final class XcodeAppInstanceInspector: AppInstanceInspector {
public struct AXNotification {
public var kind: AXNotificationKind
public var element: AXUIElement
}
public enum AXNotificationKind {
case titleChanged
case applicationActivated
case applicationDeactivated
case moved
case resized
case mainWindowChanged
case focusedWindowChanged
case focusedUIElementChanged
case windowMoved
case windowResized
case windowMiniaturized
case windowDeminiaturized
case created
case uiElementDestroyed
case xcodeCompletionPanelChanged
public init?(rawValue: String) {
switch rawValue {
case kAXTitleChangedNotification:
self = .titleChanged
case kAXApplicationActivatedNotification:
self = .applicationActivated
case kAXApplicationDeactivatedNotification:
self = .applicationDeactivated
case kAXMovedNotification:
self = .moved
case kAXResizedNotification:
self = .resized
case kAXMainWindowChangedNotification:
self = .mainWindowChanged
case kAXFocusedWindowChangedNotification:
self = .focusedWindowChanged
case kAXFocusedUIElementChangedNotification:
self = .focusedUIElementChanged
case kAXWindowMovedNotification:
self = .windowMoved
case kAXWindowResizedNotification:
self = .windowResized
case kAXWindowMiniaturizedNotification:
self = .windowMiniaturized
case kAXWindowDeminiaturizedNotification:
self = .windowDeminiaturized
case kAXCreatedNotification:
self = .created
case kAXUIElementDestroyedNotification:
self = .uiElementDestroyed
default:
return nil
}
}
}
@Published public fileprivate(set) var focusedWindow: XcodeWindowInspector?
@Published public fileprivate(set) var documentURL: URL? = nil
@Published public fileprivate(set) var workspaceURL: URL? = nil
@Published public fileprivate(set) var projectRootURL: URL? = nil
@Published public fileprivate(set) var workspaces = [WorkspaceIdentifier: Workspace]()
@Published public private(set) var completionPanel: AXUIElement?
public var realtimeWorkspaces: [WorkspaceIdentifier: WorkspaceInfo] {
updateWorkspaceInfo()
return workspaces.mapValues(\.info)
}
public let axNotifications = AsyncPassthroughSubject<AXNotification>()
public var realtimeDocumentURL: URL? { appElement.realtimeDocumentURL }
public var realtimeWorkspaceURL: URL? {
appElement.realtimeWorkspaceURL
}
public var realtimeProjectURL: URL? {
let workspaceURL = realtimeWorkspaceURL
let documentURL = realtimeDocumentURL
return WorkspaceXcodeWindowInspector.extractProjectURL(
workspaceURL: workspaceURL,
documentURL: documentURL
)
}
var _version: String?
public var version: String? {
if let _version { return _version }
guard let plistPath = runningApplication.bundleURL?
.appendingPathComponent("Contents")
.appendingPathComponent("version.plist")
.path
else { return nil }
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return nil }
var format = PropertyListSerialization.PropertyListFormat.xml
guard let plistDict = try? PropertyListSerialization.propertyList(
from: plistData,
options: .mutableContainersAndLeaves,
format: &format
) as? [String: AnyObject] else { return nil }
let result = plistDict["CFBundleShortVersionString"] as? String
_version = result
return result
}
private var longRunningTasks = Set<Task<Void, Error>>()
private var focusedWindowObservations = Set<AnyCancellable>()
deinit {
axNotifications.finish()
for task in longRunningTasks { task.cancel() }
}
override init(runningApplication: NSRunningApplication) {
super.init(runningApplication: runningApplication)
Task { @XcodeInspectorActor in
observeFocusedWindow()
observeAXNotifications()
try await Task.sleep(nanoseconds: 3_000_000_000)
// Sometimes the focused window may not be ready on app launch.
if !(focusedWindow is WorkspaceXcodeWindowInspector) {
observeFocusedWindow()
}
}
}
@XcodeInspectorActor
func refresh() {
if let focusedWindow = focusedWindow as? WorkspaceXcodeWindowInspector {
focusedWindow.refresh()
} else {
observeFocusedWindow()
}
}
@XcodeInspectorActor
private func observeFocusedWindow() {
if let window = appElement.focusedWindow {
if window.identifier == "Xcode.WorkspaceWindow" {
let window = WorkspaceXcodeWindowInspector(
app: runningApplication,
uiElement: window,
axNotifications: axNotifications
)
focusedWindowObservations.forEach { $0.cancel() }
focusedWindowObservations.removeAll()
Task { @MainActor in
focusedWindow = window
documentURL = window.documentURL
workspaceURL = window.workspaceURL
projectRootURL = window.projectRootURL
}
window.$documentURL
.filter { $0 != .init(fileURLWithPath: "/") }
.receive(on: DispatchQueue.main)
.sink { [weak self] url in
self?.documentURL = url
}.store(in: &focusedWindowObservations)
window.$workspaceURL
.filter { $0 != .init(fileURLWithPath: "/") }
.receive(on: DispatchQueue.main)
.sink { [weak self] url in
self?.workspaceURL = url
}.store(in: &focusedWindowObservations)
window.$projectRootURL
.filter { $0 != .init(fileURLWithPath: "/") }
.receive(on: DispatchQueue.main)
.sink { [weak self] url in
self?.projectRootURL = url
}.store(in: &focusedWindowObservations)
} else {
let window = XcodeWindowInspector(uiElement: window)
Task { @MainActor in
focusedWindow = window
}
}
} else {
Task { @MainActor in
focusedWindow = nil
}
}
}
@XcodeInspectorActor
func observeAXNotifications() {
longRunningTasks.forEach { $0.cancel() }
longRunningTasks = []
let axNotificationStream = AXNotificationStream(
app: runningApplication,
notificationNames:
kAXTitleChangedNotification,
kAXApplicationActivatedNotification,
kAXApplicationDeactivatedNotification,
kAXMovedNotification,
kAXResizedNotification,
kAXMainWindowChangedNotification,
kAXFocusedWindowChangedNotification,
kAXFocusedUIElementChangedNotification,
kAXWindowMovedNotification,
kAXWindowResizedNotification,
kAXWindowMiniaturizedNotification,
kAXWindowDeminiaturizedNotification,
kAXCreatedNotification,
kAXUIElementDestroyedNotification
)
let observeAXNotificationTask = Task { @XcodeInspectorActor [weak self] in
var updateWorkspaceInfoTask: Task<Void, Error>?
for await notification in axNotificationStream {
guard let self else { return }
try Task.checkCancellation()
await Task.yield()
guard let event = AXNotificationKind(rawValue: notification.name) else {
continue
}
self.axNotifications.send(.init(kind: event, element: notification.element))
if event == .focusedWindowChanged {
observeFocusedWindow()
}
if event == .focusedUIElementChanged || event == .applicationDeactivated {
updateWorkspaceInfoTask?.cancel()
updateWorkspaceInfoTask = Task { [weak self] in
guard let self else { return }
try await Task.sleep(nanoseconds: 2_000_000_000)
try Task.checkCancellation()
self.updateWorkspaceInfo()
}
}
if event == .created || event == .uiElementDestroyed {
let isCompletionPanel = {
notification.element.identifier == "_XC_COMPLETION_TABLE_"
|| notification.element.firstChild { element in
element.identifier == "_XC_COMPLETION_TABLE_"
} != nil
}
switch event {
case .created:
if isCompletionPanel() {
await MainActor.run {
self.completionPanel = notification.element
self.completionPanel?.setMessagingTimeout(1)
self.axNotifications.send(.init(
kind: .xcodeCompletionPanelChanged,
element: notification.element
))
}
}
case .uiElementDestroyed:
if isCompletionPanel() {
await MainActor.run {
self.completionPanel = nil
self.axNotifications.send(.init(
kind: .xcodeCompletionPanelChanged,
element: notification.element
))
}
}
default: continue
}
}
}
}
longRunningTasks.insert(observeAXNotificationTask)
updateWorkspaceInfo()
}
}
// MARK: - Workspace Info
extension XcodeAppInstanceInspector {
public enum WorkspaceIdentifier: Hashable {
case url(URL)
case unknown
}
public class Workspace {
public let element: AXUIElement
public var info: WorkspaceInfo
/// When a window is closed, all it's properties will be set to nil.
/// Since we can't get notification for window closing,
/// we will use it to check if the window is closed.
var isValid: Bool {
element.parent != nil
}
init(element: AXUIElement) {
self.element = element
info = .init(tabs: [])
}
}
public struct WorkspaceInfo {
public let tabs: Set<String>
public func combined(with info: WorkspaceInfo) -> WorkspaceInfo {
return .init(tabs: tabs.union(info.tabs))
}
}
func updateWorkspaceInfo() {
let workspaceInfoInVisibleSpace = Self.fetchVisibleWorkspaces(runningApplication)
let workspaces = Self.updateWorkspace(workspaces, with: workspaceInfoInVisibleSpace)
Task { @MainActor in
self.workspaces = workspaces
}
}
/// Use the project path as the workspace identifier.
static func workspaceIdentifier(_ window: AXUIElement) -> WorkspaceIdentifier {
if let url = WorkspaceXcodeWindowInspector.extractWorkspaceURL(windowElement: window) {
return WorkspaceIdentifier.url(url)
}
return WorkspaceIdentifier.unknown
}
/// With Accessibility API, we can ONLY get the information of visible windows.
static func fetchVisibleWorkspaces(
_ app: NSRunningApplication
) -> [WorkspaceIdentifier: Workspace] {
let app = AXUIElementCreateApplication(app.processIdentifier)
let windows = app.windows.filter { $0.identifier == "Xcode.WorkspaceWindow" }
var dict = [WorkspaceIdentifier: Workspace]()
for window in windows {
let workspaceIdentifier = workspaceIdentifier(window)
var traverseCount = 0
let tabs = {
guard let editArea = window.firstChild(where: { $0.description == "editor area" })
else { return Set<String>() }
var allTabs = Set<String>()
let tabBars = editArea.tabBars
for tabBar in tabBars {
tabBar.traverse { element, _ in
traverseCount += 1
if element.roleDescription == "tab" {
allTabs.insert(element.title)
return .skipDescendants
}
return .continueSearching
}
}
return allTabs
}()
let workspace = Workspace(element: window)
workspace.info = .init(tabs: tabs)
dict[workspaceIdentifier] = workspace
}
return dict
}
static func updateWorkspace(
_ old: [WorkspaceIdentifier: Workspace],
with new: [WorkspaceIdentifier: Workspace]
) -> [WorkspaceIdentifier: Workspace] {
var updated = old.filter { $0.value.isValid } // remove closed windows.
for (identifier, workspace) in new {
if let existed = updated[identifier] {
existed.info = workspace.info
} else {
updated[identifier] = workspace
}
}
return updated
}
// The screen that Xcode App located at
public var appScreen: NSScreen? {
appElement.focusedWindow?.maxIntersectionScreen
}
}
// MARK: - Focused Element
extension XcodeAppInstanceInspector {
public func getFocusedElement(shouldRecordStatus: Bool = false) -> AXUIElement? {
do {
let focused: AXUIElement = try self.appElement.copyValue(key: kAXFocusedUIElementAttribute)
if shouldRecordStatus {
Task { await Status.shared.updateAXStatus(.granted) }
}
return focused
} catch AXError.apiDisabled {
if shouldRecordStatus {
Task { await Status.shared.updateAXStatus(.notGranted) }
}
} catch {
// ignore
}
return nil
}
}
public extension AXUIElement {
var tabBars: [AXUIElement] {
// Searching by traversing with AXUIElement is (Xcode) resource consuming, we should skip
// as much as possible!
guard let editArea: AXUIElement = {
if description == "editor area" { return self }
return firstChild(where: { $0.description == "editor area" })
}() else { return [] }
var tabBars = [AXUIElement]()
editArea.traverse { element, _ in
let description = element.description
if description == "Tab Bar" {
element.traverse { element, _ in
if element.description == "tab bar" {
tabBars.append(element)
return .stopSearching
}
return .continueSearching
}
return .skipDescendantsAndSiblings
}
if element.identifier == "editor context" {
return .skipDescendantsAndSiblings
}
if element.isNonNavigatorSourceEditor {
return .skipDescendantsAndSiblings
}
if description == "Code Coverage Ribbon" {
return .skipDescendants
}
if description == "Debug Area" {
return .skipDescendants
}
if description == "debug bar" {
return .skipDescendants
}
return .continueSearching
}
return tabBars
}
var maxIntersectionScreen: NSScreen? {
guard let rect = rect else { return nil }
var bestScreen: NSScreen?
var maxIntersectionArea: CGFloat = 0
for screen in NSScreen.screens {
// Skip screens that are in full-screen mode
// Full-screen detection: visible frame equals total frame (no menu bar/dock)
if screen.frame == screen.visibleFrame {
continue
}
// Calculate intersection area between Xcode frame and screen frame
let intersection = rect.intersection(screen.frame)
let intersectionArea = intersection.width * intersection.height
// Update best screen if this intersection is larger
if intersectionArea > maxIntersectionArea {
maxIntersectionArea = intersectionArea
bestScreen = screen
}
}
return bestScreen
}
}