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
use result::*;
use ffi;
use std::ffi::CStr;
use std::hash::Hash;
pub mod connector;
pub mod encoder;
pub mod crtc;
pub mod framebuffer;
pub mod plane;
pub mod property;
pub mod dumbbuffer;

/// The underlying id for a resource.
pub type RawHandle = u32;

#[derive(Clone, Copy, PartialEq, Eq)]
/// An array to hold the name of a property.
pub struct RawName([i8; 32]);

/// A trait for devices that provide control (modesetting) functionality.
pub trait Device : Sized + super::Device {
    /// See [`ResourceHandles::load_from_device`]
    ///
    /// [`ResourceHandles::load_from_device`]:
    ///     ResourceHandles.t.html#method.load_from_device
    fn resource_handles(&self) -> Result<ResourceHandles> {
        ResourceHandles::load_from_device(self)
    }

    /// See [`PlaneResourceHandles::load_from_device`]
    ///
    /// [`PlaneResourceHandles::load_from_device`]:
    ///     PlaneResourceHandles.t.html#method.load_from_device
    fn plane_handles(&self) -> Result<PlaneResourceHandles> {
        PlaneResourceHandles::load_from_device(self)
    }

    /// See [`ResourceInfo::load_from_device`]
    ///
    /// [`ResourceInfo::load_from_device`]:
    ///     ResourceInfo.t.html#method.load_from_device
    fn resource_info<T>(&self, handle: T::Handle) -> Result<T>
        where T: ResourceInfo {

        T::load_from_device(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.
    fn set_crtc(&self, crtc: crtc::Handle, fb: framebuffer::Handle,
                cons: &[connector::Handle], position: (u32, u32),
                mode: Option<Mode>) -> Result<()> {

        crtc::set(self, crtc, fb, cons, position, mode)
    }

    /// Creates a framebuffer from a [`Buffer`], returning
    /// [`framebuffer::Info`].
    ///
    /// [`Buffer`]: ../buffer/Buffer.t.html
    /// [`framebuffer::Info`]: framebuffer/Info.t.html
    fn create_framebuffer<U>(&self, buffer: &U) -> Result<framebuffer::Info>
        where U: super::buffer::Buffer {

        framebuffer::create(self, buffer)
    }
}

/// A generalization of a handle that represents an object managed by a `Device`.
///
/// In most cases, all objects and resources that are managed by a `Device`
/// provide some sort of handle that we can use to refer to them. Almost all
/// operations performed on a `Device` that use an object or resource require
/// making requests using a handle.
pub trait ResourceHandle: Eq + Copy + Hash {
    /// Create this handle from its raw part.
    fn from_raw(RawHandle) -> Self;

    /// Get the raw part from this handle.
    fn as_raw(&self) -> RawHandle;
}

/// Information about a resource or object managed by a `Device`.
///
/// Due to external events such as hot plugging, other tasks, and even buggy
/// drivers, object information could change at any time. In fact, there are no
/// guarantees that this resource has existed or will exist at any point in
/// time. A process should treat a `ResourceInfo` as merely a hint to the
/// current state of the `Device`.
pub trait ResourceInfo : Clone + Eq {
    /// The type of handle used to load this trait.
    type Handle: ResourceHandle;

    /// Load the resource from a `Device` given its `ResourceHandle`
    fn load_from_device<T>(&T, Self::Handle) -> Result<Self> where T: Device;

    /// Get the `ResourceHandle` for this resource.
    fn handle(&self) -> Self::Handle;
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The set of resource ids that are associated with a DRM device.
pub struct ResourceHandles {
    connectors: ffi::Buffer<connector::Handle>,
    encoders: ffi::Buffer<encoder::Handle>,
    crtcs: ffi::Buffer<crtc::Handle>,
    framebuffers: ffi::Buffer<framebuffer::Handle>,
    width: (u32, u32),
    height: (u32, u32)
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// The set of plane ids that are associated with a DRM device.
pub struct PlaneResourceHandles {
    planes: ffi::Buffer<plane::Handle>
}

impl ResourceHandles {
    /// Attempts to acquire a copy of the device's ResourceHandles.
    pub fn load_from_device<T>(device: &T) -> Result<Self> where T: Device {
        let fd = device.as_raw_fd();

        let ids = {
            let mut raw: ffi::drm_mode_card_res = Default::default();
            unsafe {
                ffi::ioctl_mode_getresources(fd, &mut raw)?
            };

            let ids = ResourceHandles {
                connectors: ffi_buf!(raw.connector_id_ptr,
                                     raw.count_connectors),
                encoders: ffi_buf!(raw.encoder_id_ptr, raw.count_encoders),
                crtcs: ffi_buf!(raw.crtc_id_ptr, raw.count_crtcs),
                framebuffers: ffi_buf!(raw.fb_id_ptr, raw.count_fbs),
                width: (raw.min_width, raw.max_width),
                height: (raw.min_height, raw.max_height)
            };

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

            ids
        };

        Ok(ids)
    }

    /// Returns a slice to the list of connector handles.
    pub fn connectors<'a>(&'a self) -> &'a [connector::Handle] {
        &self.connectors
    }

    /// Returns a slice to the list of encoder handle.
    pub fn encoders<'a>(&'a self) -> &'a [encoder::Handle] {
        &self.encoders
    }

