Skip to content

Commit 585f37b

Browse files
committed
Add acceptSuggestion to pseudo command handler
1 parent 743d322 commit 585f37b

File tree

2 files changed

+64
-2
lines changed

2 files changed

+64
-2
lines changed

Core/Sources/Service/GUI/GraphicalUserInterfaceController.swift.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ public final class GraphicalUserInterfaceController {
3131
}
3232

3333
suggestionWidget.onAcceptButtonTapped = {
34-
Task {
35-
try await Environment.triggerAction("Accept Suggestion")
34+
Task { @ServiceActor in
35+
let handler = PseudoCommandHandler()
36+
await handler.acceptSuggestion()
3637
}
3738
}
3839
}

Core/Sources/Service/SuggestionCommandHandler/PseudoCommandHandler.swift

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,67 @@ struct PseudoCommandHandler {
6868
usesTabsForIndentation: false
6969
))
7070
}
71+
72+
func acceptSuggestion() async {
73+
do {
74+
try await Environment.triggerAction("Accept Suggestion")
75+
return
76+
} catch {
77+
PresentInWindowSuggestionPresenter().presentError(error)
78+
}
79+
guard let xcode = ActiveApplicationMonitor.activeXcode else { return }
80+
let application = AXUIElementCreateApplication(xcode.processIdentifier)
81+
guard let focusElement = application.focusedElement,
82+
focusElement.description == "Source Editor"
83+
else { return }
84+
guard let (content, lines, cursorPosition) = await getFileContent() else {
85+
PresentInWindowSuggestionPresenter().presentErrorMessage("Unable to get file content.")
86+
return
87+
}
88+
let handler = CommentBaseCommandHandler()
89+
do {
90+
guard let result = try await handler.acceptSuggestion(editor: .init(
91+
content: content,
92+
lines: lines,
93+
uti: "",
94+
cursorPosition: cursorPosition,
95+
selections: [],
96+
tabSize: 0,
97+
indentSize: 0,
98+
usesTabsForIndentation: false
99+
)) else { return }
100+
101+
let oldPosition = focusElement.selectedTextRange
102+
103+
let error = AXUIElementSetAttributeValue(
104+
focusElement,
105+
kAXValueAttribute as CFString,
106+
result.content as CFTypeRef
107+
)
108+
109+
if error != AXError.success {
110+
PresentInWindowSuggestionPresenter()
111+
.presentErrorMessage("Fail to set editor content.")
112+
}
113+
114+
if let oldPosition {
115+
var range = CFRange(
116+
location: oldPosition.lowerBound,
117+
length: oldPosition.upperBound
118+
)
119+
if let value = AXValueCreate(.cfRange, &range) {
120+
AXUIElementSetAttributeValue(
121+
focusElement,
122+
kAXSelectedTextRangeAttribute as CFString,
123+
value
124+
)
125+
}
126+
}
127+
128+
} catch {
129+
PresentInWindowSuggestionPresenter().presentError(error)
130+
}
131+
}
71132
}
72133

73134
private extension PseudoCommandHandler {

0 commit comments

Comments
 (0)