forked from MonitorControl/MonitorControl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppDelegate.swift
More file actions
336 lines (308 loc) · 14.5 KB
/
AppDelegate.swift
File metadata and controls
336 lines (308 loc) · 14.5 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
// Copyright © MonitorControl. @JoniVR, @theOneyouseek, @waydabber and others
import AVFoundation
import Cocoa
import Foundation
import MediaKeyTap
import os.log
import Preferences
import ServiceManagement
import SimplyCoreAudio
import Sparkle
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
var mediaKeyTap = MediaKeyTapManager()
var keyboardShortcuts = KeyboardShortcutsManager()
let coreAudio = SimplyCoreAudio()
var accessibilityObserver: NSObjectProtocol!
var reconfigureID: Int = 0 // dispatched reconfigure command ID
var sleepID: Int = 0 // sleep event ID
var safeMode = false
var jobRunning = false
var startupActionWriteCounter: Int = 0
var audioPlayer: AVAudioPlayer?
let updaterController = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: UpdaterDelegate(), userDriverDelegate: nil)
var preferencePaneStyle: Preferences.Style {
if !DEBUG_MACOS10, #available(macOS 11.0, *) {
return Preferences.Style.toolbarItems
} else {
return Preferences.Style.segmentedControl
}
}
lazy var preferencesWindowController: PreferencesWindowController = {
PreferencesWindowController(
preferencePanes: [
mainPrefsVc!,
menuslidersPrefsVc!,
keyboardPrefsVc!,
displaysPrefsVc!,
aboutPrefsVc!,
],
style: preferencePaneStyle,
animated: true
)
}()
func applicationDidFinishLaunching(_: Notification) {
app = self
menu = MenuHandler()
menu.delegate = menu
self.subscribeEventListeners()
if NSEvent.modifierFlags.contains(NSEvent.ModifierFlags.shift) {
self.safeMode = true
let alert = NSAlert()
alert.messageText = NSLocalizedString("Safe Mode Activated", comment: "Shown in the alert dialog")
alert.informativeText = NSLocalizedString("Shift was pressed during launch. MonitorControl started in safe mode. Default preferences are reloaded, DDC read is blocked.", comment: "Shown in the alert dialog")
alert.runModal()
}
let currentBuildNumber = Int(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "1") ?? 1
let previousBuildNumber: Int = (Int(prefs.string(forKey: PrefKey.buildNumber.rawValue) ?? "0") ?? 0)
if self.safeMode || ((previousBuildNumber < MIN_PREVIOUS_BUILD_NUMBER) && previousBuildNumber > 0) || (previousBuildNumber > currentBuildNumber), let bundleID = Bundle.main.bundleIdentifier {
if !self.safeMode {
let alert = NSAlert()
alert.messageText = NSLocalizedString("Incompatible previous version", comment: "Shown in the alert dialog")
alert.informativeText = NSLocalizedString("Preferences for an incompatible previous app version detected. Default preferences are reloaded.", comment: "Shown in the alert dialog")
alert.runModal()
}
prefs.removePersistentDomain(forName: bundleID)
}
prefs.set(currentBuildNumber, forKey: PrefKey.buildNumber.rawValue)
self.setDefaultPrefs()
if !DEBUG_MACOS10, #available(macOS 11.0, *) {
self.statusItem.button?.image = NSImage(systemSymbolName: "sun.max", accessibilityDescription: "MonitorControl")
} else {
self.statusItem.button?.image = NSImage(named: "status")
}
self.statusItem.menu = menu
self.checkPermissions()
CGDisplayRegisterReconfigurationCallback({ _, _, _ in app.displayReconfigured() }, nil)
self.configure(firstrun: true)
DisplayManager.shared.createGammaActivityEnforcer()
self.updaterController.startUpdater()
}
@objc func quitClicked(_: AnyObject) {
os_log("Quit clicked", type: .info)
NSApplication.shared.terminate(self)
}
@objc func prefsClicked(_: AnyObject) {
os_log("Preferences clicked", type: .info)
self.preferencesWindowController.show()
}
func applicationShouldHandleReopen(_: NSApplication, hasVisibleWindows _: Bool) -> Bool {
app.prefsClicked(self)
return true
}
func applicationWillTerminate(_: Notification) {
os_log("Goodbye!", type: .info)
DisplayManager.shared.resetSwBrightnessForAllDisplays(noPrefSave: true)
self.statusItem.isVisible = true
}
func setDefaultPrefs() {
if !prefs.bool(forKey: PrefKey.appAlreadyLaunched.rawValue) {
// Only preferences that are not false, 0 or "" by default are set here. Assumes pre-wiped database.
prefs.set(true, forKey: PrefKey.appAlreadyLaunched.rawValue)
prefs.set(true, forKey: PrefKey.SUEnableAutomaticChecks.rawValue)
}
}
@objc func displayReconfigured() {
DisplayManager.shared.resetSwBrightnessForAllDisplays(noPrefSave: true)
CGDisplayRestoreColorSyncSettings()
self.reconfigureID += 1
self.updateMediaKeyTap()
os_log("Bumping reconfigureID to %{public}@", type: .info, String(self.reconfigureID))
_ = DisplayManager.shared.destroyAllShades()
if self.sleepID == 0 {
let dispatchedReconfigureID = self.reconfigureID
os_log("Display to be reconfigured with reconfigureID %{public}@", type: .info, String(dispatchedReconfigureID))
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.configure(dispatchedReconfigureID: dispatchedReconfigureID)
}
}
}
func configure(dispatchedReconfigureID: Int = 0, firstrun: Bool = false) {
guard self.sleepID == 0, dispatchedReconfigureID == self.reconfigureID else {
return
}
os_log("Request for configuration with reconfigreID %{public}@", type: .info, String(dispatchedReconfigureID))
self.reconfigureID = 0
DisplayManager.shared.gammaInterferenceCounter = 0
DisplayManager.shared.configureDisplays()
DisplayManager.shared.addDisplayCounterSuffixes()
DisplayManager.shared.updateArm64AVServices()
if firstrun && prefs.integer(forKey: PrefKey.startupAction.rawValue) != StartupAction.write.rawValue {
DisplayManager.shared.resetSwBrightnessForAllDisplays(prefsOnly: true)
}
DisplayManager.shared.setupOtherDisplays(firstrun: firstrun)
self.updateMenusAndKeys()
if !firstrun || prefs.integer(forKey: PrefKey.startupAction.rawValue) == StartupAction.write.rawValue {
if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue) {
DisplayManager.shared.restoreSwBrightnessForAllDisplays(async: !prefs.bool(forKey: PrefKey.disableSmoothBrightness.rawValue))
}
}
displaysPrefsVc?.loadDisplayList()
self.job(start: true)
}
func updateMenusAndKeys() {
menu.updateMenus()
self.updateMediaKeyTap()
}
func checkPermissions() {
let permissionsRequired: Bool = [KeyboardVolume.media.rawValue, KeyboardVolume.both.rawValue].contains(prefs.integer(forKey: PrefKey.keyboardVolume.rawValue)) || [KeyboardBrightness.media.rawValue, KeyboardBrightness.both.rawValue].contains(prefs.integer(forKey: PrefKey.keyboardBrightness.rawValue))
if !MediaKeyTapManager.readPrivileges(prompt: false), permissionsRequired {
MediaKeyTapManager.acquirePrivileges()
}
}
private func subscribeEventListeners() {
NotificationCenter.default.addObserver(self, selector: #selector(self.audioDeviceChanged), name: Notification.Name.defaultOutputDeviceChanged, object: nil) // subscribe Audio output detector (SimplyCoreAudio)
DistributedNotificationCenter.default.addObserver(self, selector: #selector(self.displayReconfigured), name: NSNotification.Name(rawValue: kColorSyncDisplayDeviceProfilesNotification.takeRetainedValue() as String), object: nil) // ColorSync change
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.sleepNotification), name: NSWorkspace.screensDidSleepNotification, object: nil) // sleep and wake listeners
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.wakeNotification), name: NSWorkspace.screensDidWakeNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.sleepNotification), name: NSWorkspace.willSleepNotification, object: nil)
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.wakeNotification), name: NSWorkspace.didWakeNotification, object: nil)
_ = DistributedNotificationCenter.default().addObserver(forName: NSNotification.Name(rawValue: NSNotification.Name.accessibilityApi.rawValue), object: nil, queue: nil) { _ in DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.updateMediaKeyTap() } } // listen for accessibility status changes
}
@objc private func sleepNotification() {
self.sleepID += 1
os_log("Sleeping with sleep %{public}@", type: .info, String(self.sleepID))
self.updateMediaKeyTap()
}
@objc private func wakeNotification() {
if self.sleepID != 0 {
os_log("Waking up from sleep %{public}@", type: .info, String(self.sleepID))
let dispatchedSleepID = self.sleepID
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { // Some displays take time to recover...
self.soberNow(dispatchedSleepID: dispatchedSleepID)
}
}
}
private func soberNow(dispatchedSleepID: Int) {
if self.sleepID == dispatchedSleepID {
os_log("Sober from sleep %{public}@", type: .info, String(self.sleepID))
self.sleepID = 0
if self.reconfigureID != 0 {
let dispatchedReconfigureID = self.reconfigureID
os_log("Displays need reconfig after sober with reconfigureID %{public}@", type: .info, String(dispatchedReconfigureID))
self.configure(dispatchedReconfigureID: dispatchedReconfigureID)
} else if Arm64DDC.isArm64 {
os_log("Displays don't need reconfig after sober but might need AVServices update", type: .info)
DisplayManager.shared.updateArm64AVServices()
self.job(start: true)
}
self.startupActionWriteRepeatAfterSober()
self.updateMediaKeyTap()
}
}
private func startupActionWriteRepeatAfterSober(dispatchedCounter: Int = 0) {
let counter = dispatchedCounter == 0 ? 10 : dispatchedCounter
self.startupActionWriteCounter = dispatchedCounter == 0 ? counter : self.startupActionWriteCounter
guard prefs.integer(forKey: PrefKey.startupAction.rawValue) == StartupAction.write.rawValue, self.startupActionWriteCounter == counter else {
return
}
os_log("Sober write action repeat for DDC - %{public}@", type: .info, String(counter))
DisplayManager.shared.restoreOtherDisplays()
self.startupActionWriteCounter = counter - 1
if counter > 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.startupActionWriteRepeatAfterSober(dispatchedCounter: counter - 1)
}
}
}
private func job(start: Bool = false) {
guard !(self.jobRunning && start) else {
return
}
if self.sleepID == 0, self.reconfigureID == 0 {
if !self.jobRunning {
os_log("MonitorControl job started.", type: .info)
self.jobRunning = true
}
var refreshedSomething = false
for display in DisplayManager.shared.displays {
let delta = display.refreshBrightness()
if delta != 0 {
refreshedSomething = true
if prefs.bool(forKey: PrefKey.enableBrightnessSync.rawValue) {
for targetDisplay in DisplayManager.shared.displays where targetDisplay != display {
os_log("Updating delta from display %{public}@ to display %{public}@", type: .info, String(display.identifier), String(targetDisplay.identifier))
let newValue = max(0, min(1, targetDisplay.getBrightness() + delta))
_ = targetDisplay.setBrightness(newValue)
if let slider = targetDisplay.sliderHandler[.brightness] {
slider.setValue(newValue, displayID: targetDisplay.identifier)
}
}
}
}
}
let nextRefresh = refreshedSomething ? 0.1 : 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + nextRefresh) {
self.job()
}
} else {
self.jobRunning = false
os_log("MonitorControl job died because of sleep or reconfiguration.", type: .info)
}
}
func handleListenForChanged() {
self.checkPermissions()
self.updateMediaKeyTap()
}
func preferenceReset() {
os_log("Resetting all preferences.")
if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue) {
DisplayManager.shared.resetSwBrightnessForAllDisplays(async: false)
}
if let bundleID = Bundle.main.bundleIdentifier {
prefs.removePersistentDomain(forName: bundleID)
}
app.statusItem.isVisible = true
self.setDefaultPrefs()
self.checkPermissions()
self.updateMediaKeyTap()
self.configure(firstrun: true)
}
@objc func audioDeviceChanged() {
if let defaultDevice = self.coreAudio.defaultOutputDevice {
os_log("Default output device changed to “%{public}@”.", type: .info, defaultDevice.name)
os_log("Can device set its own volume? %{public}@", type: .info, defaultDevice.canSetVirtualMainVolume(scope: .output).description)
}
self.updateMediaKeyTap()
}
func updateMediaKeyTap() {
MediaKeyTap.useAlternateBrightnessKeys = !prefs.bool(forKey: PrefKey.disableAltBrightnessKeys.rawValue)
self.mediaKeyTap.updateMediaKeyTap()
}
func setStartAtLogin(enabled: Bool) {
let identifier = "\(Bundle.main.bundleIdentifier!)Helper" as CFString
SMLoginItemSetEnabled(identifier, enabled)
}
func getSystemPreferences() -> [String: AnyObject]? {
var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml
let plistPath = NSString(string: "~/Library/Preferences/.GlobalPreferences.plist").expandingTildeInPath
guard let plistXML = FileManager.default.contents(atPath: plistPath) else {
return nil
}
do {
return try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as? [String: AnyObject]
} catch {
os_log("Error reading system prefs plist: %{public}@", type: .info, error.localizedDescription)
return nil
}
}
func macOS10() -> Bool {
if !DEBUG_MACOS10, #available(macOS 11.0, *) {
return false
} else {
return true
}
}
func playVolumeChangedSound() {
guard let preferences = app.getSystemPreferences(), let hasSoundEnabled = preferences["com.apple.sound.beep.feedback"] as? Int, hasSoundEnabled == 1 else {
return
}
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: "/System/Library/LoginPlugins/BezelServices.loginPlugin/Contents/Resources/volume.aiff"))
self.audioPlayer?.volume = 1
self.audioPlayer?.play()
} catch {
os_log("%{public}@", type: .error, error.localizedDescription)
}
}
}