forked from MonitorControl/MonitorControl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExternalDisplay.swift
More file actions
344 lines (280 loc) · 11.3 KB
/
ExternalDisplay.swift
File metadata and controls
344 lines (280 loc) · 11.3 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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import AVFoundation
import Cocoa
import DDC
import os.log
class ExternalDisplay: Display {
var brightnessSliderHandler: SliderHandler?
var volumeSliderHandler: SliderHandler?
var contrastSliderHandler: SliderHandler?
var ddc: DDC?
private let prefs = UserDefaults.standard
var hideOsd: Bool {
get {
return self.prefs.bool(forKey: "hideOsd-\(self.identifier)")
}
set {
self.prefs.set(newValue, forKey: "hideOsd-\(self.identifier)")
os_log("Set `hideOsd` to: %{public}@", type: .info, String(newValue))
}
}
var needsLongerDelay: Bool {
get {
return self.prefs.object(forKey: "longerDelay-\(self.identifier)") as? Bool ?? false
}
set {
self.prefs.set(newValue, forKey: "longerDelay-\(self.identifier)")
os_log("Set `needsLongerDisplay` to: %{public}@", type: .info, String(newValue))
}
}
private var audioPlayer: AVAudioPlayer?
private let osdChicletBoxes: Float = 16
override init(_ identifier: CGDirectDisplayID, name: String, vendorNumber: UInt32?, modelNumber: UInt32?) {
super.init(identifier, name: name, vendorNumber: vendorNumber, modelNumber: modelNumber)
self.ddc = DDC(for: identifier)
}
// On some displays, the display's OSD overlaps the macOS OSD,
// calling the OSD command with 1 seems to hide it.
func hideDisplayOsd() {
guard self.hideOsd else {
return
}
for _ in 0..<20 {
_ = self.ddc?.write(command: .osd, value: UInt16(1), errorRecoveryWaitTime: 2000)
}
}
func isMuted() -> Bool {
return self.getValue(for: .audioMuteScreenBlank) == 1
}
func toggleMute(fromVolumeSlider: Bool = false) {
var muteValue: Int
var volumeOSDValue: Int
if !self.isMuted() {
muteValue = 1
volumeOSDValue = 0
} else {
muteValue = 2
volumeOSDValue = self.getValue(for: .audioSpeakerVolume)
// The volume that will be set immediately after setting unmute while the old set volume was 0 is unpredictable
// Hence, just set it to a single filled chiclet
if volumeOSDValue == 0 {
volumeOSDValue = self.stepSize(for: .audioSpeakerVolume, isSmallIncrement: false)
self.saveValue(volumeOSDValue, for: .audioSpeakerVolume)
}
}
let volumeDDCValue = UInt16(volumeOSDValue)
guard self.ddc?.write(command: .audioSpeakerVolume, value: volumeDDCValue) == true else {
return
}
if self.supportsMuteCommand() {
guard self.ddc?.write(command: .audioMuteScreenBlank, value: UInt16(muteValue)) == true else {
return
}
}
self.saveValue(muteValue, for: .audioMuteScreenBlank)
if !fromVolumeSlider {
self.hideDisplayOsd()
self.showOsd(command: volumeOSDValue > 0 ? .audioSpeakerVolume : .audioMuteScreenBlank, value: volumeOSDValue)
if volumeOSDValue > 0 {
self.playVolumeChangedSound()
}
if let slider = self.volumeSliderHandler?.slider {
slider.intValue = Int32(volumeDDCValue)
}
}
}
func stepVolume(isUp: Bool, isSmallIncrement: Bool) {
var muteValue: Int?
let volumeOSDValue = self.calcNewValue(for: .audioSpeakerVolume, isUp: isUp, isSmallIncrement: isSmallIncrement)
let volumeDDCValue = UInt16(volumeOSDValue)
if self.isMuted(), volumeOSDValue > 0 {
muteValue = 2
} else if !self.isMuted(), volumeOSDValue == 0 {
muteValue = 1
}
let isAlreadySet = volumeOSDValue == self.getValue(for: .audioSpeakerVolume)
if !isAlreadySet {
guard self.ddc?.write(command: .audioSpeakerVolume, value: volumeDDCValue) == true else {
return
}
}
if let muteValue = muteValue {
// If the mute command is supported, set its value accordingly
if self.supportsMuteCommand() {
guard self.ddc?.write(command: .audioMuteScreenBlank, value: UInt16(muteValue)) == true else {
return
}
}
self.saveValue(muteValue, for: .audioMuteScreenBlank)
}
self.hideDisplayOsd()
self.showOsd(command: .audioSpeakerVolume, value: volumeOSDValue)
if !isAlreadySet {
self.saveValue(volumeOSDValue, for: .audioSpeakerVolume)
if volumeOSDValue > 0 {
self.playVolumeChangedSound()
}
if let slider = self.volumeSliderHandler?.slider {
slider.intValue = Int32(volumeDDCValue)
}
}
}
override func stepBrightness(isUp: Bool, isSmallIncrement: Bool) {
let osdValue = Int(self.calcNewValue(for: .brightness, isUp: isUp, isSmallIncrement: isSmallIncrement))
let isAlreadySet = osdValue == self.getValue(for: .brightness)
let ddcValue = UInt16(osdValue)
// Set the contrast value according to the brightness, if necessary
if !isAlreadySet {
self.setContrastValueForBrightness(osdValue)
}
if !isAlreadySet {
guard self.ddc?.write(command: .brightness, value: ddcValue) == true else {
return
}
}
self.showOsd(command: .brightness, value: osdValue)
if !isAlreadySet {
if let slider = self.brightnessSliderHandler?.slider {
slider.intValue = Int32(ddcValue)
}
self.saveValue(osdValue, for: .brightness)
}
}
func setContrastValueForBrightness(_ brightness: Int) {
var contrastValue: Int?
if brightness == 0 {
contrastValue = 0
// Save the current DDC value for contrast so it can be restored, even across app restarts
if self.getRestoreValue(for: .contrast) == 0 {
self.setRestoreValue(self.getValue(for: .contrast), for: .contrast)
}
} else if self.getValue(for: .brightness) == 0, brightness > 0 {
contrastValue = self.getRestoreValue(for: .contrast)
}
// Only write the new contrast value if lowering contrast after brightness is enabled
if let contrastValue = contrastValue, self.prefs.bool(forKey: Utils.PrefKeys.lowerContrast.rawValue) {
_ = self.ddc?.write(command: .contrast, value: UInt16(contrastValue))
self.saveValue(contrastValue, for: .contrast)
if let slider = contrastSliderHandler?.slider {
slider.intValue = Int32(contrastValue)
}
}
}
func readDDCValues(for command: DDC.Command, tries: UInt, minReplyDelay delay: UInt64?) -> (current: UInt16, max: UInt16)? {
var values: (UInt16, UInt16)?
if self.ddc?.supported(minReplyDelay: delay) == true {
os_log("Display supports DDC.", type: .debug)
} else {
os_log("Display does not support DDC.", type: .debug)
}
if self.ddc?.enableAppReport() == true {
os_log("Display supports enabling DDC application report.", type: .debug)
} else {
os_log("Display does not support enabling DDC application report.", type: .debug)
}
values = self.ddc?.read(command: command, tries: tries, minReplyDelay: delay)
return values
}
func calcNewValue(for command: DDC.Command, isUp: Bool, isSmallIncrement: Bool) -> Int {
let currentValue = self.getValue(for: command)
let nextValue: Int
if isSmallIncrement {
nextValue = currentValue + (isUp ? 1 : -1)
} else {
let filledChicletBoxes = self.osdChicletBoxes * (Float(currentValue) / Float(self.getMaxValue(for: command)))
var nextFilledChicletBoxes: Float
var filledChicletBoxesRel: Float = isUp ? 1 : -1
// This is a workaround to ensure that if the user has set the value using a small step (that is, the current chiclet box isn't completely filled,
// the next regular up or down step will only fill or empty that chiclet, and not the next one as well - it only really works because the max value is 100
if (isUp && ceil(filledChicletBoxes) - filledChicletBoxes > 0.15) || (!isUp && filledChicletBoxes - floor(filledChicletBoxes) > 0.15) {
filledChicletBoxesRel = 0
}
nextFilledChicletBoxes = isUp ? ceil(filledChicletBoxes + filledChicletBoxesRel) : floor(filledChicletBoxes + filledChicletBoxesRel)
nextValue = Int(Float(self.getMaxValue(for: command)) * (nextFilledChicletBoxes / self.osdChicletBoxes))
}
return max(0, min(self.getMaxValue(for: command), Int(nextValue)))
}
func getValue(for command: DDC.Command) -> Int {
return self.prefs.integer(forKey: "\(command.rawValue)-\(self.identifier)")
}
func saveValue(_ value: Int, for command: DDC.Command) {
self.prefs.set(value, forKey: "\(command.rawValue)-\(self.identifier)")
}
func saveMaxValue(_ maxValue: Int, for command: DDC.Command) {
self.prefs.set(maxValue, forKey: "max-\(command.rawValue)-\(self.identifier)")
}
func getMaxValue(for command: DDC.Command) -> Int {
let max = self.prefs.integer(forKey: "max-\(command.rawValue)-\(self.identifier)")
return max == 0 ? 100 : max
}
func getRestoreValue(for command: DDC.Command) -> Int {
return self.prefs.integer(forKey: "restore-\(command.rawValue)-\(self.identifier)")
}
func setRestoreValue(_ value: Int?, for command: DDC.Command) {
self.prefs.set(value, forKey: "restore-\(command.rawValue)-\(self.identifier)")
}
func setPollingMode(_ value: Int) {
self.prefs.set(String(value), forKey: "pollingMode-\(self.identifier)")
}
/*
Polling Modes:
0 -> .none -> 0 tries
1 -> .minimal -> 5 tries
2 -> .normal -> 10 tries
3 -> .heavy -> 100 tries
4 -> .custom -> $pollingCount tries
*/
func getPollingMode() -> Int {
// Reading as string so we don't get "0" as the default value
return Int(self.prefs.string(forKey: "pollingMode-\(self.identifier)") ?? "2") ?? 2
}
func getPollingCount() -> Int {
let selectedMode = self.getPollingMode()
switch selectedMode {
case 0:
return PollingMode.none.value
case 1:
return PollingMode.minimal.value
case 2:
return PollingMode.normal.value
case 3:
return PollingMode.heavy.value
case 4:
let val = self.prefs.integer(forKey: "pollingCount-\(self.identifier)")
return PollingMode.custom(value: val).value
default:
return 0
}
}
func setPollingCount(_ value: Int) {
self.prefs.set(value, forKey: "pollingCount-\(self.identifier)")
}
private func stepSize(for command: DDC.Command, isSmallIncrement: Bool) -> Int {
return isSmallIncrement ? 1 : Int(floor(Float(self.getMaxValue(for: command)) / self.osdChicletBoxes))
}
override func showOsd(command: DDC.Command, value: Int, maxValue _: Int = 100) {
super.showOsd(command: command, value: value, maxValue: self.getMaxValue(for: command))
}
private func supportsMuteCommand() -> Bool {
// Monitors which don't support the mute command - e.g. Dell U3419W - will have a maximum value of 100 for the DDC mute command
return self.getMaxValue(for: .audioMuteScreenBlank) == 2
}
private func playVolumeChangedSound() {
let soundPath = "/System/Library/LoginPlugins/BezelServices.loginPlugin/Contents/Resources/volume.aiff"
let soundUrl = URL(fileURLWithPath: soundPath)
// Check if user has enabled "Play feedback when volume is changed" in Sound Preferences
guard let preferences = Utils.getSystemPreferences(),
let hasSoundEnabled = preferences["com.apple.sound.beep.feedback"] as? Int,
hasSoundEnabled == 1 else {
os_log("sound not enabled", type: .info)
return
}
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: soundUrl)
self.audioPlayer?.volume = 1
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
} catch {
os_log("%{public}@", type: .error, error.localizedDescription)
}
}
}