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
use ffi;
use std::fmt;
use types::*;

/// Device event direction.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Direction {
    Input,
    Output,
}

/// Represents a PortMidi device.
#[derive(Clone, Debug)]
pub struct DeviceInfo {
    id: PortMidiDeviceId,
    /// The device name
    name: String,
    /// Event direction
    dir: Direction,
}
impl DeviceInfo {
    /// Creates a new `DeviceInfo` instance for the given device id.
    /// Returns an `Error::PortMidi(_)` if the given id is invalid.
    pub fn new(id: PortMidiDeviceId) -> Result<Self> {
        let dev_inf_ptr = unsafe { ffi::Pm_GetDeviceInfo(id) };
        if dev_inf_ptr.is_null() {
            Err(Error::PortMidi(ffi::PmError::PmInvalidDeviceId))
        } else {
            let name = unsafe { ffi::ptr_to_string((*dev_inf_ptr).name).unwrap() };
            let direction = if unsafe { (*dev_inf_ptr).input != 0 } {
                Direction::Input
            } else {
                Direction::Output
            };

            Ok(DeviceInfo {
                id,
                name,
                dir: direction,
            })
        }
    }

    /// Returns `true` for an input device.
    pub fn is_input(&self) -> bool {
        match self.dir {
            Direction::Input => true,
            _ => false,
        }
    }

    /// Returns `true` for an output device.
    pub fn is_output(&self) -> bool {
        !self.is_input()
    }

    /// Returns the device name.
    pub fn name(&self) -> &String {
        &self.name
    }

    /// Returns the device event direction.
    pub fn direction(&self) -> Direction {
        self.dir
    }

    /// Returns the device id.
    pub fn id(&self) -> PortMidiDeviceId {
        self.id
    }
}
impl fmt::Display for DeviceInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}) {:?}: {}", self.id(), self.direction(), self.name())
    }
}