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
use std::{mem, fmt};
use std::borrow::Cow;
use std::ffi::{CStr, CString};
use libc::{self, c_int, c_char};
use {sys, Error, Status, FeatureCode, Capabilities, Value};

#[derive(Clone)]
pub struct DisplayInfo {
    handle: sys::DDCA_Display_Ref,
    display_number: i32,
    manufacturer_id: Vec<u8>,
    model_name: Vec<u8>,
    serial_number: Vec<u8>,
    edid: Box<[u8]>,
    path: DisplayPath,
}

unsafe impl Send for DisplayInfo { }
unsafe impl Sync for DisplayInfo { }

impl DisplayInfo {
    pub fn open(&self) -> ::Result<Display> {
        unsafe {
            let mut handle = mem::uninitialized();
            let status = sys::ddca_open_display(self.handle, &mut handle as *mut _);
            Error::from_status(status).map(|_| Display::from_raw(handle))
        }
    }

    pub unsafe fn from_raw(raw: &sys::DDCA_Display_Info) -> Self {
        fn from_ptr(ptr: *const c_char) -> Vec<u8> {
            if ptr.is_null() {
                Default::default()
            } else {
                unsafe {
                    CStr::from_ptr(ptr).to_bytes().to_owned()
                }
            }
        }

        DisplayInfo {
            handle: raw.dref,
            display_number: raw.dispno,
            manufacturer_id: from_ptr(raw.mfg_id),
            model_name: from_ptr(raw.model_name),
            serial_number: from_ptr(raw.sn),
            edid: raw.edid_bytes().to_owned().into(),
            path: DisplayPath::from_raw(&raw.path, raw.usb_bus, raw.usb_device)
                .unwrap_or_else(|_| DisplayPath::Usb {
                    // stupid fallback, but should never happen...
                    bus_number: raw.usb_bus,
                    device_number: raw.usb_device,
                    hiddev_device_number: -1,
                }),
        }
    }

    pub fn enumerate() -> ::Result<DisplayInfoList> {
        unsafe {
            let res = sys::ddca_get_display_info_list();
            if res.is_null() {
                Err(Error::new(Status::new(libc::EINVAL)))
            } else {
                Ok(DisplayInfoList::from_raw(res))
            }
        }
    }

    pub fn raw(&self) -> sys::DDCA_Display_Ref {
        self.handle
    }

    pub fn display_number(&self) -> i32 {
        self.display_number
    }

    pub fn manufacturer_id(&self) -> Cow<str> {
        String::from_utf8_lossy(&self.manufacturer_id)
    }

    pub fn manufacturer_id_bytes(&self) -> &[u8] {
        &self.manufacturer_id
    }

    pub fn model_name(&self) -> Cow<str> {
        String::from_utf8_lossy(&self.model_name)
    }

    pub fn model_name_bytes(&self) -> &[u8] {
        &self.model_name
    }

    pub fn serial_number(&self) -> Cow<str> {
        String::from_utf8_lossy(&self.serial_number)
    }

    pub fn serial_number_bytes(&self) -> &[u8] {
        &self.serial_number
    }

    pub fn edid(&self) -> &[u8] {
        &self.edid
    }

    pub fn path(&self) -> DisplayPath {
        self.path
    }
}

impl fmt::Debug for DisplayInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("DisplayInfo")
            .field("display_number", &self.display_number)
            .field("manufacturer_id", &self.manufacturer_id())
            .field("model_name", &self.model_name())
            .field("serial_number", &self.serial_number())
            .field("path", &self.path())
            .finish()
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DisplayPath {
    I2c {
        bus_number: i32,
    },
    Usb {
        bus_number: i32,
        device_number: i32,
        hiddev_device_number: i32,
    },
    Adl {
        adapter_index: i32,
        display_index: i32,
    },
}

impl DisplayPath {
    pub fn from_raw(path: &sys::DDCA_IO_Path, usb_bus: c_int, usb_device: c_int) -> Result<Self, ()> {
        match path.io_mode {
            sys::DDCA_IO_DEVI2C => Ok(DisplayPath::I2c {
                bus_number: path.i2c_busno(),
            }),
            sys::DDCA_IO_USB => Ok(DisplayPath::Usb {
                bus_number: usb_bus as _,
                device_number: usb_device as _,
                hiddev_device_number: path.hiddev_devno(),
            }),
            sys::DDCA_IO_ADL => Ok(DisplayPath::Adl {
                adapter_index: path.adlno().iAdapterIndex,
                display_index: path.adlno().iDisplayIndex,
            }),
            _ => Err(()),
        }
    }
}

pub struct DisplayInfoList {
    handle: *mut sys::DDCA_Display_Info_List,
}

unsafe impl Send for DisplayInfoList { }
unsafe impl Sync for DisplayInfoList { }

impl fmt::Debug for DisplayInfoList {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_list().entries(self.into_iter()).finish()
    }
}

