-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
SBShortcuts.swift
63 lines (55 loc) · 1.79 KB
/
SBShortcuts.swift
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
import Cocoa
import ScriptingBridge
enum SBShortcutsError: Error {
case unableToCreateApplication
case unableToGetShortcuts
case unableToCreateShortcut
case unableToOpenShortcut
}
// Inspiration for this implementation is credited to https://github.com/swiftbar/SwiftBar 👏
final class SBShortcuts {
static func getShortcuts() throws -> [Shortcut] {
guard let application: SBApp = SBApplication(bundleIdentifier: "com.apple.shortcuts.events") else {
throw SBShortcutsError.unableToCreateApplication
}
guard let sbShortcuts = application.shortcuts?.get() else {
throw SBShortcutsError.unableToGetShortcuts
}
var shortcuts = [Shortcut]()
for shortcut in sbShortcuts {
guard let ref = shortcut as? SBShortcut,
let name = ref.name else { continue }
let shortcut = Shortcut(name: name)
shortcuts.append(shortcut)
}
return shortcuts
}
static func openShortcut(_ name: String) throws {
var components = URLComponents()
components.scheme = "shortcuts"
components.host = "open-shortcut"
components.queryItems = [
URLQueryItem(name: "name", value: name),
]
guard let url = components.url else {
throw SBShortcutsError.unableToOpenShortcut
}
NSWorkspace.shared.open(url)
}
static func createShortcut() throws {
guard let url = URL(string: "shortcuts://create-shortcut") else {
throw SBShortcutsError.unableToOpenShortcut
}
NSWorkspace.shared.open(url)
}
}
@objc fileprivate protocol SBApp {
@objc optional var shortcuts: SBElementArray { get }
}
extension SBApplication: SBApp { }
extension SBObject: SBShortcut { }
@objc protocol SBShortcut {
@objc optional var id: String { get }
@objc optional var name: String { get }
@objc optional func run(withInput: Any?) -> Any?
}