brightness 0.8.0

Get and set display brightness
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
// Copyright (C) 2022 The brightness project authors. Distributed under the 0BSD license.

//! Platform-specific implementation for Windows.

use crate::{Error, blocking::BrightnessDevice};
use itertools::Either;
use std::{
    collections::HashMap,
    ffi::{OsString, c_void},
    fmt,
    iter::once,
    mem::size_of,
    os::windows::ffi::OsStringExt,
};
use windows::{
    Win32::{
        Devices::Display::{
            DISPLAY_BRIGHTNESS, DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME, DISPLAYCONFIG_MODE_INFO,
            DISPLAYCONFIG_MODE_INFO_TYPE_TARGET, DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL,
            DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_TARGET_DEVICE_NAME,
            DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, DISPLAYPOLICY_AC, DISPLAYPOLICY_DC,
            DestroyPhysicalMonitor, DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes,
            GetMonitorBrightness, GetNumberOfPhysicalMonitorsFromHMONITOR,
            GetPhysicalMonitorsFromHMONITOR, IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS,
            IOCTL_VIDEO_QUERY_SUPPORTED_BRIGHTNESS, IOCTL_VIDEO_SET_DISPLAY_BRIGHTNESS,
            PHYSICAL_MONITOR, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig, SetMonitorBrightness,
        },
        Foundation::{
            CloseHandle, ERROR_ACCESS_DENIED, ERROR_SUCCESS, HANDLE, LPARAM, RECT, WIN32_ERROR,
        },
        Graphics::Gdi::{
            DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, EnumDisplayDevicesW, EnumDisplayMonitors,
            GetMonitorInfoW, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW,
        },
        Storage::FileSystem::{
            CreateFileW, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE,
            OPEN_EXISTING,
        },
        System::IO::DeviceIoControl,
        UI::WindowsAndMessaging::EDD_GET_DEVICE_INTERFACE_NAME,
    },
    core::{BOOL, Error as WinError, PCWSTR},
};

/// Windows-specific brightness functionality.
pub trait BrightnessExt {
    /// Returns device description
    fn device_description(&self) -> Result<String, Error>;

    /// Returns the device registry key
    fn device_registry_key(&self) -> Result<String, Error>;

    /// Returns the device path
    fn device_path(&self) -> Result<String, Error>;
}

#[derive(Debug)]
pub(crate) struct BlockingDeviceImpl {
    physical_monitor: WrappedPhysicalMonitor,
    file_handle: WrappedFileHandle,
    device_name: String,
    friendly_name: String,
    /// Note: PHYSICAL_MONITOR.szPhysicalMonitorDescription == DISPLAY_DEVICEW.DeviceString
    /// Description is **not** unique.
    pub(crate) device_description: String,
    pub(crate) device_key: String,
    /// Note: DISPLAYCONFIG_TARGET_DEVICE_NAME.monitorDevicePath == DISPLAY_DEVICEW.DeviceID (with EDD_GET_DEVICE_INTERFACE_NAME)\
    /// These are in the "DOS Device Path" format.
    pub(crate) device_path: String,
    output_technology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY,
}

impl BlockingDeviceImpl {
    fn is_internal(&self) -> bool {
        self.output_technology == DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL
    }
}

/// A safe wrapper for a physical monitor handle that implements `Drop` to call `DestroyPhysicalMonitor`
struct WrappedPhysicalMonitor(HANDLE);

impl fmt::Debug for WrappedPhysicalMonitor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

impl Drop for WrappedPhysicalMonitor {
    fn drop(&mut self) {
        unsafe {
            let _ = DestroyPhysicalMonitor(self.0);
        }
    }
}

unsafe impl Send for WrappedPhysicalMonitor {}

unsafe impl Sync for WrappedPhysicalMonitor {}

/// A safe wrapper for a windows HANDLE that implements `Drop` to call `CloseHandle`
struct WrappedFileHandle(HANDLE);

impl fmt::Debug for WrappedFileHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

impl Drop for WrappedFileHandle {
    fn drop(&mut self) {
        unsafe {
            let _ = CloseHandle(self.0);
        }
    }
}

