forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAXHelper.swift
More file actions
70 lines (63 loc) · 2.14 KB
/
AXHelper.swift
File metadata and controls
70 lines (63 loc) · 2.14 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
import XPCShared
import XcodeInspector
import AppKit
public struct AXHelper {
public init() {}
/// When Xcode commands are not available, we can fallback to directly
/// set the value of the editor with Accessibility API.
public func injectUpdatedCodeWithAccessibilityAPI(
_ result: UpdatedContent,
focusElement: AXUIElement,
onSuccess: (() -> Void)? = nil,
onError: (() -> Void)? = nil
) throws {
let oldPosition = focusElement.selectedTextRange
let oldScrollPosition = focusElement.parent?.verticalScrollBar?.doubleValue
let error = AXUIElementSetAttributeValue(
focusElement,
kAXValueAttribute as CFString,
result.content as CFTypeRef
)
if error != AXError.success {
if let onError = onError {
onError()
}
}
// recover selection range
if let selection = result.newSelection {
var range = SourceEditor.convertCursorRangeToRange(selection, in: result.content)
if let value = AXValueCreate(.cfRange, &range) {
AXUIElementSetAttributeValue(
focusElement,
kAXSelectedTextRangeAttribute as CFString,
value
)
}
} else if let oldPosition {
var range = CFRange(
location: oldPosition.lowerBound,
length: 0
)
if let value = AXValueCreate(.cfRange, &range) {
AXUIElementSetAttributeValue(
focusElement,
kAXSelectedTextRangeAttribute as CFString,
value
)
}
}
// recover scroll position
if let oldScrollPosition,
let scrollBar = focusElement.parent?.verticalScrollBar
{
AXUIElementSetAttributeValue(
scrollBar,
kAXValueAttribute as CFString,
oldScrollPosition as CFTypeRef
)
}
if let onSuccess = onSuccess {
onSuccess()
}
}
}