| 1 |
//! Web MIDI Backend. |
| 2 |
//! |
| 3 |
//! Reference: |
| 4 |
//! * [W3C Editor's Draft](https://webaudio.github.io/web-midi-api/) |
| 5 |
//! * [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/MIDIAccess) |
| 6 |
|
| 7 |
extern crate js_sys; |
| 8 |
extern crate wasm_bindgen; |
| 9 |
extern crate web_sys; |
| 10 |
|
| 11 |
use self::js_sys::{Map, Promise, Uint8Array}; |
| 12 |
use self::wasm_bindgen::prelude::*; |
| 13 |
use self::wasm_bindgen::JsCast; |
| 14 |
use self::web_sys::{MidiAccess, MidiOptions, MidiMessageEvent}; |
| 15 |
|
| 16 |
use std::cell::RefCell; |
| 17 |
use std::sync::{Arc, Mutex}; |
| 18 |
|
| 19 |
use ::errors::*; |
| 20 |
use ::Ignore; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
thread_local! { |
| 25 |
static STATIC : RefCell<Static> = RefCell::new(Static::new()); |
| 26 |
} |
| 27 |
|
| 28 |
struct Static { |
| 29 |
pub access: Option<MidiAccess>, |
| 30 |
pub request: Option<Promise>, |
| 31 |
pub ever_requested: bool, |
| 32 |
|
| 33 |
pub on_ok: Closure<dyn FnMut(JsValue)>, |
| 34 |
pub on_err: Closure<dyn FnMut(JsValue)>, |
| 35 |
} |
| 36 |
|
| 37 |
impl Static { |
| 38 |
pub fn new() -> Self { |
| 39 |
let mut s = Self { |
| 40 |
access: None, |
| 41 |
request: None, |
| 42 |
ever_requested: false, |
| 43 |
|
| 44 |
on_ok: Closure::wrap(Box::new(|access| { |
| 45 |
STATIC.with(|s|{ |
| 46 |
let mut s = s.borrow_mut(); |
| 47 |
let access : MidiAccess = access.dyn_into().unwrap(); |
| 48 |
s.request = None; |
| 49 |
s.access = Some(access); |
| 50 |
}); |
| 51 |
})), |
| 52 |
on_err: Closure::wrap(Box::new(|_error| { |
| 53 |
STATIC.with(|s|{ |
| 54 |
let mut s = s.borrow_mut(); |
| 55 |
s.request = None; |
| 56 |
}); |
| 57 |
})), |
| 58 |
}; |
| 59 |
// Some notes on sysex behavior: |
| 60 |
// 1) Some devices (but not all!) may work without sysex |
| 61 |
// 2) Chrome will only prompt the end user to grant permission if they requested sysex permissions for now... |
| 62 |
// but that's changing soon for "security reasons" (reduced fingerprinting? poorly tested drivers?): |
| 63 |
// https://www.chromestatus.com/feature/5138066234671104 |
| 64 |
// |
| 65 |
// I've chosen to hardcode sysex=true here, since that'll be compatible with more devices, *and* should change |
| 66 |
// less behavior when Chrome's changes land. |
| 67 |
s.request_midi_access(true); |
| 68 |
s |
| 69 |
} |
| 70 |
|
| 71 |
fn request_midi_access(&mut self, sysex: bool) { |
| 72 |
self.ever_requested = true; |
| 73 |
if self.access.is_some() { return; } // Already have access |
| 74 |
if self.request.is_some() { return; } // Mid-request already |
| 75 |
let window = if let Some(w) = web_sys::window() { w } else { return; }; |
| 76 |
|
| 77 |
let _request = match window.navigator().request_midi_access_with_options(MidiOptions::new().sysex(sysex)) { |
| 78 |
Ok(p) => { self.request = Some(p.then2(&self.on_ok, &self.on_err)); }, |
| 79 |
Err(_) => { return; } // node.js? brower doesn't support webmidi? other? |
| 80 |
}; |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
#[derive(Clone, PartialEq)] |
| 85 |
pub struct MidiInputPort { |
| 86 |
input: web_sys::MidiInput, |
| 87 |
} |
| 88 |
|
| 89 |
pub struct MidiInput { |
| 90 |
ignore_flags: Ignore |
| 91 |
} |
| 92 |
|
| 93 |
impl MidiInput { |
| 94 |
pub fn new(_client_name: &str) -> Result<Self, InitError> { |
| 95 |
STATIC.with(|_|{}); |
| 96 |
Ok(MidiInput { ignore_flags: Ignore::None }) |
| 97 |
} |
| 98 |
|
| 99 |
pub(crate) fn ports_internal(&self) -> Vec<::common::MidiInputPort> { |
| 100 |
STATIC.with(|s|{ |
| 101 |
let mut v = Vec::new(); |
| 102 |
let s = s.borrow(); |
| 103 |
if let Some(access) = s.access.as_ref() { |
| 104 |
let inputs : Map = access.inputs().unchecked_into(); |
| 105 |
inputs.for_each(&mut |value, _|{ |
| 106 |
v.push(::common::MidiInputPort { |
| 107 |
imp: MidiInputPort { input: value.dyn_into().unwrap() } |
| 108 |
}); |
| 109 |
}); |
| 110 |
} |
| 111 |
v |
| 112 |
}) |
| 113 |
} |
| 114 |
|
| 115 |
pub fn ignore(&mut self, flags: Ignore) { |
| 116 |
self.ignore_flags = flags; |
| 117 |
} |
| 118 |
|
| 119 |
pub fn port_count(&self) -> usize { |
| 120 |
STATIC.with(|s| { |
| 121 |
let s = s.borrow(); |
| 122 |
s.access.as_ref().map(|access| access.inputs().unchecked_into::<Map>().size() as usize).unwrap_or(0) |
| 123 |
}) |
| 124 |
} |
| 125 |
|
| 126 |
pub fn port_name(&self, port: &MidiInputPort) -> Result<String, PortInfoError> { |
| 127 |
Ok(port.input.name().unwrap_or_else(|| port.input.id())) |
| 128 |
} |
| 129 |
|
| 130 |
pub fn connect<F, T: Send + 'static>( |
| 131 |
self, port: &MidiInputPort, _port_name: &str, mut callback: F, data: T |
| 132 |
) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>> |
| 133 |
where F: FnMut(u64, &[u8], &mut T) + Send + 'static |
| 134 |
{ |
| 135 |
let input = port.input.clone(); |
| 136 |
let _ = input.open(); // NOTE: asyncronous! |
| 137 |
|
| 138 |
let ignore_flags = self.ignore_flags; |
| 139 |
let user_data = Arc::new(Mutex::new(Some(data))); |
| 140 |
|
| 141 |
let closure = { |
| 142 |
let user_data = user_data.clone(); |
| 143 |
|
| 144 |
let closure = Closure::wrap(Box::new(move |event: MidiMessageEvent| { |
| 145 |
let time = (event.time_stamp() * 1000.0) as u64; // ms -> us |
| 146 |
let buffer = event.data().unwrap(); |
| 147 |
|
| 148 |
let status = buffer[0]; |
| 149 |
if !(status == 0xF0 && ignore_flags.contains(Ignore::Sysex) || |
| 150 |
status == 0xF1 && ignore_flags.contains(Ignore::Time) || |
| 151 |
status == 0xF8 && ignore_flags.contains(Ignore::Time) || |
| 152 |
status == 0xFE && ignore_flags.contains(Ignore::ActiveSense)) |
| 153 |
{ |
| 154 |
callback(time, &buffer[..], user_data.lock().unwrap().as_mut().unwrap()); |
| 155 |
} |
| 156 |
}) as Box<dyn FnMut(MidiMessageEvent)>); |
| 157 |
|
| 158 |
input.set_onmidimessage(Some(closure.as_ref().unchecked_ref())); |
| 159 |
|
| 160 |
closure |
| 161 |
}; |
| 162 |
|
| 163 |
Ok(MidiInputConnection { ignore_flags, input, user_data, closure }) |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
pub struct MidiInputConnection<T> { |
| 168 |
ignore_flags: Ignore, |
| 169 |
input: web_sys::MidiInput, |
| 170 |
user_data: Arc<Mutex<Option<T>>>, |
| 171 |
#[allow(dead_code)] // Must be kept alive until we decide to unregister from input |
| 172 |
closure: Closure<dyn FnMut(MidiMessageEvent)>, |
| 173 |
} |
| 174 |
|
| 175 |
impl<T> MidiInputConnection<T> { |
| 176 |
pub fn close(self) -> (MidiInput, T) { |
| 177 |
let Self { ignore_flags, input, user_data, .. } = self; |
| 178 |
|
| 179 |
input.set_onmidimessage(None); |
| 180 |
let mut user_data = user_data.lock().unwrap(); |
| 181 |
|
| 182 |
( |
| 183 |
MidiInput { ignore_flags }, |
| 184 |
user_data.take().unwrap() |
| 185 |
) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
#[derive(Clone, PartialEq)] |
| 190 |
pub struct MidiOutputPort { |
| 191 |
output: web_sys::MidiOutput, |
| 192 |
} |
| 193 |
|
| 194 |
pub struct MidiOutput { |
| 195 |
} |
| 196 |
|
| 197 |
impl MidiOutput { |
| 198 |
pub fn new(_client_name: &str) -> Result<Self, InitError> { |
| 199 |
STATIC.with(|_|{}); |
| 200 |
Ok(MidiOutput {}) |
| 201 |
} |
| 202 |
|
| 203 |
pub(crate) fn ports_internal(&self) -> Vec<::common::MidiOutputPort> { |
| 204 |
STATIC.with(|s|{ |
| 205 |
let mut v = Vec::new(); |
| 206 |
let s = s.borrow(); |
| 207 |
if let Some(access) = s.access.as_ref() { |
| 208 |
access.outputs().unchecked_into::<Map>().for_each(&mut |value, _|{ |
| 209 |
v.push(::common::MidiOutputPort { |
| 210 |
imp: MidiOutputPort { output: value.dyn_into().unwrap() } |
| 211 |
}); |
| 212 |
}); |
| 213 |
} |
| 214 |
v |
| 215 |
}) |
| 216 |
} |
| 217 |
|
| 218 |
pub fn port_count(&self) -> usize { |
| 219 |
STATIC.with(|s|{ |
| 220 |
let s = s.borrow(); |
| 221 |
s.access.as_ref().map(|access| access.outputs().unchecked_into::<Map>().size() as usize).unwrap_or(0) |
| 222 |
}) |
| 223 |
} |
| 224 |
|
| 225 |
pub fn port_name(&self, port: &MidiOutputPort) -> Result<String, PortInfoError> { |
| 226 |
Ok(port.output.name().unwrap_or_else(|| port.output.id())) |
| 227 |
} |
| 228 |
|
| 229 |
pub fn connect(self, port: &MidiOutputPort, _port_name: &str) -> Result<MidiOutputConnection, ConnectError<MidiOutput>> { |
| 230 |
let _ = port.output.open(); // NOTE: asyncronous! |
| 231 |
Ok(MidiOutputConnection{ |
| 232 |
output: port.output.clone() |
| 233 |
}) |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
pub struct MidiOutputConnection { |
| 238 |
output: web_sys::MidiOutput, |
| 239 |
} |
| 240 |
|
| 241 |
impl MidiOutputConnection { |
| 242 |
pub fn close(self) -> MidiOutput { |
| 243 |
let _ = self.output.close(); // NOTE: asyncronous! |
| 244 |
MidiOutput {} |
| 245 |
} |
| 246 |
|
| 247 |
pub fn send(&mut self, message: &[u8]) -> Result<(), SendError> { |
| 248 |
self.output.send(unsafe { Uint8Array::view(message) }.as_ref()).map_err(|_| SendError::Other("JavaScript exception")) |
| 249 |
} |
| 250 |
} |