unsafe impl Send for WrappedFileHandle {}

unsafe impl Sync for WrappedFileHandle {}

#[inline]
fn flag_set<T: std::ops::BitAnd<Output = T> + std::cmp::PartialEq + Copy>(t: T, flag: T) -> bool {
    t & flag == flag
}

impl crate::blocking::Brightness for BlockingDeviceImpl {
    fn device_name(&self) -> Result<String, Error> {
        Ok(self.device_name.clone())
    }

    fn friendly_device_name(&self) -> Result<String, Error> {
        Ok(self.friendly_name.clone())
    }

    fn get(&self) -> Result<u32, Error> {
        Ok(if self.is_internal() {
            ioctl_query_display_brightness(self)?
        } else {
            ddcci_get_monitor_brightness(self)?.get_current_percentage()
        })
    }

    fn set(&self, percentage: u32) -> Result<(), Error> {
        if self.is_internal() {
            let supported = ioctl_query_supported_brightness(self)?;
            let new_value = supported.get_nearest(percentage);
            ioctl_set_display_brightness(self, new_value)?;
        } else {
            let current = ddcci_get_monitor_brightness(self)?;
            let new_value = current.percentage_to_current(percentage);
            ddcci_set_monitor_brightness(self, new_value)?;
        }
        Ok(())
    }
}

pub(crate) fn brightness_devices() -> impl Iterator<Item = Result<BlockingDeviceImpl, SysError>> {
    unsafe {
        let device_info_map = match get_device_info_map() {
            Ok(info) => info,
            Err(e) => return Either::Right(once(Err(e))),
        };
        let hmonitors = match enum_display_monitors() {
            Ok(monitors) => monitors,
            Err(e) => return Either::Right(once(Err(e))),
        };
        Either::Left(
            hmonitors
                .into_iter()
                .flat_map(move |hmonitor| {
                    let physical_monitors = match get_physical_monitors_from_hmonitor(hmonitor) {
                        Ok(p) => p,
                        Err(e) => return vec![Err(e)],
                    };
                    let display_devices = match get_display_devices_from_hmonitor(hmonitor) {
                        Ok(p) => p,
                        Err(e) => return vec![Err(e)],
                    };
                    if display_devices.len() != physical_monitors.len() {
                        // There doesn't seem to be any way to directly associate a physical monitor
                        // handle with the equivalent display device, other than by array indexing
                        // https://stackoverflow.com/questions/63095216/how-to-associate-physical-monitor-with-monitor-deviceid
                        return vec![Err(SysError::EnumerationMismatch)];
                    }
                    physical_monitors
                        .into_iter()
                        .zip(display_devices)
                        .filter_map(|(physical_monitor, display_device)| {
                            get_file_handle_for_display_device(&display_device)
                                .transpose()
                                .map(|file_handle| (physical_monitor, display_device, file_handle))
                        })
                        .map(|(physical_monitor, display_device, file_handle)| {
                            let file_handle = file_handle?;
                            let info = device_info_map
                                .get(&display_device.DeviceID)
                                .ok_or(SysError::DeviceInfoMissing)?;
                            Ok(BlockingDeviceImpl {
                                physical_monitor,
                                file_handle,
                                device_name: wchar_to_string(&display_device.DeviceName),
                                friendly_name: wchar_to_string(&info.monitorFriendlyDeviceName),
                                device_description: wchar_to_string(&display_device.DeviceString),
                                device_key: wchar_to_string(&display_device.DeviceKey),
                                device_path: wchar_to_string(&display_device.DeviceID),
                                output_technology: info.outputTechnology,
                            })
                        })
                        .collect()
                })
                .collect::<Vec<_>>()
                .into_iter(),
        )
    }
}

