Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,10 @@ and X11-style licences) and libxcb-xkb (https://xcb.freedesktop.org, X11 licence
as Ubuntu 22.04 builds them, in usr/lib/chromaforge/, with their copyright files beside them as
LICENSE-libxkbcommon.txt and LICENSE-libxcb.txt. winit opens them at run time for the keyboard;
the AppImage carries them for desktops that do not have them installed.

MIDI controllers
----------------
crates/surface/src/midi.rs and the MIDI controller page of Settings ▸ Controls were written with
MIDI2LR (https://github.com/rsjaffe/MIDI2LR, Copyright (c) Rory Jaffe and contributors, GNU General
Public License version 3) read as a reference for behaviour: which kinds of relative encoding
controllers send and how MIDI learn reads them.
4 changes: 2 additions & 2 deletions apps/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1818,9 +1818,9 @@ fn run() -> eframe::Result {
app.ui.settings.gpu = false;
app.notices.push(notice);
}
let (midi_actions, midi_reload, midi_problem) = midi::start(cc.egui_ctx.clone());
let (midi_actions, midi_reload, midi_problem, midi_raw, midi_ports) = midi::start(cc.egui_ctx.clone());
app.notices.extend(midi_problem);
app = app.with_midi(midi_actions, midi_reload);
app = app.with_midi(midi_actions, midi_reload).with_midi_surface(midi_raw, midi_ports);
// requests from --control and from the control-surface listener
let (control_tx, control_rx) = std::sync::mpsc::channel();
let mut control_started = false;
Expand Down
139 changes: 102 additions & 37 deletions apps/app/src/midi.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
//! MIDI controller input (Windows and macOS; see `docs/midi.md`). Without a `midi.toml` nothing is
//! opened: MIDI ports are exclusive on Windows, so the app doesn't take them from other programs
//! unless the user asks. With one, a background thread keeps the ports the map wants open,
//! re-scanning every few seconds so a controller plugged in later is picked up, and sends what the
//! map makes of each message to the UI thread, which applies it as a develop edit or a command.
//! MIDI controller input (Windows and macOS; see `docs/midi.md` and `docs/control-surfaces.md` →
//! MIDI controllers). MIDI ports are exclusive on Windows, so the app opens only the ports it is
//! asked to: the ones a `midi.toml` names, and the ones Settings ▸ Controls uses as control
//! surfaces (`lcc_ui_egui::surface_midi`). A background thread keeps them open, re-scanning every
//! few seconds so a controller plugged in later is picked up, and lists every port it finds for
//! Settings ▸ Controls. A message the map binds goes to the UI thread as the map's action; any
//! other message from a port the surface uses goes there raw, for the surface engine.
//! Failing to open MIDI at all just means no controller: it never stops the app.

use std::path::PathBuf;
use std::sync::mpsc::{Receiver, channel};
use std::sync::{Arc, PoisonError, RwLock};

use lcc_engine::midi::{Action, Map};
use lcc_ui_egui::surface_midi::MidiPorts;

/// Raw messages for the surface engine: (port, bytes).
pub type Raw = Receiver<(String, Vec<u8>)>;

/// Re-reads the map file and swaps it in; the message says what happened.
pub type Reload = Box<dyn FnMut() -> Result<String, String>>;
Expand Down Expand Up @@ -63,51 +69,81 @@ fn reload(path: Option<PathBuf>, shared: &Shared) -> Result<String, String> {
Ok(said)
}

/// Start MIDI input. Returns the actions to apply, a reload function for the `midi.reload` command and
/// a message to show the user if the map file at startup was unusable.
pub fn start(ctx: egui::Context) -> (Receiver<Action>, Reload, Option<String>) {
/// Start MIDI input. Returns the map's actions to apply, a reload function for the `midi.reload`
/// command, a message to show the user if the map file at startup was unusable, and the surface's
/// raw messages with the ports it shares with the port thread.
pub fn start(ctx: egui::Context) -> (Receiver<Action>, Reload, Option<String>, Raw, MidiPorts) {
let (map, problem) = load_map();
let shared: Shared = Arc::new(RwLock::new(Arc::new(map)));
let (tx, rx) = channel::<Action>();
spawn(ctx, tx, Arc::clone(&shared));
(rx, Box::new(move || reload(map_path(), &shared)), problem)
let (raw_tx, raw_rx) = channel::<(String, Vec<u8>)>();
let ports = MidiPorts::default();
spawn(ctx, tx, raw_tx, Arc::clone(&shared), ports.clone());
(rx, Box::new(move || reload(map_path(), &shared)), problem, raw_rx, ports)
}

/// Does the port thread need `name` open: the map names it, or the surface uses it?
fn wanted(map: &Map, surface: &std::collections::BTreeSet<String>, name: &str) -> bool {
(!map.is_empty() && map.wants_input(name)) || surface.contains(name)
}

#[cfg(any(windows, target_os = "macos"))]
fn spawn(ctx: egui::Context, tx: std::sync::mpsc::Sender<Action>, shared: Shared) {
use std::collections::HashMap;
fn spawn(ctx: egui::Context, tx: std::sync::mpsc::Sender<Action>, raw: std::sync::mpsc::Sender<(String, Vec<u8>)>, shared: Shared, ports: MidiPorts) {
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::mpsc::Sender;
use std::time::Duration;

use lcc_ui_egui::surface_midi::PortInfo;
use midir::{MidiInput, MidiInputConnection};

/// How often the port list is checked for hot-plugged devices.
const RESCAN: Duration = Duration::from_secs(3);
/// How often the port list is checked for hot-plugged devices and for the ports Settings ▸
/// Controls wants.
const RESCAN: Duration = Duration::from_secs(1);

fn scan(tx: &Sender<Action>, ctx: &egui::Context, shared: &Shared, map: &Map, open: &mut HashMap<String, MidiInputConnection<()>>) {
// ports the map no longer selects close even when the probe below fails
open.retain(|name, _| map.wants_input(name));
struct Senders {
tx: Sender<Action>,
raw: Sender<(String, Vec<u8>)>,
ctx: egui::Context,
shared: Shared,
wanted: Arc<RwLock<BTreeSet<String>>>,
}

fn scan(s: &Senders, ports: &MidiPorts, open: &mut HashMap<String, MidiInputConnection<()>>, errors: &mut BTreeMap<String, String>) {
let map = Arc::clone(&s.shared.read().unwrap_or_else(PoisonError::into_inner));
let surface = s.wanted.read().unwrap_or_else(PoisonError::into_inner).clone();
// ports no longer wanted close even when the probe below fails
open.retain(|name, _| wanted(&map, &surface, name));
let Ok(probe) = MidiInput::new(&format!("{} probe", lcc_brand::DISPLAY_NAME)) else { return };
let names: Vec<String> = probe.ports().iter().filter_map(|p| probe.port_name(p).ok()).filter(|n| map.wants_input(n)).collect();
// closing a vanished or no longer wanted port frees its slot, so it can be opened again later
let names: Vec<String> = probe.ports().iter().filter_map(|p| probe.port_name(p).ok()).collect();
// closing a vanished port frees its slot, so it can be opened again later
open.retain(|name, _| names.contains(name));
for name in names {
if open.contains_key(&name) {
errors.retain(|name, _| names.contains(name) && wanted(&map, &surface, name));
for name in names.iter().filter(|n| wanted(&map, &surface, n)) {
if open.contains_key(name) {
continue;
}
let Ok(input) = MidiInput::new(lcc_brand::DISPLAY_NAME) else { continue };
let Some(port) = input.ports().into_iter().find(|p| input.port_name(p).is_ok_and(|n| n == name)) else { continue };
let (tx, ctx, shared, port_name) = (tx.clone(), ctx.clone(), Arc::clone(shared), name.clone());
let Some(port) = input.ports().into_iter().find(|p| input.port_name(p).is_ok_and(|n| n == *name)) else { continue };
let (tx, raw, ctx, shared, wanted_now, port_name) =
(s.tx.clone(), s.raw.clone(), s.ctx.clone(), Arc::clone(&s.shared), Arc::clone(&s.wanted), name.clone());
let conn = input.connect(
&port,
"app-in",
move |_stamp, bytes, _| {
log::debug!("MIDI {port_name}: {bytes:02X?}");
// the map in use now, so a reload takes effect without reopening the port
// the map in use now, so a reload takes effect without reopening the port; what
// the map binds is its, the rest goes to the surface when it uses this port
let map = Arc::clone(&shared.read().unwrap_or_else(PoisonError::into_inner));
if let Some(action) = lcc_engine::midi::parse(bytes).and_then(|msg| map.action(msg))
&& tx.send(action).is_ok()
{
let action = if map.wants_input(&port_name) { lcc_engine::midi::parse(bytes).and_then(|msg| map.action(msg)) } else { None };
let sent = match action {
Some(action) => tx.send(action).is_ok(),
None => {
wanted_now.read().unwrap_or_else(PoisonError::into_inner).contains(&port_name)
&& bytes.len() <= 3
&& raw.send((port_name.clone(), bytes.to_vec())).is_ok()
}
};
if sent {
ctx.request_repaint();
}
},
Expand All @@ -116,23 +152,30 @@ fn spawn(ctx: egui::Context, tx: std::sync::mpsc::Sender<Action>, shared: Shared
match conn {
Ok(c) => {
log::info!("MIDI input opened: {name}");
open.insert(name, c);
errors.remove(name);
open.insert(name.clone(), c);
}
Err(e) => {
log::warn!("MIDI input {name} could not be opened: {e}");
errors.insert(name.clone(), e.to_string());
}
Err(e) => log::warn!("MIDI input {name} could not be opened: {e}"),
}
}
let found: Vec<PortInfo> =
names.iter().map(|n| PortInfo { name: n.clone(), open: open.contains_key(n), error: errors.get(n).cloned() }).collect();
let mut shown = ports.found.write().unwrap_or_else(PoisonError::into_inner);
if *shown != found {
*shown = found;
s.ctx.request_repaint();
}
}

let s = Senders { tx, raw, ctx, shared, wanted: Arc::clone(&ports.wanted) };
let spawned = std::thread::Builder::new().name("midi-input".into()).spawn(move || {
let mut open = HashMap::new();
let mut errors = BTreeMap::new();
loop {
let map = Arc::clone(&shared.read().unwrap_or_else(PoisonError::into_inner));
if map.is_empty() {
// no map: hold no ports
open.clear();
} else {
scan(&tx, &ctx, &shared, &map, &mut open);
}
scan(&s, &ports, &mut open, &mut errors);
std::thread::sleep(RESCAN);
}
});
Expand All @@ -143,7 +186,14 @@ fn spawn(ctx: egui::Context, tx: std::sync::mpsc::Sender<Action>, shared: Shared

/// No MIDI backend on this platform yet (Linux's needs ALSA, a C library).
#[cfg(not(any(windows, target_os = "macos")))]
fn spawn(_ctx: egui::Context, _tx: std::sync::mpsc::Sender<Action>, _shared: Shared) {}
fn spawn(
_ctx: egui::Context,
_tx: std::sync::mpsc::Sender<Action>,
_raw: std::sync::mpsc::Sender<(String, Vec<u8>)>,
_shared: Shared,
_ports: MidiPorts,
) {
}

#[cfg(test)]
mod tests {
Expand All @@ -164,6 +214,21 @@ mod tests {
shared.read().unwrap().len()
}

#[test]
fn ports_are_opened_for_the_map_or_the_surface() {
let none = std::collections::BTreeSet::new();
let surface = std::collections::BTreeSet::from(["X-TOUCH MINI".to_string()]);
let empty = Map::default();
assert!(!wanted(&empty, &none, "X-TOUCH MINI"), "nothing asks: the port stays free for other programs");
assert!(wanted(&empty, &surface, "X-TOUCH MINI"));
let map = Map::from_toml(
r#"inputs = ["SMC-Mixer"]
bindings = [{ on = "note", number = 1, run = "library.next" }]"#,
)
.unwrap();
assert!(wanted(&map, &none, "SMC-Mixer") && !wanted(&map, &none, "X-TOUCH MINI"));
}

#[test]
fn no_file_means_no_map() {
assert_eq!(read_map(None), Ok(None));
Expand Down
8 changes: 7 additions & 1 deletion crates/surface/src/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ pub fn find_control(id: &str) -> Option<&'static ControlDef> {
pub fn group_of(id: &str) -> PageGroup {
match find_control(id) {
Some(c) => c.group,
// a MIDI controller's knobs and faders page with the dials, its notes with the keys
None if id.starts_with("midi.cc.") || id.starts_with("midi.pb.") => PageGroup::Dials,
None if id.starts_with("dial") || id.starts_with("roller") || id.starts_with("enc") || id.starts_with("knob") => PageGroup::Dials,
None => PageGroup::Keys,
}
Expand All @@ -129,7 +131,8 @@ pub fn group_of(id: &str) -> PageGroup {
pub fn is_encoder(id: &str) -> bool {
match find_control(id) {
Some(c) => c.kind == ControlKind::Encoder,
None => group_of(id) == PageGroup::Dials && !id.starts_with("pad"),
// a MIDI control's binding says what it does (a CC may be a button)
None => group_of(id) == PageGroup::Dials && !id.starts_with("pad") && !crate::midi::is_midi(id),
}
}

Expand All @@ -155,6 +158,9 @@ mod tests {
assert_eq!(group_of("pad.2"), PageGroup::Dials);
assert_eq!(group_of("knob.7"), PageGroup::Dials);
assert_eq!(group_of("midi.note.36"), PageGroup::Keys);
assert_eq!(group_of("midi.cc.1.16"), PageGroup::Dials);
assert_eq!(group_of("midi.pb.1"), PageGroup::Dials);
assert!(!is_encoder("midi.cc.1.16"), "a CC's binding says whether it turns or presses");
assert!(is_encoder("dial") && is_encoder("roller") && is_encoder("knob.3"));
assert!(!is_encoder("key.1") && !is_encoder("pad.1"));
}
Expand Down
4 changes: 4 additions & 0 deletions crates/surface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
//! - [`settings`]: everything the user tunes, stored as `control-surfaces.json`.
//! - [`loupedeck`]: the Loupedeck+ console's controls, their defaults, and importing a Loupedeck
//! profile's layout.
//! - [`midi`]: MIDI controllers: raw messages to input, how each control sends, which ports to use.
//! - [`pickup`]: faders and knobs with ends take over a value once they reach it.
//! - [`tactilebridge`]: imports a TactileBridge `settings.json` and its Logi profiles (`.lp5`).
//! - [`catalog`]: every action in categories (the editor's picker; plugins list them in their app).
//! - [`protocol`]: pairing tokens and the message shapes of the surface protocol.
Expand All @@ -31,7 +33,9 @@ pub mod devices;
pub mod icons;
pub mod layout;
pub mod loupedeck;
pub mod midi;
pub mod motion;
pub mod pickup;
pub mod profile;
pub mod protocol;
pub mod runtime;
Expand Down
Loading
Loading