impl DisplayInfoList {
    pub unsafe fn from_raw(handle: *mut sys::DDCA_Display_Info_List) -> Self {
        DisplayInfoList {
            handle: handle,
        }
    }

    pub fn raw(&self) -> &sys::DDCA_Display_Info_List {
        unsafe { &*self.handle }
    }

    pub fn len(&self) -> usize {
        self.raw().info().len() as usize
    }

    pub fn get(&self, index: usize) -> DisplayInfo {
        unsafe {
            DisplayInfo::from_raw(&self.raw().info()[index])
        }
    }
}

impl<'a> IntoIterator for &'a DisplayInfoList {
    type Item = DisplayInfo;
    type IntoIter = DisplayInfoIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        DisplayInfoIter {
            list: self,
            index: 0,
        }
    }
}

impl Drop for DisplayInfoList {
    fn drop(&mut self) {
        unsafe {
            sys::ddca_free_display_info_list(self.handle)
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct DisplayInfoIter<'a> {
    list: &'a DisplayInfoList,
    index: usize,
}

impl<'a> Iterator for DisplayInfoIter<'a> {
    type Item = DisplayInfo;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.list.len() {
            let index = self.index;
            self.index += 1;
            Some(self.list.get(index))
        } else {
            None
        }
    }
}

#[derive(Debug)]
pub struct Display {
    handle: sys::DDCA_Display_Handle,
}
unsafe impl Send for Display { }

impl Display {
    pub unsafe fn from_raw(handle: sys::DDCA_Display_Handle) -> Self {
        Display {
            handle: handle,
        }
    }

    pub fn capabilities_string(&self) -> ::Result<CString> {
        unsafe {
            let mut res = mem::uninitialized();
            Error::from_status(sys::ddca_get_capabilities_string(
                self.handle, &mut res
            ))?;
            let string = CStr::from_ptr(res).to_owned();
            libc::free(res as *mut _);
            Ok(string)
        }
    }

    pub fn capabilities(&self) -> ::Result<Capabilities> {
        self.capabilities_string().and_then(|c| Capabilities::from_cstr(&c))
    }

    pub fn vcp_set_simple(&self, code: FeatureCode, value: u8) -> ::Result<()> {
        unsafe {
            Error::from_status(sys::ddca_set_simple_nc_vcp_value(
                self.handle, code as _, value
            )).map(drop)
        }
    }

    pub fn vcp_set_raw(&self, code: FeatureCode, value: u16) -> ::Result<()> {
        unsafe {
            Error::from_status(sys::ddca_set_raw_vcp_value(
                self.handle, code as _, (value >> 8) as u8, value as u8
            )).map(drop)
        }
    }

    pub fn vcp_set_continuous(&self, code: FeatureCode, value: i32) -> ::Result<()> {
        unsafe {
            Error::from_status(sys::ddca_set_continuous_vcp_value(
                self.handle, code as _, value
            )).map(drop)
        }
    }

    pub fn vcp_get_value(&self, code: FeatureCode) -> ::Result<Value> {
        unsafe {
            let mut raw = mem::uninitialized();
            Error::from_status(sys::ddca_get_any_vcp_value(
                self.handle, code as _, sys::DDCA_NON_TABLE_VCP_VALUE_PARM, &mut raw
            ))?;
            let raw = &mut *raw;
            if raw.value_type != sys::DDCA_NON_TABLE_VCP_VALUE || raw.opcode != code {
                libc::free(raw as *mut _ as *mut _);
                return Err(Error::new(Status::new(libc::EINVAL)))
            }
            let value = Value::from_raw(raw.c_nc());
            libc::free(raw as *mut _ as *mut _);
            Ok(value)
        }
    }

    pub fn vcp_get_table(&self, code: FeatureCode) -> ::Result<Vec<u8>> {
        unsafe {
            let mut raw = mem::uninitialized();
            Error::from_status(sys::ddca_get_any_vcp_value(
                self.handle, code as _, sys::DDCA_TABLE_VCP_VALUE_PARM, &mut raw
            ))?;
            let raw = &mut *raw;
            if raw.value_type != sys::DDCA_TABLE_VCP_VALUE || raw.opcode != code {
                libc::free(raw as *mut _ as *mut _);
                return Err(Error::new(Status::new(libc::EINVAL)))
            }
            let value = raw.t().bytes().to_owned();
            libc::free(raw.t().bytes as *mut _);
            libc::free(raw as *mut _ as *mut _);
            Ok(value)
        }
    }

    pub fn raw(&self) -> sys::DDCA_Display_Handle {
        self.handle
    }
}

impl Drop for Display {
    fn drop(&mut self) {
        unsafe {
            sys::ddca_close_display(self.handle);
        }
    }
}

#[test]
fn test_displays() {
    for display in &DisplayInfo::enumerate().unwrap() {
        drop(display.open());
    }
}