/// Returns a `HashMap` of Device Path to `DISPLAYCONFIG_TARGET_DEVICE_NAME`.\
/// This can be used to find the `DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY` for a monitor.\
/// The output technology is used to determine if a device is internal or external.
unsafe fn get_device_info_map()
-> Result<HashMap<[u16; 128], DISPLAYCONFIG_TARGET_DEVICE_NAME>, SysError> {
    let mut path_count = 0;
    let mut mode_count = 0;
    check_status(
        unsafe {
            GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)
        },
        SysError::GetDisplayConfigBufferSizes,
    )?;
    let mut display_paths = vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
    let mut display_modes = vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
    check_status(
        unsafe {
            QueryDisplayConfig(
                QDC_ONLY_ACTIVE_PATHS,
                &mut path_count,
                display_paths.as_mut_ptr(),
                &mut mode_count,
                display_modes.as_mut_ptr(),
                None,
            )
        },
        SysError::QueryDisplayConfig,
    )?;
    display_modes
        .into_iter()
        .filter(|mode| mode.infoType == DISPLAYCONFIG_MODE_INFO_TYPE_TARGET)
        .flat_map(|mode| {
            let mut device_name = DISPLAYCONFIG_TARGET_DEVICE_NAME::default();
            device_name.header.size = size_of::<DISPLAYCONFIG_TARGET_DEVICE_NAME>() as u32;
            device_name.header.adapterId = mode.adapterId;
            device_name.header.id = mode.id;
            device_name.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
            let result =
                to_win32_error(unsafe { DisplayConfigGetDeviceInfo(&mut device_name.header) });
            match result {
                ERROR_SUCCESS => Some(Ok((device_name.monitorDevicePath, device_name))),
                // This error occurs if the calling process does not have access to the current desktop or is running on a remote session.
                ERROR_ACCESS_DENIED => None,
                _ => Some(Err(SysError::DisplayConfigGetDeviceInfo(result.into()))),
            }
        })
        .collect()
}

/// Calls `EnumDisplayMonitors` and returns a list of `HMONITOR` handles.\
/// Note that a `HMONITOR` is a logical construct that may correspond to multiple physical monitors.\
/// e.g. when in "Duplicate" mode two physical monitors will belong to the same `HMONITOR`
unsafe fn enum_display_monitors() -> Result<Vec<HMONITOR>, SysError> {
    unsafe extern "system" fn enum_monitors(
        handle: HMONITOR,
        _: HDC,
        _: *mut RECT,
        data: LPARAM,
    ) -> BOOL {
        let monitors = unsafe { &mut *(data.0 as *mut Vec<HMONITOR>) };
        monitors.push(handle);
        true.into()
    }
    let mut hmonitors = Vec::<HMONITOR>::new();
    unsafe {
        EnumDisplayMonitors(
            None,
            None,
            Some(enum_monitors),
            LPARAM(&mut hmonitors as *mut _ as isize),
        )
    }
    .ok()
    .map_err(SysError::EnumDisplayMonitors)?;
    Ok(hmonitors)
}

/// Gets the list of `PHYSICAL_MONITOR` handles that belong to a `HMONITOR`.\
/// These handles are required for use with the DDC/CI functions, however a valid handle will still
/// be returned for non DDC/CI monitors and also Remote Desktop Session displays.\
/// Also note that physically connected but disabled (inactive) monitors are not returned from this API.
unsafe fn get_physical_monitors_from_hmonitor(
    hmonitor: HMONITOR,
) -> Result<Vec<WrappedPhysicalMonitor>, SysError> {
    let mut physical_number: u32 = 0;
    unsafe { GetNumberOfPhysicalMonitorsFromHMONITOR(hmonitor, &mut physical_number) }
        .map_err(SysError::GetPhysicalMonitors)?;
    let mut raw_physical_monitors = vec![PHYSICAL_MONITOR::default(); physical_number as usize];
    // Allocate first so that pushing the wrapped handles always succeeds.
    let mut physical_monitors = Vec::with_capacity(raw_physical_monitors.len());
    unsafe { GetPhysicalMonitorsFromHMONITOR(hmonitor, &mut raw_physical_monitors) }
        .map_err(SysError::GetPhysicalMonitors)?;
    // Transform immediately into WrappedPhysicalMonitor so the handles don't leak
    raw_physical_monitors
        .into_iter()
        .for_each(|pm| physical_monitors.push(WrappedPhysicalMonitor(pm.hPhysicalMonitor)));
    Ok(physical_monitors)
}

