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
use midir::{MidiInput, MidiInputConnection, MidiInputPort, MidiOutput, MidiOutputConnection};
fn guess_port<T: midir::MidiIO>(midi_io: &T, keyword: &str) -> Option<T::Port> {
for port in midi_io.ports() {
let name = match midi_io.port_name(&port) {
Ok(name) => name,
Err(_) => continue,
};
if name.contains(keyword) {
return Some(port);
}
}
None
}
pub trait OutputDevice
where
Self: Sized,
{
const MIDI_CONNECTION_NAME: &'static str;
const MIDI_DEVICE_KEYWORD: &'static str;
/// Initiate from an existing midir connection.
fn from_connection(connection: MidiOutputConnection) -> Result<Self, crate::MidiError>;
fn send(&mut self, bytes: &[u8]) -> Result<(), crate::MidiError>;
fn guess() -> Result<Self, crate::MidiError> {
let midi_output = MidiOutput::new(crate::APPLICATION_NAME)?;
let port = guess_port(&midi_output, Self::MIDI_DEVICE_KEYWORD).ok_or(
crate::MidiError::NoPortFound {
keyword: Self::MIDI_DEVICE_KEYWORD,
},
)?;
let connection = midi_output.connect(&port, Self::MIDI_CONNECTION_NAME)?;
Self::from_connection(connection)
}
}
/// A handler for a Launchpad input connection. This variant is used when an input connection is
/// initiated with callback
pub struct InputDeviceHandler {
_connection: MidiInputConnection<()>,
}
/// A handler for a Launchpad input connection that can be polled for new messages. The actual
/// polling methods are implemented inside [MsgPollingWrapper](crate::MsgPollingWrapper). Look there
/// for documentation on how to poll messages.
pub struct InputDeviceHandlerPolling<Message> {
_connection: MidiInputConnection<()>,
receiver: std::sync::mpsc::Receiver<Message>,
}
impl<Message> crate::MsgPollingWrapper for InputDeviceHandlerPolling<Message> {
type Message = Message;
fn receiver(&self) -> &std::sync::mpsc::Receiver<Self::Message> {
&self.receiver
}
}
pub trait InputDevice {
const MIDI_CONNECTION_NAME: &'static str;
const MIDI_DEVICE_KEYWORD: &'static str;
type Message;
fn decode_message(timestamp: u64, data: &[u8]) -> Self::Message;
#[must_use = "If not saved, the connection will be immediately dropped"]
fn from_port<F>(
midi_input: MidiInput,
port: &MidiInputPort,
mut user_callback: F,
) -> Result<InputDeviceHandler, crate::MidiError>
where
F: FnMut(Self::Message) + Send + 'static,
{
let midir_callback = move |timestamp: u64, data: &[u8], _: &mut _| {
let msg = Self::decode_message(timestamp, data);
(user_callback)(msg);
};
let connection =
midi_input.connect(port, Self::MIDI_CONNECTION_NAME, midir_callback, ())?;
Ok(InputDeviceHandler {
_connection: connection,
})
}
#[must_use = "If not saved, the connection will be immediately dropped"]
fn from_port_polling(
midi_input: MidiInput,
port: &MidiInputPort,
) -> Result<InputDeviceHandlerPolling<Self::Message>, crate::MidiError>
where
Self::Message: Send + 'static,
{
let (sender, receiver) = std::sync::mpsc::channel();
let midir_callback = move |timestamp: u64, data: &[u8], _: &mut _| {
let msg = Self::decode_message(timestamp, data);
// The following statement can only panic when the receiver was dropped but the
// connection is still alive. This can't happen by accident I think, because the
// user would have to destructure the input device handler in order to get the
// connection and the receiver seperately, in order to drop one but not the other -
// but if he does that it's his fault that he gets a panic /shrug
sender
.send(msg)
.expect("Message receiver has hung up (this shouldn't happen)");
};
let connection =
midi_input.connect(port, Self::MIDI_CONNECTION_NAME, midir_callback, ())?;
Ok(InputDeviceHandlerPolling {
_connection: connection,
receiver,
})
}
/// Search the midi devices and choose the first midi device matching the wanted Launchpad type.
#[must_use = "If not saved, the connection will be immediately dropped"]
fn guess<F>(user_callback: F) -> Result<InputDeviceHandler, crate::MidiError>
where
F: FnMut(Self::Message) + Send + 'static,
{
let midi_input = MidiInput::new(crate::APPLICATION_NAME)?;
let port = guess_port(&midi_input, Self::MIDI_DEVICE_KEYWORD).ok_or(
crate::MidiError::NoPortFound {
keyword: Self::MIDI_DEVICE_KEYWORD,
},
)?;
Self::from_port(midi_input, &port, user_callback)
}
/// Search the midi devices and choose the first midi device matching the wanted Launchpad type.
#[must_use = "If not saved, the connection will be immediately dropped"]
fn guess_polling() -> Result<InputDeviceHandlerPolling<Self::Message>, crate::MidiError>
where
Self::Message: Send + 'static,
{
let midi_input = MidiInput::new(crate::APPLICATION_NAME)?;
let port = guess_port(&midi_input, Self::MIDI_DEVICE_KEYWORD).ok_or(
crate::MidiError::NoPortFound {
keyword: Self::MIDI_DEVICE_KEYWORD,
},
)?;
Self::from_port_polling(midi_input, &port)
}
}
/// An iterator that yields canvas input messages for some user-defined time duration. For more
/// information, see [MsgPollingWrapper::iter_for]
pub struct IterFor<'a, M> {
receiver: &'a std::sync::mpsc::Receiver<M>,
deadline: std::time::Instant,
}
impl<M> Iterator for IterFor<'_, M> {
type Item = M;
fn next(&mut self) -> Option<Self::Item> {
let now = std::time::Instant::now();
if now >= self.deadline {
return None;
}
self.receiver
.recv_timeout(self.deadline - std::time::Instant::now())
.ok()
}
}
// I have no idea what I'm doing
pub trait MsgPollingWrapper {
/// The type of message that is yielded
type Message;
/// Returns a [std::sync::mpsc::Receiver] that yields messages, where the type of messages is
/// described by the associated [`Self::Message`] type
fn receiver(&self) -> &std::sync::mpsc::Receiver<Self::Message>;
/// Wait for a message to arrive, and return that. For a non-block variant, see
/// [`Self::try_recv`].
fn recv(&self) -> Self::Message {
self.receiver()
.recv()
.expect("Message sender has hung up - please report a bug")
}
/// If there is a pending message, return that. Otherwise, return `None`.
///
/// This function does not block.
fn try_recv(&self) -> Option<Self::Message> {
use std::sync::mpsc::TryRecvError;
match self.receiver().try_recv() {
Ok(msg) => Some(msg),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
panic!("Message sender has hung up - please report a bug")
}
}
}
/// Receives a single message. If no message arrives within the timespan specified by `timeout`,
/// `None` is returned.
fn recv_timeout(&self, timeout: std::time::Duration) -> Option<Self::Message> {
use std::sync::mpsc::RecvTimeoutError;
match self.receiver().recv_timeout(timeout) {
Ok(msg) => Some(msg),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => {
panic!("Message sender has hung up - please report a bug")
}
}
}
/// Returns an iterator over all arriving messages. The iterator will only return when the
/// MIDI connection has been dropped.
///
/// For an iteration method that doesn't block, but returns immediately when there are no more
/// pending messages, see [`Self::iter_pending`].
fn iter(&self) -> std::sync::mpsc::Iter<Self::Message> {
self.receiver().iter()
}
/// Returns an iterator over the currently pending messages. As soon as all pending messages
/// have been iterated over, the iterator will return.
///
/// For an iteration method that will block, waiting for new messages to arrive, see
/// [`Self::iter`].
fn iter_pending(&self) -> std::sync::mpsc::TryIter<Self::Message> {
self.receiver().try_iter()
}
/// Returns an iterator that yields all arriving messages for a specified amount of time. After
/// the specified `duration` has passed, the iterator will stop and not yield any more messages.
///
/// For a shorthand of this function that accepts the duration in milliseconds, see
/// [`Self::iter_for_millis`]
fn iter_for(&self, duration: std::time::Duration) -> IterFor<Self::Message> {
IterFor {
receiver: self.receiver(),
deadline: std::time::Instant::now() + duration,
}
}
/// Returns an iterator that yields all arriving messages for a specified amount of time. After
/// the specified `duration` has passed, the iterator will stop and not yield any more messages.
///
/// For a more general version of this function that accepts any [std::time::Duration], see
/// [`Self::iter_for`]
fn iter_for_millis(&self, millis: u64) -> IterFor<Self::Message> {
self.iter_for(std::time::Duration::from_millis(millis))
}
/// Drain of any pending messages. This is useful on Launchpad startup - the Launchpad has the
/// weird property that any button inputs while disconnected queue up and will all be released
/// at the same time as soon as someone connects to it. In most cases you don't want to deal
/// with those stale messages though - in those cases, call `drain()` after establishing the
/// connection.
///
/// This function returns the number of messages that were discarded.
///
/// This is equivalent to `self.iter_pending().count()`.
fn drain(&self) -> usize {
self.iter_pending().count()
}
}