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
//! # CRTC
//!
//! A CRTC is a display controller provided by your device. It's primary job is
//! to take pixel data and send it to a connector with the proper resolution and
//! frequencies.
//!
//! Specific CRTCs can only be attached to connectors that have an encoder it
//! supports. For example, you can have a CRTC that can not output to analog
//! connectors. These are built in hardware limitations.
//!
//! Each CRTC has a built in plane, which can be attached to a framebuffer. It
//! can also use pixel data from other planes to perform hardware compositing.

use iPoint;
use buffer;
use control::{self, ResourceHandle, ResourceInfo};
use result::*;
use ffi;

use control::framebuffer::Handle as FBHandle;
use control::connector::Handle as ConHandle;

use std::any::Any;
use std::boxed::Box;
use std::io::Read;
use std::mem;
use std::time::Duration;

/// A [`ResourceHandle`] for a CRTC.
///
/// Like all control resources, every CRTC has a unique `Handle` associated with
/// it. This `Handle` can be used to acquire information about the CRTC (see
/// [`crtc::Info`]) or change the CRTC's state.
///
/// These can be retrieved by using [`ResourceIds::crtcs`].
///
/// [`ResourceHandle`]: ResourceHandle.t.html
/// [`crtc::Info`]: Info.t.html
/// [`ResourceIds::crtcs`]: ResourceIds.t.html#method.crtcs
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, From, Into)]
pub struct Handle(control::RawHandle);
impl ResourceHandle for Handle {}

/// A [`ResourceInfo`] for a CRTC.
///
/// [`ResourceInfo`]: ResourceInfo.t.html
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Info {
    handle: Handle,
    position: (u32, u32),
    mode: Option<control::Mode>,
    fb: control::framebuffer::Handle,
    gamma_length: u32,
}

impl Info {
    /// Returns the current position
    pub fn position(&self) -> (u32, u32) {
        self.position
    }

    /// Returns the currently set [`Mode`].
    ///
    /// [`Mode`]: ../Mode.t.html
    pub fn mode(&self) -> Option<control::Mode> {
        self.mode.clone()
    }

    /// Returns the currently active framebuffer
    pub fn fb(&self) -> FBHandle {
        self.fb
    }
}

impl control::property::LoadProperties for Handle {
    const TYPE: u32 = ffi::DRM_MODE_OBJECT_CRTC;
}

impl ResourceInfo for Info {
    type Handle = Handle;

    fn load_from_device<T>(device: &T, handle: Handle) -> Result<Self>
    where
        T: control::Device,
    {
        let crtc = {
            let mut raw: ffi::drm_mode_crtc = Default::default();
            raw.crtc_id = handle.0;
            unsafe {
                try!(ffi::ioctl_mode_getcrtc(device.as_raw_fd(), &mut raw));
            }

            Self {
                handle: handle,
                position: (raw.x, raw.y),
                mode: if raw.mode_valid != 0 {
                    Some(control::Mode {
                        mode: raw.mode.clone(),
                    })
                } else {
                    None
                },
                fb: control::framebuffer::Handle::from(raw.fb_id),
                gamma_length: raw.gamma_size,
            }
        };

        Ok(crtc)
    }

    fn handle(&self) -> Self::Handle {
        self.handle
    }
}

