forked from MonitorControl/MonitorControl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediaKeyTapManager.swift
More file actions
228 lines (215 loc) · 11.1 KB
/
MediaKeyTapManager.swift
File metadata and controls
228 lines (215 loc) · 11.1 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright © MonitorControl. @JoniVR, @theOneyouseek, @waydabber and others
import AudioToolbox
import Cocoa
import Foundation
import MediaKeyTap
import os.log
class MediaKeyTapManager: MediaKeyTapDelegate {
var mediaKeyTap: MediaKeyTap?
var keyRepeatTimers: [MediaKey: Timer] = [:]
func handle(mediaKey: MediaKey, event: KeyEvent?, modifiers: NSEvent.ModifierFlags?) {
let isPressed = event?.keyPressed ?? true
let isRepeat = event?.keyRepeat ?? false
let isControl = modifiers?.isSuperset(of: NSEvent.ModifierFlags([.control])) ?? false
let isCommand = modifiers?.isSuperset(of: NSEvent.ModifierFlags([.command])) ?? false
let isOption = modifiers?.isSuperset(of: NSEvent.ModifierFlags([.option])) ?? false
let isShift = modifiers?.isSuperset(of: NSEvent.ModifierFlags([.shift])) ?? false
if isPressed, isCommand, !isControl, mediaKey == .brightnessDown, DisplayManager.engageMirror() {
return
}
guard app.sleepID == 0, app.reconfigureID == 0 else {
self.showOSDLock(mediaKey)
return
}
if isPressed, self.handleOpenPrefPane(mediaKey: mediaKey, event: event, modifiers: modifiers) {
return
}
var isSmallIncrement = isOption && isShift
let isContrast = isControl && isOption && isCommand
if [.brightnessUp, .brightnessDown].contains(mediaKey), prefs.bool(forKey: PrefKey.useFineScaleBrightness.rawValue) {
isSmallIncrement = !isSmallIncrement
}
if [.volumeUp, .volumeDown, .mute].contains(mediaKey), prefs.bool(forKey: PrefKey.useFineScaleVolume.rawValue) {
isSmallIncrement = !isSmallIncrement
}
if isPressed, isControl, !isOption, mediaKey == .brightnessUp || mediaKey == .brightnessDown {
self.handleDirectedBrightness(isCommandModifier: isCommand, isUp: mediaKey == .brightnessUp, isSmallIncrement: isSmallIncrement)
return
}
let oppositeKey: MediaKey? = self.oppositeMediaKey(mediaKey: mediaKey)
// If the opposite key to the one being held has an active timer, cancel it - we'll be going in the opposite direction
if let oppositeKey = oppositeKey, let oppositeKeyTimer = self.keyRepeatTimers[oppositeKey], oppositeKeyTimer.isValid {
oppositeKeyTimer.invalidate()
} else if let mediaKeyTimer = self.keyRepeatTimers[mediaKey], mediaKeyTimer.isValid {
// If there's already an active timer for the key being held down, let it run rather than executing it again
if isRepeat {
return
}
mediaKeyTimer.invalidate()
}
self.sendDisplayCommand(mediaKey: mediaKey, isRepeat: isRepeat, isSmallIncrement: isSmallIncrement, isPressed: isPressed, isContrast: isContrast)
}
func handleDirectedBrightness(isCommandModifier: Bool, isUp: Bool, isSmallIncrement: Bool) {
if isCommandModifier {
for otherDisplay in DisplayManager.shared.getOtherDisplays() {
otherDisplay.stepBrightness(isUp: isUp, isSmallIncrement: isSmallIncrement)
}
for appleDisplay in DisplayManager.shared.getAppleDisplays() where !appleDisplay.isBuiltIn() {
appleDisplay.stepBrightness(isUp: isUp, isSmallIncrement: isSmallIncrement)
}
return
} else if let internalDisplay = DisplayManager.shared.getBuiltInDisplay() as? AppleDisplay {
internalDisplay.stepBrightness(isUp: isUp, isSmallIncrement: isSmallIncrement)
return
}
}
private func showOSDLock(_ mediaKey: MediaKey) {
if [.brightnessUp, .brightnessDown].contains(mediaKey) {
OSDUtils.showOSDLockOnAllDisplays(osdImage: OSDUtils.OSDImage.brightness.rawValue)
}
if [.volumeUp, .volumeDown, .mute].contains(mediaKey) {
OSDUtils.showOSDLockOnAllDisplays(osdImage: OSDUtils.OSDImage.audioSpeaker.rawValue)
}
}
private func sendDisplayCommand(mediaKey: MediaKey, isRepeat: Bool, isSmallIncrement: Bool, isPressed: Bool, isContrast: Bool = false) {
self.sendDisplayCommandVolumeMute(mediaKey: mediaKey, isRepeat: isRepeat, isSmallIncrement: isSmallIncrement, isPressed: isPressed)
self.sendDisplayCommandBrightnessContrast(mediaKey: mediaKey, isRepeat: isRepeat, isSmallIncrement: isSmallIncrement, isPressed: isPressed, isContrast: isContrast)
}
private func sendDisplayCommandVolumeMute(mediaKey: MediaKey, isRepeat: Bool, isSmallIncrement: Bool, isPressed: Bool) {
guard [.volumeUp, .volumeDown, .mute].contains(mediaKey), app.sleepID == 0, app.reconfigureID == 0, let affectedDisplays = DisplayManager.shared.getAffectedDisplays(isBrightness: false, isVolume: true) else {
return
}
var wasNotIsPressedVolumeSentAlready = false
for display in affectedDisplays where !display.readPrefAsBool(key: .isDisabled) {
switch mediaKey {
case .mute:
// The mute key should not respond to press + hold or keyup
if !isRepeat, isPressed, let display = display as? OtherDisplay {
display.toggleMute()
if !wasNotIsPressedVolumeSentAlready, display.readPrefAsInt(for: .audioMuteScreenBlank) != 1, !display.readPrefAsBool(key: .unavailableDDC, for: .audioSpeakerVolume) {
app.playVolumeChangedSound()
wasNotIsPressedVolumeSentAlready = true
}
}
case .volumeUp, .volumeDown:
// volume only matters for other displays
if let display = display as? OtherDisplay {
if isPressed {
display.stepVolume(isUp: mediaKey == .volumeUp, isSmallIncrement: isSmallIncrement)
} else if !wasNotIsPressedVolumeSentAlready, !display.readPrefAsBool(key: .unavailableDDC, for: .audioSpeakerVolume) {
app.playVolumeChangedSound()
wasNotIsPressedVolumeSentAlready = true
}
}
default: continue
}
}
}
private func sendDisplayCommandBrightnessContrast(mediaKey: MediaKey, isRepeat _: Bool, isSmallIncrement: Bool, isPressed: Bool, isContrast: Bool = false) {
guard [.brightnessUp, .brightnessDown].contains(mediaKey), app.sleepID == 0, app.reconfigureID == 0, isPressed, let affectedDisplays = DisplayManager.shared.getAffectedDisplays(isBrightness: true, isVolume: false) else {
return
}
for display in affectedDisplays where !display.readPrefAsBool(key: .isDisabled) {
switch mediaKey {
case .brightnessUp:
if isContrast, let otherDisplay = display as? OtherDisplay {
otherDisplay.stepContrast(isUp: mediaKey == .brightnessUp, isSmallIncrement: isSmallIncrement)
} else {
var isAnyDisplayInSwAfterBrightnessMode: Bool = false
for display in affectedDisplays where ((display as? OtherDisplay)?.isSwBrightnessNotDefault() ?? false) && !((display as? OtherDisplay)?.isSw() ?? false) && prefs.bool(forKey: PrefKey.separateCombinedScale.rawValue) {
isAnyDisplayInSwAfterBrightnessMode = true
}
if !(isAnyDisplayInSwAfterBrightnessMode && !(((display as? OtherDisplay)?.isSwBrightnessNotDefault() ?? false) && !((display as? OtherDisplay)?.isSw() ?? false))) {
display.stepBrightness(isUp: mediaKey == .brightnessUp, isSmallIncrement: isSmallIncrement)
}
}
case .brightnessDown:
if isContrast, let otherDisplay = display as? OtherDisplay {
otherDisplay.stepContrast(isUp: mediaKey == .brightnessUp, isSmallIncrement: isSmallIncrement)
} else {
display.stepBrightness(isUp: mediaKey == .brightnessUp, isSmallIncrement: isSmallIncrement)
}
default: continue
}
}
}
private func oppositeMediaKey(mediaKey: MediaKey) -> MediaKey? {
if mediaKey == .brightnessUp {
return .brightnessDown
} else if mediaKey == .brightnessDown {
return .brightnessUp
} else if mediaKey == .volumeUp {
return .volumeDown
} else if mediaKey == .volumeDown {
return .volumeUp
}
return nil
}
func updateMediaKeyTap() {
var keys: [MediaKey] = []
if [KeyboardBrightness.media.rawValue, KeyboardBrightness.both.rawValue].contains(prefs.integer(forKey: PrefKey.keyboardBrightness.rawValue)) {
keys.append(contentsOf: [.brightnessUp, .brightnessDown])
}
if [KeyboardVolume.media.rawValue, KeyboardVolume.both.rawValue].contains(prefs.integer(forKey: PrefKey.keyboardVolume.rawValue)) {
keys.append(contentsOf: [.mute, .volumeUp, .volumeDown])
}
// Remove brightness keys if no external displays are connected, but only if brightness fine control is not active
var isInternalDisplayOnly = true
for display in DisplayManager.shared.getAllDisplays() where !display.isBuiltIn() {
isInternalDisplayOnly = false
}
if isInternalDisplayOnly, !prefs.bool(forKey: PrefKey.useFineScaleBrightness.rawValue) {
let keysToDelete: [MediaKey] = [.brightnessUp, .brightnessDown]
keys.removeAll { keysToDelete.contains($0) }
}
// Remove volume related keys if audio device is controllable
if let defaultAudioDevice = app.coreAudio.defaultOutputDevice {
let keysToDelete: [MediaKey] = [.volumeUp, .volumeDown, .mute]
if prefs.integer(forKey: PrefKey.multiKeyboardVolume.rawValue) == MultiKeyboardVolume.audioDeviceNameMatching.rawValue {
if DisplayManager.shared.updateAudioControlTargetDisplays(deviceName: defaultAudioDevice.name) == 0 {
keys.removeAll { keysToDelete.contains($0) }
}
} else if defaultAudioDevice.canSetVirtualMasterVolume(scope: .output) == true {
keys.removeAll { keysToDelete.contains($0) }
}
}
self.mediaKeyTap?.stop()
// returning an empty array listens for all mediakeys in MediaKeyTap
if keys.count > 0 {
self.mediaKeyTap = MediaKeyTap(delegate: self, on: KeyPressMode.keyDownAndUp, for: keys, observeBuiltIn: true)
self.mediaKeyTap?.start()
}
}
func handleOpenPrefPane(mediaKey: MediaKey, event: KeyEvent?, modifiers: NSEvent.ModifierFlags?) -> Bool {
guard let modifiers = modifiers else { return false }
if !(modifiers.contains(.option) && !modifiers.contains(.shift) && !modifiers.contains(.control) && !modifiers.contains(.command)) {
return false
}
if event?.keyRepeat == true {
return false
}
switch mediaKey {
case .brightnessUp, .brightnessDown:
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Library/PreferencePanes/Displays.prefPane"))
case .mute, .volumeUp, .volumeDown:
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Library/PreferencePanes/Sound.prefPane"))
default:
return false
}
return true
}
static func acquirePrivileges() {
if !self.readPrivileges(prompt: true) {
let alert = NSAlert()
alert.messageText = NSLocalizedString("Shortcuts not available", comment: "Shown in the alert dialog")
alert.informativeText = NSLocalizedString("You need to enable MonitorControl in System Preferences > Security and Privacy > Accessibility for the keyboard shortcuts to work", comment: "Shown in the alert dialog")
alert.runModal()
}
}
static func readPrivileges(prompt: Bool) -> Bool {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: prompt]
let status = AXIsProcessTrustedWithOptions(options)
os_log("Reading Accessibility privileges - Current access status %{public}@", type: .info, String(status))
return status
}
}