-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathXcodeInspector+TriggerCommand.swift
More file actions
207 lines (189 loc) · 7.44 KB
/
XcodeInspector+TriggerCommand.swift
File metadata and controls
207 lines (189 loc) · 7.44 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
import AppKit
import AXExtension
import Foundation
import Logger
import Status
public extension XcodeAppInstanceInspector {
func triggerCopilotCommand(name: String, activateXcode: Bool = true) async throws {
let bundleName = Bundle.main.object(forInfoDictionaryKey: "EXTENSION_BUNDLE_NAME") as! String
let status = await getExtensionStatus(bundleName: bundleName)
guard status == .granted else {
let reason: String
switch status {
case .notGranted:
reason = "No bundle found for \(bundleName)."
case .disabled:
reason = "\(bundleName) is found but disabled."
default:
reason = ""
}
throw CantRunCommand(path: "Editor/\(bundleName)/\(name)", reason: reason)
}
try await triggerMenuItem(path: ["Editor", bundleName, name], activateApp: activateXcode)
}
private func getExtensionStatus(bundleName: String) async -> ExtensionPermissionStatus {
let app = AXUIElementCreateApplication(runningApplication.processIdentifier)
guard let menuBar = app.menuBar,
let editorMenu = menuBar.child(title: "Editor") else {
return .notGranted
}
if let bundleMenuItem = editorMenu.child(title: bundleName, role: "AXMenuItem") {
var enabled: CFTypeRef?
let error = AXUIElementCopyAttributeValue(bundleMenuItem, kAXEnabledAttribute as CFString, &enabled)
if error == .success, let isEnabled = enabled as? Bool {
return isEnabled ? .granted : .disabled
}
return .disabled
}
return .notGranted
}
}
public extension AppInstanceInspector {
struct CantRunCommand: Error, LocalizedError {
let path: String
let reason: String
public var errorDescription: String {
"Can't run command \(path): \(reason)"
}
}
@MainActor
func triggerMenuItem(path: [String], activateApp: Bool) async throws {
let sourcePath = path.joined(separator: "/")
func cantRunCommand(_ reason: String) -> CantRunCommand {
return CantRunCommand(path: sourcePath, reason: reason)
}
guard path.count >= 2 else { throw cantRunCommand("Path too short.") }
if activateApp {
if !runningApplication.activate() {
Logger.service.error("""
Trigger menu item \(sourcePath): \
Xcode not activated.
""")
}
} else {
if !runningApplication.isActive {
Logger.service.error("""
Trigger menu item \(sourcePath): \
Xcode not activated.
""")
}
}
await Task.yield()
if UserDefaults.shared.value(for: \.triggerActionWithAccessibilityAPI) {
let app = AXUIElementCreateApplication(runningApplication.processIdentifier)
guard let menuBar = app.menuBar else {
Logger.service.error("""
Trigger menu item \(sourcePath) failed: \
Menu not found.
""")
throw cantRunCommand("Menu not found.")
}
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 \(sourcePath) failed: \
\(error.localizedDescription)
""")
throw cantRunCommand(error.localizedDescription)
} else {
#if DEBUG
Logger.service.info("""
Trigger menu item \(sourcePath) succeeded.
""")
#endif
return
}
} else if let menu = currentMenu.child(title: item) {
#if DEBUG
Logger.service.info("""
Trigger menu item \(sourcePath): Move to \(item).
""")
#endif
currentMenu = menu
} else {
Logger.service.error("""
Trigger menu item \(sourcePath) failed: \
\(item) is not found.
""")
throw cantRunCommand("\(item) is not found.")
}
}
} else {
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 cantRunCommand(error.localizedDescription)
}
}
}
}
@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)
}
}
}