forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTabToAcceptSuggestion.swift
More file actions
213 lines (189 loc) · 6.87 KB
/
TabToAcceptSuggestion.swift
File metadata and controls
213 lines (189 loc) · 6.87 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
import ActiveApplicationMonitor
import AppKit
import CGEventOverride
import Foundation
import Logger
import Preferences
import SuggestionBasic
import UserDefaultsObserver
import Workspace
import XcodeInspector
final class TabToAcceptSuggestion {
let hook: CGEventHookType = CGEventHook(eventsOfInterest: [.keyDown]) { message in
Logger.service.debug("TabToAcceptSuggestion: \(message)")
}
let workspacePool: WorkspacePool
let acceptSuggestion: () -> Void
let expandSuggestion: () -> Void
let collapseSuggestion: () -> Void
let dismissSuggestion: () -> Void
private var modifierEventMonitor: Any?
private let userDefaultsObserver = UserDefaultsObserver(
object: UserDefaults.shared, forKeyPaths: [
UserDefaultPreferenceKeys().acceptSuggestionWithTab.key,
UserDefaultPreferenceKeys().dismissSuggestionWithEsc.key,
], context: nil
)
private var stoppedForExit = false
struct ObservationKey: Hashable {}
var canTapToAcceptSuggestion: Bool {
UserDefaults.shared.value(for: \.acceptSuggestionWithTab)
}
var canEscToDismissSuggestion: Bool {
UserDefaults.shared.value(for: \.dismissSuggestionWithEsc)
}
@MainActor
func stopForExit() {
stoppedForExit = true
stopObservation()
}
init(
workspacePool: WorkspacePool,
acceptSuggestion: @escaping () -> Void,
dismissSuggestion: @escaping () -> Void,
expandSuggestion: @escaping () -> Void,
collapseSuggestion: @escaping () -> Void
) {
_ = ThreadSafeAccessToXcodeInspector.shared
self.workspacePool = workspacePool
self.acceptSuggestion = acceptSuggestion
self.dismissSuggestion = dismissSuggestion
self.expandSuggestion = expandSuggestion
self.collapseSuggestion = collapseSuggestion
hook.add(
.init(
eventsOfInterest: [.keyDown],
convert: { [weak self] _, _, event in
self?.handleEvent(event) ?? .unchanged
}
),
forKey: ObservationKey()
)
}
func start() {
Task { [weak self] in
for await _ in ActiveApplicationMonitor.shared.createInfoStream() {
guard let self else { return }
try Task.checkCancellation()
Task { @MainActor in
if ActiveApplicationMonitor.shared.activeXcode != nil {
self.startObservation()
} else {
self.stopObservation()
}
}
}
}
userDefaultsObserver.onChange = { [weak self] in
guard let self else { return }
Task { @MainActor in
if self.canTapToAcceptSuggestion {
self.startObservation()
} else {
self.stopObservation()
}
}
}
}
@MainActor
func startObservation() {
guard !stoppedForExit else { return }
guard canTapToAcceptSuggestion else { return }
hook.activateIfPossible()
removeMonitor()
modifierEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { [weak self] event in
self?.handleModifierEvents(event: event)
}
}
@MainActor
func stopObservation() {
hook.deactivate()
removeMonitor()
}
private func removeMonitor() {
if let monitor = modifierEventMonitor {
NSEvent.removeMonitor(monitor)
modifierEventMonitor = nil
}
}
func handleEvent(_ event: CGEvent) -> CGEventManipulation.Result {
let (accept, reason) = Self.shouldAcceptSuggestion(
event: event,
workspacePool: workspacePool,
xcodeInspector: ThreadSafeAccessToXcodeInspector.shared
)
if let reason = reason {
Logger.service.debug("TabToAcceptSuggestion: \(accept ? "" : "not") accepting due to: \(reason)")
}
if accept {
acceptSuggestion()
return .discarded
}
return .unchanged
}
func handleModifierEvents(event: NSEvent) {
if event.modifierFlags.contains(NSEvent.ModifierFlags.option) {
expandSuggestion()
} else {
collapseSuggestion()
}
}
}
extension TabToAcceptSuggestion {
/// Returns whether a given keyboard event should be intercepted and trigger
/// accepting a suggestion.
static func shouldAcceptSuggestion(
event: CGEvent,
workspacePool: WorkspacePool,
xcodeInspector: ThreadSafeAccessToXcodeInspectorProtocol
) -> (accept: Bool, reason: String?) {
let keycode = Int(event.getIntegerValueField(.keyboardEventKeycode))
let tab = 48
guard keycode == tab else { return (false, nil) }
if event.flags.contains(.maskHelp) { return (false, nil) }
if event.flags.contains(.maskShift) { return (false, nil) }
if event.flags.contains(.maskControl) { return (false, nil) }
if event.flags.contains(.maskCommand) { return (false, nil) }
guard xcodeInspector.hasActiveXcode else {
return (false, "No active Xcode")
}
guard xcodeInspector.hasFocusedEditor else {
return (false, "No focused editor")
}
guard let fileURL = xcodeInspector.activeDocumentURL else {
return (false, "No active document")
}
guard let filespace = workspacePool.fetchFilespaceIfExisted(fileURL: fileURL) else {
return (false, "No filespace")
}
if filespace.presentingSuggestion == nil {
return (false, "No suggestion")
}
return (true, nil)
}
}
import Combine
protocol ThreadSafeAccessToXcodeInspectorProtocol {
var activeDocumentURL: URL? {get}
var hasActiveXcode: Bool {get}
var hasFocusedEditor: Bool {get}
}
private class ThreadSafeAccessToXcodeInspector: ThreadSafeAccessToXcodeInspectorProtocol {
static let shared = ThreadSafeAccessToXcodeInspector()
private(set) var activeDocumentURL: URL?
private(set) var hasActiveXcode = false
private(set) var hasFocusedEditor = false
private var cancellable: Set<AnyCancellable> = []
init() {
let inspector = XcodeInspector.shared
inspector.$activeDocumentURL.receive(on: DispatchQueue.main).sink { [weak self] newValue in
self?.activeDocumentURL = newValue
}.store(in: &cancellable)
inspector.$activeXcode.receive(on: DispatchQueue.main).sink { [weak self] newValue in
self?.hasActiveXcode = newValue != nil
}.store(in: &cancellable)
inspector.$focusedEditor.receive(on: DispatchQueue.main).sink { [weak self] newValue in
self?.hasFocusedEditor = newValue != nil
}.store(in: &cancellable)
}
}