    /// Returns a slice to the list of CRTC handles.
    pub fn crtcs<'a>(&'a self) -> &'a [crtc::Handle] {
        &self.crtcs
    }

    /// Returns a slice to the list of framebuffer handle.
    pub fn framebuffers<'a>(&'a self) -> &'a [framebuffer::Handle] {
        &self.framebuffers
    }

    /// TODO: Learn and document.
    pub fn width(&self) -> (u32, u32) {
        (self.width)
    }

    /// TODO: Learn and document.
    pub fn height(&self) -> (u32, u32) {
        (self.height)

    }

    pub fn filter_crtcs(&self, filter: CrtcListFilter) -> ffi::Buffer<crtc::Handle> {
        self.crtcs.iter().enumerate().filter(| &(n, _) | {
            (1 << n) & filter.0 != 0
        }).map(| (_, &e) | e).collect()
    }
}

impl PlaneResourceHandles {
    /// Loads the plane ids from a device.
    pub fn load_from_device<T>(device: &T) -> Result<Self>
        where T: Device {

        let phandles = {
            let mut raw: ffi::drm_mode_get_plane_res = Default::default();
            unsafe {
                try!(ffi::ioctl_mode_getplaneresources(device.as_raw_fd(),
                                                       &mut raw));
            }

            let phandles = PlaneResourceHandles {
                planes: ffi_buf!(raw.plane_id_ptr, raw.count_planes)
            };

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

            phandles
        };

        Ok(phandles)
    }

    /// Returns a slice to the list of plane ids.
    pub fn planes<'a>(&'a self) -> &'a [plane::Handle] {
        &self.planes
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum Type {
    Connector,
    Encoder,
    Property,
    Framebuffer,
    Blob,
    Plane,
    Crtc,
    Unknown
}

#[warn(non_upper_case_globals)]
impl From<Type> for u32 {
    fn from(n: Type) -> Self {
        match n {
            Type::Connector => ffi::DRM_MODE_OBJECT_CONNECTOR,
            Type::Encoder => ffi::DRM_MODE_OBJECT_ENCODER,
            //Type::Mode => ffi::DRM_MODE_OBJECT_MODE,
            Type::Property => ffi::DRM_MODE_OBJECT_PROPERTY,
            Type::Framebuffer => ffi::DRM_MODE_OBJECT_FB,
            Type::Blob => ffi::DRM_MODE_OBJECT_BLOB,
            Type::Plane => ffi::DRM_MODE_OBJECT_PLANE,
            Type::Crtc => ffi::DRM_MODE_OBJECT_CRTC,
            Type::Unknown => ffi::DRM_MODE_OBJECT_ANY,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// A handle to a generic resource id
pub enum ResourceHandleType {
    Connector(connector::Handle),
    Encoder(encoder::Handle),
    Crtc(crtc::Handle),
    Framebuffer(framebuffer::Handle),
    Plane(plane::Handle),
    Property(property::Handle)
}

#[derive(Debug, Clone, PartialEq, Eq)]
// TODO: Document
pub struct GammaLookupTable {
    pub red: ffi::Buffer<u16>,
    pub green: ffi::Buffer<u16>,
    pub blue: ffi::Buffer<u16>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// A filter that can be used with a ResourceHandles to determine the set of
/// Crtcs that can attach to a specific encoder.
pub struct CrtcListFilter(u32);

#[derive(Debug, Clone, Copy)]
pub struct Mode {
    // We're using the FFI struct because the DRM API expects it when giving it
    // to a CRTC or creating a blob from it. Maybe in the future we can look at
    // another option.
    mode: ffi::drm_mode_modeinfo
}

impl Mode {
    /// Returns the clock speed of this mode.
    pub fn clock(&self) -> u32 {
        self.mode.clock
    }

    /// Returns the size (resolution) of the mode.
    pub fn size(&self) -> (u16, u16) {
        (self.mode.hdisplay, self.mode.vdisplay)
    }

    /// Returns the horizontal sync start, end, and total.
    pub fn hsync(&self) -> (u16, u16, u16) {
        (self.mode.hsync_start, self.mode.hsync_end, self.mode.htotal)
    }

    /// Returns the vertical sync start, end, and total.
    pub fn vsync(&self) -> (u16, u16, u16) {
        (self.mode.vsync_start, self.mode.vsync_end, self.mode.vtotal)
    }

    /// Returns the horizontal skew of this mode.
    pub fn hskew(&self) -> u16 {
        self.mode.hskew
    }

    /// Returns the vertical scan of this mode.
    pub fn vscan(&self) -> u16 {
        self.mode.vscan
    }

    /// Returns the name of the mode.
    pub fn name(&self) -> &CStr {
        unsafe {
            CStr::from_ptr(&self.mode.name as *const _)
        }
    }
}

// We need to implement PartialEq manually for Mode
impl PartialEq for Mode {
    fn eq(&self, other: &Mode) -> bool {
        self.mode.clock == other.mode.clock &&
            self.mode.clock == other.mode.clock &&
            self.mode.hdisplay == other.mode.hdisplay &&
            self.mode.hsync_start == other.mode.hsync_start &&
            self.mode.hsync_end == other.mode.hsync_end &&
            self.mode.htotal == other.mode.htotal &&
            self.mode.hskew == other.mode.hskew &&
            self.mode.vdisplay == other.mode.vdisplay &&
            self.mode.vsync_start == other.mode.vsync_start &&
            self.mode.vsync_end == other.mode.vsync_end &&
            self.mode.vtotal == other.mode.vtotal &&
            self.mode.vscan == other.mode.vscan &&
            self.mode.vrefresh == other.mode.vrefresh &&
            self.mode.flags == other.mode.flags &&
            self.mode.type_ == other.mode.type_ &&
            self.mode.name == other.mode.name
    }
}

impl Eq for Mode {}

impl ::std::fmt::Debug for RawName {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        let cstr = unsafe {
            CStr::from_ptr(::std::mem::transmute(&self))
        };
        write!(f, "{:?}", cstr)
    }
}