/// Gets the list of display devices that belong to a `HMONITOR`.\
/// Due to the `EDD_GET_DEVICE_INTERFACE_NAME` flag, the `DISPLAY_DEVICEW` will contain the DOS
/// device path for each monitor in the `DeviceID` field.\
/// Note: Connected but inactive displays have been filtered out.
unsafe fn get_display_devices_from_hmonitor(
    hmonitor: HMONITOR,
) -> Result<Vec<DISPLAY_DEVICEW>, SysError> {
    let mut info = MONITORINFOEXW::default();
    info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32;
    let info_ptr = &mut info as *mut _ as *mut MONITORINFO;
    unsafe { GetMonitorInfoW(hmonitor, info_ptr) }
        .ok()
        .map_err(SysError::GetMonitorInfo)?;
    Ok((0..)
        .map_while(|device_number| {
            let mut device = DISPLAY_DEVICEW {
                cb: size_of::<DISPLAY_DEVICEW>() as u32,
                ..Default::default()
            };
            unsafe {
                EnumDisplayDevicesW(
                    PCWSTR(info.szDevice.as_ptr()),
                    device_number,
                    &mut device,
                    EDD_GET_DEVICE_INTERFACE_NAME,
                )
            }
            .as_bool()
            .then_some(device)
        })
        .filter(|device| flag_set(device.StateFlags, DISPLAY_DEVICE_ACTIVE))
        .collect())
}

/// Opens and returns a file handle for a display device using its DOS device path.\
/// These handles are only used for the `DeviceIoControl` API (for internal displays); a
/// handle can still be returned for external displays, but it should not be used.\
/// A `None` value means that a handle could not be opened, but this was for an expected reason,
/// indicating this display device should be skipped.
unsafe fn get_file_handle_for_display_device(
    display_device: &DISPLAY_DEVICEW,
) -> Result<Option<WrappedFileHandle>, SysError> {
    unsafe {
        CreateFileW(
            PCWSTR(display_device.DeviceID.as_ptr()),
            (FILE_GENERIC_READ | FILE_GENERIC_WRITE).0,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            None,
            OPEN_EXISTING,
            Default::default(),
            None,
        )
    }
    .map(|h| Some(WrappedFileHandle(h)))
    .or_else(|e| {
        // This error occurs for virtual devices e.g. Remote Desktop
        // sessions - they are not real monitors
        (e.code() == ERROR_ACCESS_DENIED.to_hresult())
            .then_some(None)
            .ok_or_else(|| SysError::OpeningMonitorDeviceInterfaceHandle {
                device_name: wchar_to_string(&display_device.DeviceName),
                source: e,
            })
    })
}

