forked from sindresorhus/KeyboardShortcuts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecorderCocoa.swift
327 lines (264 loc) · 9.07 KB
/
RecorderCocoa.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
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#if os(macOS)
import AppKit
import Carbon.HIToolbox
extension KeyboardShortcuts {
/**
A `NSView` that lets the user record a keyboard shortcut.
You would usually put this in your settings window.
It automatically prevents choosing a keyboard shortcut that is already taken by the system or by the app's main menu by showing a user-friendly alert to the user.
It takes care of storing the keyboard shortcut in `UserDefaults` for you.
```swift
import AppKit
import KeyboardShortcuts
final class SettingsViewController: NSViewController {
override func loadView() {
view = NSView()
let recorder = KeyboardShortcuts.RecorderCocoa(for: .toggleUnicornMode)
view.addSubview(recorder)
}
}
```
*/
public final class RecorderCocoa: NSSearchField, NSSearchFieldDelegate {
private let minimumWidth = 130.0
private let onChange: ((_ shortcut: Shortcut?) -> Void)?
private var canBecomeKey = false
private var eventMonitor: LocalEventMonitor?
private var shortcutsNameChangeObserver: NSObjectProtocol?
private var windowDidResignKeyObserver: NSObjectProtocol?
private var windowDidBecomeKeyObserver: NSObjectProtocol?
/**
The shortcut name for the recorder.
Can be dynamically changed at any time.
*/
public var shortcutName: Name {
didSet {
guard shortcutName != oldValue else {
return
}
setStringValue(name: shortcutName)
// This doesn't seem to be needed anymore, but I cannot test on older OS versions, so keeping it just in case.
if #unavailable(macOS 12) {
DispatchQueue.main.async { [self] in
// Prevents the placeholder from being cut off.
blur()
}
}
}
}
/// :nodoc:
override public var canBecomeKeyView: Bool { canBecomeKey }
/// :nodoc:
override public var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width = minimumWidth
return size
}
private var cancelButton: NSButtonCell?
private var showsCancelButton: Bool {
get { (cell as? NSSearchFieldCell)?.cancelButtonCell != nil }
set {
(cell as? NSSearchFieldCell)?.cancelButtonCell = newValue ? cancelButton : nil
}
}
/**
- Parameter name: Strongly-typed keyboard shortcut name.
- Parameter onChange: Callback which will be called when the keyboard shortcut is changed/removed by the user. This can be useful when you need more control. For example, when migrating from a different keyboard shortcut solution and you need to store the keyboard shortcut somewhere yourself instead of relying on the built-in storage. However, it's strongly recommended to just rely on the built-in storage when possible.
*/
public required init(
for name: Name,
onChange: ((_ shortcut: Shortcut?) -> Void)? = nil
) {
self.shortcutName = name
self.onChange = onChange
super.init(frame: .zero)
self.delegate = self
self.placeholderString = "record_shortcut".localized
self.alignment = .center
(cell as? NSSearchFieldCell)?.searchButtonCell = nil
self.wantsLayer = true
setContentHuggingPriority(.defaultHigh, for: .vertical)
setContentHuggingPriority(.defaultHigh, for: .horizontal)
// Hide the cancel button when not showing the shortcut so the placeholder text is properly centered. Must be last.
self.cancelButton = (cell as? NSSearchFieldCell)?.cancelButtonCell
setStringValue(name: name)
setUpEvents()
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setStringValue(name: KeyboardShortcuts.Name) {
stringValue = getShortcut(for: shortcutName).map { "\($0)" } ?? ""
// If `stringValue` is empty, hide the cancel button to let the placeholder center.
showsCancelButton = !stringValue.isEmpty
}
private func setUpEvents() {
shortcutsNameChangeObserver = NotificationCenter.default.addObserver(forName: .shortcutByNameDidChange, object: nil, queue: nil) { [weak self] notification in
guard
let self,
let nameInNotification = notification.userInfo?["name"] as? KeyboardShortcuts.Name,
nameInNotification == shortcutName
else {
return
}
setStringValue(name: nameInNotification)
}
}
private func endRecording() {
eventMonitor = nil
placeholderString = "record_shortcut".localized
showsCancelButton = !stringValue.isEmpty
restoreCaret()
KeyboardShortcuts.isPaused = false
}
private func preventBecomingKey() {
canBecomeKey = false
// Prevent the control from receiving the initial focus.
DispatchQueue.main.async { [self] in
canBecomeKey = true
}
}
/// :nodoc:
public func controlTextDidChange(_ object: Notification) {
if stringValue.isEmpty {
saveShortcut(nil)
}
showsCancelButton = !stringValue.isEmpty
if stringValue.isEmpty {
// Hack to ensure that the placeholder centers after the above `showsCancelButton` setter.
focus()
}
}
/// :nodoc:
public func controlTextDidEndEditing(_ object: Notification) {
endRecording()
}
/// :nodoc:
override public func viewDidMoveToWindow() {
guard let window else {
windowDidResignKeyObserver = nil
windowDidBecomeKeyObserver = nil
endRecording()
return
}
// Ensures the recorder stops when the window is hidden.
// This is especially important for Settings windows, which as of macOS 13.5, only hides instead of closes when you click the close button.
windowDidResignKeyObserver = NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: nil) { [weak self] _ in
guard
let self,
let window = self.window
else {
return
}
endRecording()
window.makeFirstResponder(nil)
}
// Ensures the recorder does not receive initial focus when a hidden window becomes unhidden.
windowDidBecomeKeyObserver = NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: nil) { [weak self] _ in
self?.preventBecomingKey()
}
preventBecomingKey()
}
/// :nodoc:
override public func becomeFirstResponder() -> Bool {
let shouldBecomeFirstResponder = super.becomeFirstResponder()
guard shouldBecomeFirstResponder else {
return shouldBecomeFirstResponder
}
placeholderString = "press_shortcut".localized
showsCancelButton = !stringValue.isEmpty
hideCaret()
KeyboardShortcuts.isPaused = true // The position here matters.
eventMonitor = LocalEventMonitor(events: [.keyDown, .leftMouseUp, .rightMouseUp]) { [weak self] event in
guard let self else {
return nil
}
let clickPoint = convert(event.locationInWindow, from: nil)
let clickMargin = 3.0
if
event.type == .leftMouseUp || event.type == .rightMouseUp,
!bounds.insetBy(dx: -clickMargin, dy: -clickMargin).contains(clickPoint)
{
blur()
return event
}
guard event.isKeyEvent else {
return nil
}
if
event.modifiers.isEmpty,
event.specialKey == .tab
{
blur()
// We intentionally bubble up the event so it can focus the next responder.
return event
}
if
event.modifiers.isEmpty,
event.keyCode == kVK_Escape // TODO: Make this strongly typed.
{
blur()
return nil
}
if
event.modifiers.isEmpty,
event.specialKey == .delete
|| event.specialKey == .deleteForward
|| event.specialKey == .backspace
{
clear()
return nil
}
// The “shift” key is not allowed without other modifiers or a function key, since it doesn't actually work.
guard
!event.modifiers.subtracting(.shift).isEmpty
|| event.specialKey?.isFunctionKey == true,
let shortcut = Shortcut(event: event)
else {
NSSound.beep()
return nil
}
if let menuItem = shortcut.takenByMainMenu {
// TODO: Find a better way to make it possible to dismiss the alert by pressing "Enter". How can we make the input automatically temporarily lose focus while the alert is open?
blur()
NSAlert.showModal(
for: window,
title: String.localizedStringWithFormat("keyboard_shortcut_used_by_menu_item".localized, menuItem.title)
)
focus()
return nil
}
if shortcut.isTakenBySystem {
blur()
let modalResponse = NSAlert.showModal(
for: window,
title: "keyboard_shortcut_used_by_system".localized,
// TODO: Add button to offer to open the relevant system settings pane for the user.
message: "keyboard_shortcuts_can_be_changed".localized,
buttonTitles: [
"ok".localized,
"force_use_shortcut".localized
]
)
focus()
// If the user has selected "Use Anyway" in the dialog (the second option), we'll continue setting the keyboard shorcut even though it's reserved by the system.
guard modalResponse == .alertSecondButtonReturn else {
return nil
}
}
stringValue = "\(shortcut)"
showsCancelButton = true
saveShortcut(shortcut)
blur()
return nil
}.start()
return shouldBecomeFirstResponder
}
private func saveShortcut(_ shortcut: Shortcut?) {
setShortcut(shortcut, for: shortcutName)
onChange?(shortcut)
}
}
}
#endif