99import Cocoa
1010
1111class Utils : NSObject {
12+ private static func printCommandValue( _ command: Int32 , _ value: Int ) {
13+ let cmdString : ( Int32 ) -> String ? = {
14+ switch $0 {
15+ case BRIGHTNESS:
16+ return " Brightness "
17+ case CONTRAST:
18+ return " Contrast "
19+ case AUDIO_SPEAKER_VOLUME:
20+ return " Volume "
21+ default :
22+ return nil
23+ }
24+ }
25+
26+ print ( " \( cmdString ( command) ?? " N/A " ) value: \( value) " )
27+ }
1228
1329 // MARK: - DDCCTL
1430
@@ -21,7 +37,10 @@ class Utils: NSObject {
2137 static func sendCommand( _ command: Int32 , toMonitor monitor: CGDirectDisplayID , withValue value: Int ) {
2238 var wrcmd = DDCWriteCommand ( control_id: UInt8 ( command) , new_value: UInt8 ( value) )
2339 DDCWrite ( monitor, & wrcmd)
24- print ( " \( command == BRIGHTNESS ? " Brightness " : " Volume " ) value : \( value) " )
40+
41+ #if DEBUG
42+ printCommandValue ( command, value)
43+ #endif
2544 }
2645
2746 /// Get current value of ddcctl command
@@ -30,14 +49,18 @@ class Utils: NSObject {
3049 /// - command: The command to send
3150 /// - monitor: The id of the monitor to send the command to
3251 /// - Returns: the value of the command
33- static func getCommand( _ command: Int32 , fromMonitor monitor: CGDirectDisplayID ) -> Int {
52+ static func getCommand( _ command: Int32 , fromMonitor monitor: CGDirectDisplayID ) -> Int ? {
3453 var readCmd = DDCReadCommand ( )
3554 readCmd. control_id = UInt8 ( command)
3655 readCmd. max_value = 0
3756 readCmd. current_value = 0
3857 DDCRead ( monitor, & readCmd)
39- print ( " \( command == BRIGHTNESS ? " Brightness " : " Volume " ) value : \( readCmd. current_value) " )
40- return Int ( readCmd. current_value)
58+
59+ #if DEBUG
60+ printCommandValue ( command, Int ( readCmd. current_value) )
61+ #endif
62+
63+ return readCmd. success ? Int ( readCmd. current_value) : nil
4164 }
4265
4366 // MARK: - Menu
@@ -75,10 +98,8 @@ class Utils: NSObject {
7598 slider. target = handler
7699 slider. minValue = 0
77100 slider. maxValue = 100
78- slider. integerValue = getCommand ( command, fromMonitor: display. identifier)
79101 slider. action = #selector( SliderHandler . valueChanged)
80102 handler. slider = slider
81- display. saveValue ( slider. integerValue, for: command)
82103
83104 view. addSubview ( label)
84105 view. addSubview ( slider)
@@ -88,6 +109,26 @@ class Utils: NSObject {
88109 menu. insertItem ( item, at: 0 )
89110 menu. insertItem ( NSMenuItem . separator ( ) , at: 1 )
90111
112+ DispatchQueue . global ( qos: . background) . async {
113+ var val : Int ?
114+
115+ for _ in 0 ... 100 {
116+ if let res = getCommand ( command, fromMonitor: display. identifier) {
117+ val = res
118+ break
119+ }
120+ usleep ( 40000 )
121+ }
122+
123+ if let val = val {
124+ display. saveValue ( val, for: command)
125+
126+ DispatchQueue . main. async {
127+ slider. integerValue = val
128+ }
129+ }
130+ }
131+
91132 return handler
92133 }
93134
0 commit comments