#[derive(Clone, Debug, Error)]
pub(crate) enum SysError {
    #[error("Failed to enumerate device monitors")]
    EnumDisplayMonitors(#[source] WinError),
    #[error("Failed to get display config buffer sizes")]
    GetDisplayConfigBufferSizes(#[source] WinError),
    #[error("Failed to query display config")]
    QueryDisplayConfig(#[source] WinError),
    #[error("Failed to get display config device info")]
    DisplayConfigGetDeviceInfo(#[source] WinError),
    #[error("Failed to get monitor info")]
    GetMonitorInfo(#[source] WinError),
    #[error("Failed to get physical monitors from the HMONITOR")]
    GetPhysicalMonitors(#[source] WinError),
    #[error(
        "The length of GetPhysicalMonitorsFromHMONITOR() and EnumDisplayDevicesW() results did not \
     match, this could be because monitors were connected/disconnected while loading devices"
    )]
    EnumerationMismatch,
    #[error(
        "Unable to find a matching device info for this display device, this could be because monitors \
     were connected while loading devices"
    )]
    DeviceInfoMissing,
    #[error("Failed to open monitor interface handle (CreateFileW)")]
    OpeningMonitorDeviceInterfaceHandle {
        device_name: String,
        source: WinError,
    },
    #[error("Failed to query supported brightness (IOCTL)")]
    IoctlQuerySupportedBrightness {
        device_name: String,
        source: WinError,
    },
    #[error("Failed to query display brightness (IOCTL)")]
    IoctlQueryDisplayBrightness {
        device_name: String,
        source: WinError,
    },
    #[error("Unexpected response when querying display brightness (IOCTL)")]
    IoctlQueryDisplayBrightnessUnexpectedResponse { device_name: String },
    #[error("Failed to get monitor brightness (DDCCI)")]
    GettingMonitorBrightness {
        device_name: String,
        source: WinError,
    },
    #[error("Failed to set monitor brightness (IOCTL)")]
    IoctlSetBrightness {
        device_name: String,
        source: WinError,
    },
    #[error("Failed to set monitor brightness (DDCCI)")]
    SettingBrightness {
        device_name: String,
        source: WinError,
    },
}

impl From<SysError> for Error {
    fn from(e: SysError) -> Self {
        match &e {
            SysError::EnumerationMismatch
            | SysError::DeviceInfoMissing
            | SysError::GetDisplayConfigBufferSizes(..)
            | SysError::QueryDisplayConfig(..)
            | SysError::DisplayConfigGetDeviceInfo(..)
            | SysError::GetPhysicalMonitors(..)
            | SysError::EnumDisplayMonitors(..)
            | SysError::GetMonitorInfo(..)
            | SysError::OpeningMonitorDeviceInterfaceHandle { .. } => {
                Error::ListingDevices(Box::new(e))
            }
            SysError::IoctlQuerySupportedBrightness { device_name, .. }
            | SysError::IoctlQueryDisplayBrightness { device_name, .. }
            | SysError::IoctlQueryDisplayBrightnessUnexpectedResponse { device_name }
            | SysError::GettingMonitorBrightness { device_name, .. } => Error::GettingDeviceInfo {
                device: device_name.clone(),
                source: Box::new(e),
            },
            SysError::SettingBrightness { device_name, .. }
            | SysError::IoctlSetBrightness { device_name, .. } => Error::SettingBrightness {
                device: device_name.clone(),
                source: Box::new(e),
            },
        }
    }
}

fn wchar_to_string(s: &[u16]) -> String {
    let end = s.iter().position(|&x| x == 0).unwrap_or(s.len());
    let truncated = &s[0..end];
    OsString::from_wide(truncated).to_string_lossy().into()
}

fn to_win32_error(status: i32) -> WIN32_ERROR {
    WIN32_ERROR(status as u32)
}

fn check_status<F, E>(status: WIN32_ERROR, f: F) -> Result<(), E>
where
    F: FnOnce(WinError) -> E,
{
    status.ok().map_err(f)
}

#[derive(Debug, Default)]
struct DdcciBrightnessValues {
    min: u32,
    current: u32,
    max: u32,
}

impl DdcciBrightnessValues {
    fn get_current_percentage(&self) -> u32 {
        let normalised_max = (self.max - self.min) as f64;
        let normalised_current = (self.current - self.min) as f64;
        (normalised_current / normalised_max * 100.0).round() as u32
    }

    fn percentage_to_current(&self, percentage: u32) -> u32 {
        let normalised_max = (self.max - self.min) as f64;
        let fraction = percentage as f64 / 100.0;
        let normalised_current = fraction * normalised_max;
        normalised_current.round() as u32 + self.min
    }
}

fn ddcci_get_monitor_brightness(
    device: &BlockingDeviceImpl,
) -> Result<DdcciBrightnessValues, SysError> {
    unsafe {
        let mut v = DdcciBrightnessValues::default();
        BOOL(GetMonitorBrightness(
            device.physical_monitor.0,
            &mut v.min,
            &mut v.current,
            &mut v.max,
        ))
        .ok()
        .map(|_| v)
        .map_err(|e| SysError::GettingMonitorBrightness {
            device_name: device.device_name.clone(),
            source: e,
        })
    }
}

fn ddcci_set_monitor_brightness(device: &BlockingDeviceImpl, value: u32) -> Result<(), SysError> {
    unsafe {
        BOOL(SetMonitorBrightness(device.physical_monitor.0, value))
            .ok()
            .map_err(|e| SysError::SettingBrightness {
                device_name: device.device_name.clone(),
                source: e,
            })
    }
}

/// Each level is a value from 0 to 100
#[derive(Debug)]
struct IoctlSupportedBrightnessLevels(Vec<u8>);

impl IoctlSupportedBrightnessLevels {
    fn get_nearest(&self, percentage: u32) -> u8 {
        self.0
            .iter()
            .copied()
            .min_by_key(|&num| (num as i64 - percentage as i64).abs())
            .unwrap_or(0)
    }
}

fn ioctl_query_supported_brightness(
    device: &BlockingDeviceImpl,
) -> Result<IoctlSupportedBrightnessLevels, SysError> {
    unsafe {
        let mut bytes_returned = 0;
        let mut out_buffer = Vec::<u8>::with_capacity(256);
        DeviceIoControl(
            device.file_handle.0,
            IOCTL_VIDEO_QUERY_SUPPORTED_BRIGHTNESS,
            None,
            0,
            Some(out_buffer.as_mut_ptr() as *mut c_void),
            out_buffer.capacity() as u32,
            Some(&mut bytes_returned),
            None,
        )
        .map(|_| {
            out_buffer.set_len(bytes_returned as usize);
            IoctlSupportedBrightnessLevels(out_buffer)
        })
        .map_err(|e| SysError::IoctlQuerySupportedBrightness {
            device_name: device.device_name.clone(),
            source: e,
        })
    }
}

fn ioctl_query_display_brightness(device: &BlockingDeviceImpl) -> Result<u32, SysError> {
    unsafe {
        let mut bytes_returned = 0;
        let mut display_brightness = DISPLAY_BRIGHTNESS::default();
        DeviceIoControl(
            device.file_handle.0,
            IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS,
            None,
            0,
            Some(&mut display_brightness as *mut DISPLAY_BRIGHTNESS as *mut c_void),
            size_of::<DISPLAY_BRIGHTNESS>() as u32,
            Some(&mut bytes_returned),
            None,
        )
        .map_err(|e| SysError::IoctlQueryDisplayBrightness {
            device_name: device.device_name.clone(),
            source: e,
        })
        .and_then(|_| match display_brightness.ucDisplayPolicy as u32 {
            DISPLAYPOLICY_AC => {
                // This is a value between 0 and 100.
                Ok(display_brightness.ucACBrightness as u32)
            }
            DISPLAYPOLICY_DC => {
                // This is a value between 0 and 100.
                Ok(display_brightness.ucDCBrightness as u32)
            }
            _ => Err(SysError::IoctlQueryDisplayBrightnessUnexpectedResponse {
                device_name: device.device_name.clone(),
            }),
        })
    }
}

fn ioctl_set_display_brightness(device: &BlockingDeviceImpl, value: u8) -> Result<(), SysError> {
    // Seems to currently be missing from metadata
    const DISPLAYPOLICY_BOTH: u8 = 3;
    unsafe {
        let mut display_brightness = DISPLAY_BRIGHTNESS {
            ucACBrightness: value,
            ucDCBrightness: value,
            ucDisplayPolicy: DISPLAYPOLICY_BOTH,
        };
        let mut bytes_returned = 0;
        DeviceIoControl(
            device.file_handle.0,
            IOCTL_VIDEO_SET_DISPLAY_BRIGHTNESS,
            Some(&mut display_brightness as *mut DISPLAY_BRIGHTNESS as *mut c_void),
            size_of::<DISPLAY_BRIGHTNESS>() as u32,
            None,
            0,
            Some(&mut bytes_returned),
            None,
        )
        .map(|_| {
            // There is a bug where if the IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS is
            // called immediately after then it won't show the newly updated values
            // Doing a very tiny sleep seems to mitigate this
            std::thread::sleep(std::time::Duration::from_nanos(1));
        })
        .map_err(|e| SysError::IoctlSetBrightness {
            device_name: device.device_name.clone(),
            source: e,
        })
    }
}

impl BrightnessExt for BrightnessDevice {
    fn device_description(&self) -> Result<String, Error> {
        Ok(self.0.device_description.clone())
    }

    fn device_registry_key(&self) -> Result<String, Error> {
        Ok(self.0.device_key.clone())
    }

    fn device_path(&self) -> Result<String, Error> {
        Ok(self.0.device_path.clone())
    }
}