forked from MonitorControl/MonitorControl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.swift
More file actions
188 lines (146 loc) · 6.12 KB
/
Utils.swift
File metadata and controls
188 lines (146 loc) · 6.12 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
import Cocoa
import DDC
import os.log
import ServiceManagement
class Utils: NSObject {
// MARK: - Menu
/// Create a slider and add it to the menu
///
/// - Parameters:
/// - menu: Menu containing the slider
/// - display: Display to control
/// - command: Command (Brightness/Volume/...)
/// - title: Title of the slider
/// - Returns: An `NSSlider` slider
static func addSliderMenuItem(toMenu menu: NSMenu, forDisplay display: Display, command: DDC.Command, title: String) -> SliderHandler {
let item = NSMenuItem()
let handler = SliderHandler(display: display, command: command)
let slider = NSSlider(value: 0, minValue: 0, maxValue: 100, target: handler, action: #selector(SliderHandler.valueChanged))
slider.isEnabled = false
slider.frame.size.width = 180
slider.frame.origin = NSPoint(x: 20, y: 5)
handler.slider = slider
let view = NSView(frame: NSRect(x: 0, y: 0, width: slider.frame.width + 30, height: slider.frame.height + 10))
view.addSubview(slider)
item.view = view
menu.insertItem(item, at: 0)
menu.insertItem(withTitle: title, action: nil, keyEquivalent: "", at: 0)
DispatchQueue.global(qos: .background).async {
defer {
DispatchQueue.main.async {
slider.isEnabled = true
}
}
var values: (UInt16, UInt16)?
let delay = display.needsLongerDelay ? UInt64(40 * kMillisecondScale) : nil
if display.ddc?.supported(minReplyDelay: delay) == true {
os_log("Display supports DDC.", type: .debug)
} else {
os_log("Display does not support DDC.", type: .debug)
}
if display.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)
}
let tries = UInt(display.getPollingCount())
os_log("Polling %{public}@ times", type: .info, String(tries))
if tries != 0 {
values = display.ddc?.read(command: command, tries: tries, minReplyDelay: delay)
}
let (currentValue, maxValue) = values ?? (UInt16(display.getValue(for: command)), UInt16(display.getMaxValue(for: command)))
display.saveValue(Int(currentValue), for: command)
display.saveMaxValue(Int(maxValue), for: command)
os_log("%{public}@ (%{public}@):", type: .info, display.name, String(reflecting: command))
os_log(" - current value: %{public}@", type: .info, String(currentValue))
os_log(" - maximum value: %{public}@", type: .info, String(maxValue))
DispatchQueue.main.async {
slider.integerValue = Int(currentValue)
slider.maxValue = Double(maxValue)
}
}
return handler
}
// MARK: - Utilities
/// Acquire Privileges (Necessary to listen to keyboard event globally)
static func acquirePrivileges() {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let accessibilityEnabled = AXIsProcessTrustedWithOptions(options)
if !accessibilityEnabled {
let alert = NSAlert()
alert.addButton(withTitle: NSLocalizedString("Ok", comment: "Shown in the alert dialog"))
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.alertStyle = .warning
alert.runModal()
}
return
}
static func setStartAtLogin(enabled: Bool) {
let identifier = "\(Bundle.main.bundleIdentifier!)Helper" as CFString
SMLoginItemSetEnabled(identifier, enabled)
os_log("Toggle start at login state: %{public}@", type: .info, enabled ? "on" : "off")
}
static 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
}
}
// MARK: - Display Infos
/// Get the name of a display
///
/// - Parameter edid: the EDID of a display
/// - Returns: a string
static func getDisplayName(forEdid edid: EDID) -> String {
return edid.displayName() ?? NSLocalizedString("Unknown", comment: "Unknown display name")
}
/// Get the main display from a list of display
///
/// - Parameter displays: List of Display
/// - Returns: the main display or nil if not found
static func getCurrentDisplay(from displays: [Display]) -> Display? {
guard let mainDisplayID = NSScreen.main?.displayID else {
return nil
}
return displays.first { $0.identifier == mainDisplayID }
}
// MARK: - Enums
/// UserDefault Keys for the app prefs
enum PrefKeys: String {
/// Was the app launched once
case appAlreadyLaunched
/// Does the app start when plugged to an external monitor
case startWhenExternal
/// Keys listened for (Brightness/Volume)
case listenFor
/// Show contrast sliders
case showContrast
/// Lower contrast after brightness
case lowerContrast
/// Change Brightness/Volume for all screens
case allScreens
/// Friendly name changed
case friendlyName
/// Prefs Reset
case preferenceReset
/// Used for notification when displays are updated in DisplayManager
case displayListUpdate
}
/// Keys for the value of listenFor option
enum ListenForKeys: Int {
/// Listen for Brightness and Volume keys
case brightnessAndVolumeKeys = 0
/// Listen for Brightness keys only
case brightnessOnlyKeys = 1
/// Listen for Volume keys only
case volumeOnlyKeys = 2
}
}