forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXcodeInspector+TriggerCommand.swift
More file actions
142 lines (130 loc) · 4.98 KB
/
XcodeInspector+TriggerCommand.swift
File metadata and controls
142 lines (130 loc) · 4.98 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
import AppKit
import AXExtension
import Foundation
import Logger
public extension XcodeAppInstanceInspector {
func triggerCopilotCommand(name: String, activateXcode: Bool = true) async throws {
let bundleName = Bundle.main
.object(forInfoDictionaryKey: "EXTENSION_BUNDLE_NAME") as! String
try await triggerMenuItem(path: ["Editor", bundleName, name], activateXcode: activateXcode)
}
}
public extension AppInstanceInspector {
@MainActor
func triggerMenuItem(path: [String], activateXcode: Bool) async throws {
guard !path.isEmpty else { return }
struct CantRunCommand: Error, LocalizedError {
let path: [String]
var errorDescription: String? {
"Can't run command \(path.joined(separator: "/"))."
}
}
if activateXcode {
if !runningApplication.activate() {
throw CantRunCommand(path: path)
}
} else {
if !runningApplication.isActive {
throw CantRunCommand(path: path)
}
}
await Task.yield()
if UserDefaults.shared.value(for: \.triggerActionWithAccessibilityAPI) {
let app = AXUIElementCreateApplication(runningApplication.processIdentifier)
guard let menuBar = app.menuBar else { throw CantRunCommand(path: path) }
var path = path
var currentMenu = menuBar
while !path.isEmpty {
let item = path.removeFirst()
if path.isEmpty, let button = currentMenu.child(title: item, role: "AXMenuItem") {
let error = AXUIElementPerformAction(button, kAXPressAction as CFString)
if error != AXError.success {
Logger.service.error("""
Trigger menu item \(path.joined(separator: "/")) failed: \
\(error.localizedDescription)
""")
throw error
} else {
return
}
} else if let menu = currentMenu.child(title: item) {
currentMenu = menu
} else {
throw CantRunCommand(path: path)
}
}
} else {
guard path.count >= 2 else { throw CantRunCommand(path: path) }
let clickTask = {
var path = path
let button = path.removeLast()
let menuBarItem = path.removeFirst()
let list = path
.reversed()
.map { "menu 1 of menu item \"\($0)\"" }
.joined(separator: " of ")
return """
click menu item "\(button)" of \(list) \
of menu bar item "\(menuBarItem)" \
of menu bar 1
"""
}()
/// check if menu is open, if not, click the menu item.
let appleScript = """
tell application "System Events"
set theprocs to every process whose unix id is \
\(runningApplication.processIdentifier)
repeat with proc in theprocs
tell proc
repeat with theMenu in menus of menu bar 1
set theValue to value of attribute "AXVisibleChildren" of theMenu
if theValue is not {} then
return
end if
end repeat
\(clickTask)
end tell
end repeat
end tell
"""
do {
try await runAppleScript(appleScript)
} catch {
Logger.service.error("""
Trigger menu item \(path.joined(separator: "/")) failed: \
\(error.localizedDescription)
""")
throw error
}
}
}
}
@discardableResult
func runAppleScript(_ appleScript: String) async throws -> String {
let task = Process()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["-e", appleScript]
let outpipe = Pipe()
task.standardOutput = outpipe
task.standardError = Pipe()
return try await withUnsafeThrowingContinuation { continuation in
do {
task.terminationHandler = { _ in
do {
if let data = try outpipe.fileHandleForReading.readToEnd(),
let content = String(data: data, encoding: .utf8)
{
continuation.resume(returning: content)
return
}
continuation.resume(returning: "")
} catch {
continuation.resume(throwing: error)
}
}
try task.run()
} catch {
continuation.resume(throwing: error)
}
}
}