/// Attaches a framebuffer to a CRTC's built-in plane, attaches the CRTC to
/// a connector, and sets the CRTC's mode to output the pixel data.
pub fn set<T>(
    device: &T,
    handle: Handle,
    fb: FBHandle,
    cons: &[ConHandle],
    position: (u32, u32),
    mode: Option<control::Mode>,
) -> Result<()>
where
    T: control::Device,
{
    let mut raw: ffi::drm_mode_crtc = Default::default();
    raw.x = position.0;
    raw.y = position.1;
    raw.crtc_id = handle.into();
    raw.fb_id = fb.into();
    raw.set_connectors_ptr = cons.as_ptr() as u64;
    raw.count_connectors = cons.len() as u32;

    match mode {
        Some(m) => {
            raw.mode = m.mode;
            raw.mode_valid = 1;
        }
        _ => (),
    };

    unsafe {
        try!(ffi::ioctl_mode_setcrtc(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Flags to alter the behaviour of a page flip
pub enum PageFlipFlags {
    /// Request a vblank event on page flip
    PageFlipEvent = ffi::DRM_MODE_PAGE_FLIP_EVENT,
    /// Request page flip as soon as possible, not waiting for vblank
    PageFlipAsync = ffi::DRM_MODE_PAGE_FLIP_ASYNC,
}

/// Queue a page flip on the given crtc.
///
/// On the next vblank the given framebuffer will be attached to the
/// crtc and an event will be triggered by the device, which will be indicated by it's fd becoming
/// readable. The event can be received using `handle_event`.
pub fn page_flip<T>(device: &T, handle: Handle, fb: FBHandle, flags: &[PageFlipFlags]) -> Result<()>
where
    T: control::Device,
{
    let mut raw: ffi::drm_mode_crtc_page_flip = Default::default();
    raw.fb_id = fb.into();
    raw.crtc_id = handle.into();
    raw.flags = flags.into_iter().fold(0, |val, flag| val | *flag as u32);
    raw.user_data = handle.0 as u64;

    unsafe {
        try!(ffi::ioctl_mode_page_flip(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

/// Iterator over `Event`s of a device. Create via `receive_events`.
pub struct Events {
    event_buf: [u8; 1024],
    amount: usize,
    i: usize,
}

/// An event from a device.
pub enum Event {
    /// A vblank happened
    Vblank(VblankEvent),
    /// A page flip happened
    PageFlip(PageFlipEvent),
    /// Unknown event, raw data provided
    Unknown(Vec<u8>),
}

/// Vblank event
pub struct VblankEvent {
    /// sequence of the frame
    pub frame: u32,
    /// duration between events
    pub duration: Duration,
    /// crtc that did throw the event
    pub crtc: Handle,
}

/// Page Flip event
pub struct PageFlipEvent {
    /// sequence of the frame
    pub frame: u32,
    /// duration between events
    pub duration: Duration,
    /// crtc that did throw the event
    pub crtc: Handle,
}

impl Iterator for Events {
    type Item = Event;

    fn next(&mut self) -> Option<Event> {
        if self.amount > 0 && self.i < self.amount {
            let event = unsafe {
                &*(self.event_buf.as_ptr().offset(self.i as isize) as *const ffi::drm_event)
            };
            self.i += event.length as usize;
            match event.type_ {
                x if x == ffi::DRM_EVENT_VBLANK => {
                    let vblank_event: &ffi::drm_event_vblank =
                        unsafe { mem::transmute(event) };
                    Some(Event::Vblank(VblankEvent {
                        frame: vblank_event.sequence,
                        duration: Duration::new(
                            vblank_event.tv_sec as u64,
                            vblank_event.tv_usec * 100,
                        ),
                        crtc: Handle::from(vblank_event.user_data as u32),
                    }))
                }
                x if x == ffi::DRM_EVENT_FLIP_COMPLETE => {
                    let vblank_event: &ffi::drm_event_vblank =
                        unsafe { mem::transmute(event) };
                    Some(Event::PageFlip(PageFlipEvent {
                        frame: vblank_event.sequence,
                        duration: Duration::new(
                            vblank_event.tv_sec as u64,
                            vblank_event.tv_usec * 1000,
                        ),
                        crtc: Handle::from(if vblank_event.crtc_id != 0 {
                            vblank_event.crtc_id
                        } else {
                            vblank_event.user_data as u32
                        }),
                    }))
                }
                _ => Some(Event::Unknown(
                    self.event_buf[self.i - (event.length as usize)..self.i].to_vec(),
                )),
            }
        } else {
            None
        }
    }
}

/// Receives all pending events of a given device and returns an Iterator for them.
pub fn receive_events<T>(device: &T) -> Result<Events>
where
    T: control::Device,
{
    struct DeviceWrapper<'a, T: control::Device + 'a>(&'a T);
    impl<'a, T: control::Device> Read for DeviceWrapper<'a, T> {
        fn read(&mut self, buf: &mut [u8]) -> ::std::io::Result<usize> {
            ::nix::unistd::read(self.0.as_raw_fd(), buf).map_err(|err| match err {
                ::nix::Error::Sys(_) => ::std::io::Error::last_os_error(),
                err => ::std::io::Error::new(::std::io::ErrorKind::Other, err),
            })
        }
    }
    let mut wrapper = DeviceWrapper(device);

    let mut event_buf: [u8; 1024] = [0; 1024];
    let amount = try!(wrapper.read(&mut event_buf));

    Ok(Events {
        event_buf,
        amount,
        i: 0,
    })
}

/// Sets a hardware-cursor on the given crtc with the image of a given buffer
pub fn set_cursor<T, B>(device: &T, handle: Handle, buffer: &B) -> Result<()>
where
    T: control::Device,
    B: buffer::Buffer + ?Sized,
{
    let dimensions = buffer.size();

    let mut raw: ffi::drm_mode_cursor = Default::default();
    raw.flags = ffi::DRM_MODE_CURSOR_BO;
    raw.crtc_id = handle.into();
    raw.width = dimensions.0;
    raw.height = dimensions.1;
    raw.handle = buffer.handle().into();

    unsafe {
        try!(ffi::ioctl_mode_cursor(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

/// Sets a hardware-cursor on the given crtc with the image of a given buffer and a hotspot marking
/// the click point of the cursor
pub fn set_cursor2<T, B>(device: &T, handle: Handle, buffer: &B, hotspot: iPoint) -> Result<()>
where
    T: control::Device,
    B: buffer::Buffer + ?Sized,
{
    let dimensions = buffer.size();

    let mut raw: ffi::drm_mode_cursor2 = Default::default();
    raw.flags = ffi::DRM_MODE_CURSOR_BO;
    raw.crtc_id = handle.into();
    raw.width = dimensions.0;
    raw.height = dimensions.1;
    raw.handle = buffer.handle().into();
    raw.hot_x = hotspot.0;
    raw.hot_y = hotspot.1;

    unsafe {
        try!(ffi::ioctl_mode_cursor2(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

/// Moves a set cursor on a given crtc
pub fn move_cursor<T>(device: &T, handle: Handle, to: iPoint) -> Result<()>
where
    T: control::Device,
{
    let mut raw: ffi::drm_mode_cursor = Default::default();
    raw.flags = ffi::DRM_MODE_CURSOR_MOVE;
    raw.crtc_id = handle.into();
    raw.x = to.0;
    raw.y = to.1;

    unsafe {
        try!(ffi::ioctl_mode_cursor(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

/// Clears any hardware-cursor on the given crtc
pub fn clear_cursor<T>(device: &T, handle: Handle) -> Result<()>
where
    T: control::Device,
{
    let mut raw: ffi::drm_mode_cursor = Default::default();
    raw.flags = ffi::DRM_MODE_CURSOR_BO;
    raw.crtc_id = handle.into();
    raw.width = 0;
    raw.height = 0;
    raw.handle = 0;

    unsafe {
        try!(ffi::ioctl_mode_cursor(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}

#[derive(Debug, Clone)]
/// The hardware gamma ramp
pub struct GammaRamp {
    /// Red color component
    pub red: Box<[u16]>,
    /// Green color component
    pub green: Box<[u16]>,
    /// Blue color component
    pub blue: Box<[u16]>,
}

/// Receive the currently set gamma ramp of a crtc
pub fn gamma<T>(device: &T, handle: Handle) -> Result<GammaRamp>
where
    T: control::Device,
{
    let info = Info::load_from_device(device, handle)?;

    let mut raw: ffi::drm_mode_crtc_lut = Default::default();
    raw.crtc_id = handle.into();
    raw.gamma_size = info.gamma_length;
    let red = ffi_buf!(raw.red, info.gamma_length as usize);
    let green = ffi_buf!(raw.green, info.gamma_length as usize);
    let blue = ffi_buf!(raw.blue, info.gamma_length as usize);

    unsafe {
        try!(ffi::ioctl_mode_getgamma(device.as_raw_fd(), &mut raw));
    }

    Ok(GammaRamp {
        red: red.into_boxed_slice(),
        green: green.into_boxed_slice(),
        blue: blue.into_boxed_slice(),
    })
}

/// Set a gamma ramp for the given crtc
pub fn set_gamma<T>(device: &T, handle: Handle, mut gamma: GammaRamp) -> Result<()>
where
    T: control::Device,
{
    let info = Info::load_from_device(device, handle)?;

    if gamma.red.len() as u32 != info.gamma_length {
        return Err(Error::from_kind(ErrorKind::InvalidGammaSize(
            gamma.red.len(),
            info.gamma_length,
        )));
    }

    if gamma.green.len() as u32 != info.gamma_length {
        return Err(Error::from_kind(
            ErrorKind::InvalidGammaSize(gamma.green.len(), info.gamma_length).into(),
        ));
    }

    if gamma.blue.len() as u32 != info.gamma_length {
        return Err(Error::from_kind(
            ErrorKind::InvalidGammaSize(gamma.blue.len(), info.gamma_length).into(),
        ));
    }

    let mut raw: ffi::drm_mode_crtc_lut = Default::default();
    raw.crtc_id = handle.into();
    raw.gamma_size = info.gamma_length;
    raw.red = gamma.red.as_mut_ptr() as u64;
    raw.green = gamma.green.as_mut_ptr() as u64;
    raw.blue = gamma.blue.as_mut_ptr() as u64;

    unsafe {
        try!(ffi::ioctl_mode_setgamma(device.as_raw_fd(), &mut raw));
    }

    Ok(())
}