forked from sindresorhus/KeyboardShortcuts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecorderCocoa.swift
291 lines (234 loc) · 7.91 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
import Cocoa
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 Cocoa
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: Double = 130
private var eventMonitor: LocalEventMonitor?
private let onChange: ((_ shortcut: Shortcut?) -> Void)?
private var observer: NSObjectProtocol?
private var canBecomeKey = false
/**
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() {
observer = 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 == self.shortcutName
else {
return
}
self.setStringValue(name: nameInNotification)
}
}
/// :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) {
eventMonitor = nil
placeholderString = "record_shortcut".localized
showsCancelButton = !stringValue.isEmpty
KeyboardShortcuts.isPaused = false
}
/// :nodoc:
override public func viewDidMoveToWindow() {
guard window != nil else {
return
}
// Prevent the control from receiving the initial focus.
DispatchQueue.main.async { [self] in
canBecomeKey = true
}
}
/// :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 = self.convert(event.locationInWindow, from: nil)
let clickMargin = 3.0
if
event.type == .leftMouseUp || event.type == .rightMouseUp,
!self.bounds.insetBy(dx: -clickMargin, dy: -clickMargin).contains(clickPoint)
{
self.blur()
return event
}
guard event.isKeyEvent else {
return nil
}
if
event.modifiers.isEmpty,
event.specialKey == .tab
{
self.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.
{
self.blur()
return nil
}
if
event.modifiers.isEmpty,
event.specialKey == .delete
|| event.specialKey == .deleteForward
|| event.specialKey == .backspace
{
self.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?
self.blur()
NSAlert.showModal(
for: self.window,
title: String.localizedStringWithFormat("keyboard_shortcut_used_by_menu_item".localized, menuItem.title)
)
self.focus()
return nil
}
if shortcut.isTakenBySystem {
self.blur()
let modalResponse = NSAlert.showModal(
for: self.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: [
"force_use_shortcut".localized,
"Cancel"
]
)
self.focus()
// first button returned from alert means user wants to continue setting this
// shortcut despite it being used by system.
guard modalResponse == .alertFirstButtonReturn else {
return nil
}
}
self.stringValue = "\(shortcut)"
self.showsCancelButton = true
self.saveShortcut(shortcut)
self.blur()
return nil
}.start()
return shouldBecomeFirstResponder
}
private func saveShortcut(_ shortcut: Shortcut?) {
setShortcut(shortcut, for: shortcutName)
onChange?(shortcut)
}
}
}