mirror of
https://codeberg.org/unspeaker/tek.git
synced 2025-12-07 12:16:42 +01:00
modularize core
This commit is contained in:
parent
a4061535b5
commit
2837ffff4a
43 changed files with 629 additions and 770 deletions
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
const CONFIG_FILE_NAME: &'static str = "tek.toml";
|
||||
const PROJECT_FILE_NAME: &'static str = "project.toml";
|
||||
|
|
|
|||
90
src/core/device.rs
Normal file
90
src/core/device.rs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// A UI component that may have presence on the JACK grap.
|
||||
pub trait Device: Render + Handle + PortList + Send + Sync {
|
||||
fn boxed (self) -> Box<dyn Device> where Self: Sized + 'static {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// All things that implement the required traits can be treated as `Device`.
|
||||
impl<T: Render + Handle + PortList + Send + Sync> Device for T {}
|
||||
|
||||
/// A device dynamicammy composed of state and handlers.
|
||||
pub struct DynamicDevice<T> {
|
||||
pub state: Arc<Mutex<T>>,
|
||||
pub render: Mutex<Box<dyn FnMut(&T, &mut Buffer, Rect)->Usually<Rect> + Send>>,
|
||||
pub handle: Arc<Mutex<Box<dyn FnMut(&mut T, &AppEvent)->Usually<bool> + Send>>>,
|
||||
pub process: Arc<Mutex<Box<dyn FnMut(&mut T, &Client, &ProcessScope)->Control + Send>>>,
|
||||
pub client: Option<DynamicAsyncClient>
|
||||
}
|
||||
|
||||
impl<T> Handle for DynamicDevice<T> {
|
||||
fn handle (&mut self, event: &AppEvent) -> Usually<bool> {
|
||||
self.handle.lock().unwrap()(&mut *self.state.lock().unwrap(), event)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Render for DynamicDevice<T> {
|
||||
fn render (&self, buf: &mut Buffer, area: Rect) -> Usually<Rect> {
|
||||
self.render.lock().unwrap()(&*self.state.lock().unwrap(), buf, area)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PortList + Send + Sync + 'static> PortList for DynamicDevice<T> {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_ins()
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_outs()
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_ins()
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_outs()
|
||||
}
|
||||
}
|
||||
|
||||
type DynamicAsyncClient = AsyncClient<DynamicNotifications, DynamicProcessHandler>;
|
||||
type DynamicNotifications = Notifications<Box<dyn Fn(AppEvent) + Send + Sync>>;
|
||||
type DynamicProcessHandler = ClosureProcessHandler<BoxedProcessHandler>;
|
||||
|
||||
impl<T: Send + Sync + 'static> DynamicDevice<T> {
|
||||
pub fn new <'a, R, H, P> (render: R, handle: H, process: P, state: T) -> Self where
|
||||
R: FnMut(&T, &mut Buffer, Rect) -> Usually<Rect> + Send + 'static,
|
||||
H: FnMut(&mut T, &AppEvent) -> Usually<bool> + Send + 'static,
|
||||
P: FnMut(&mut T, &Client, &ProcessScope) -> Control + Send + 'static,
|
||||
{
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(state)),
|
||||
render: Mutex::new(Box::new(render)),
|
||||
handle: Arc::new(Mutex::new(Box::new(handle))),
|
||||
process: Arc::new(Mutex::new(Box::new(process))),
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
pub fn state (&self) -> std::sync::MutexGuard<'_, T> {
|
||||
self.state.lock().unwrap()
|
||||
}
|
||||
pub fn activate (mut self, client: Client) -> Usually<Self> {
|
||||
self.client = Some(client.activate_async(Notifications(Box::new({
|
||||
let state = self.state.clone();
|
||||
let handle = self.handle.clone();
|
||||
move|event|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut handle = handle.lock().unwrap();
|
||||
handle(&mut state, &event).unwrap();
|
||||
}
|
||||
}) as Box<dyn Fn(AppEvent) + Send + Sync>), ClosureProcessHandler::new(Box::new({
|
||||
let state = self.state.clone();
|
||||
let process = self.process.clone();
|
||||
move|client: &Client, scope: &ProcessScope|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut process = process.lock().unwrap();
|
||||
(process)(&mut state, client, scope)
|
||||
}
|
||||
}) as BoxedProcessHandler))?);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
89
src/core/handle.rs
Normal file
89
src/core/handle.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that handle input events.
|
||||
pub trait Handle {
|
||||
/// Handle an input event.
|
||||
/// Returns Ok(true) if the device handled the event.
|
||||
/// This is the mechanism which allows nesting of components;.
|
||||
fn handle (&mut self, _e: &AppEvent) -> Usually<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppEvent {
|
||||
/// Terminal input
|
||||
Input(::crossterm::event::Event),
|
||||
/// Update values but not the whole form.
|
||||
Update,
|
||||
/// Update the whole form.
|
||||
Redraw,
|
||||
/// Device gains focus
|
||||
Focus,
|
||||
/// Device loses focus
|
||||
Blur,
|
||||
/// JACK notification
|
||||
Jack(JackEvent)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum JackEvent {
|
||||
ThreadInit,
|
||||
Shutdown(ClientStatus, String),
|
||||
Freewheel(bool),
|
||||
SampleRate(Frames),
|
||||
ClientRegistration(String, bool),
|
||||
PortRegistration(PortId, bool),
|
||||
PortRename(PortId, String, String),
|
||||
PortsConnected(PortId, PortId, bool),
|
||||
GraphReorder,
|
||||
XRun,
|
||||
}
|
||||
|
||||
pub struct Notifications<T: Fn(AppEvent) + Send>(pub T);
|
||||
|
||||
impl<T: Fn(AppEvent) + Send> NotificationHandler for Notifications<T> {
|
||||
fn thread_init (&self, _: &Client) {
|
||||
self.0(AppEvent::Jack(JackEvent::ThreadInit));
|
||||
}
|
||||
|
||||
fn shutdown (&mut self, status: ClientStatus, reason: &str) {
|
||||
self.0(AppEvent::Jack(JackEvent::Shutdown(status, reason.into())));
|
||||
}
|
||||
|
||||
fn freewheel (&mut self, _: &Client, enabled: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::Freewheel(enabled)));
|
||||
}
|
||||
|
||||
fn sample_rate (&mut self, _: &Client, frames: Frames) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::SampleRate(frames)));
|
||||
Control::Quit
|
||||
}
|
||||
|
||||
fn client_registration (&mut self, _: &Client, name: &str, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::ClientRegistration(name.into(), reg)));
|
||||
}
|
||||
|
||||
fn port_registration (&mut self, _: &Client, id: PortId, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRegistration(id, reg)));
|
||||
}
|
||||
|
||||
fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRename(id, old.into(), new.into())));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn ports_connected (&mut self, _: &Client, a: PortId, b: PortId, are: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortsConnected(a, b, are)));
|
||||
}
|
||||
|
||||
fn graph_reorder (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::GraphReorder));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn xrun (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::XRun));
|
||||
Control::Continue
|
||||
}
|
||||
}
|
||||
35
src/core/jack.rs
Normal file
35
src/core/jack.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
use crate::core::*;
|
||||
|
||||
pub type BoxedNotificationHandler =
|
||||
Box<dyn Fn(AppEvent) + Send>;
|
||||
|
||||
pub type BoxedProcessHandler =
|
||||
Box<dyn FnMut(&Client, &ProcessScope)-> Control + Send>;
|
||||
|
||||
pub type Jack<N> =
|
||||
AsyncClient<N, ClosureProcessHandler<BoxedProcessHandler>>;
|
||||
|
||||
pub use ::jack::{
|
||||
AsyncClient,
|
||||
AudioIn,
|
||||
AudioOut,
|
||||
Client,
|
||||
ClientOptions,
|
||||
ClientStatus,
|
||||
ClosureProcessHandler,
|
||||
Control,
|
||||
Frames,
|
||||
MidiIn,
|
||||
MidiOut,
|
||||
NotificationHandler,
|
||||
Port,
|
||||
PortFlags,
|
||||
PortId,
|
||||
PortSpec,
|
||||
ProcessHandler,
|
||||
ProcessScope,
|
||||
RawMidi,
|
||||
Transport,
|
||||
TransportState,
|
||||
TransportStatePosition
|
||||
};
|
||||
39
src/core/keymap.rs
Normal file
39
src/core/keymap.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
use crate::core::*;
|
||||
|
||||
pub type KeyHandler<T> = &'static dyn Fn(&mut T)->Usually<bool>;
|
||||
|
||||
pub type KeyBinding<T> = (
|
||||
KeyCode, KeyModifiers, &'static str, &'static str, KeyHandler<T>
|
||||
);
|
||||
|
||||
pub type KeyMap<T> = [KeyBinding<T>];
|
||||
|
||||
pub fn handle_keymap <T> (
|
||||
state: &mut T, event: &AppEvent, keymap: &KeyMap<T>,
|
||||
) -> Usually<bool> {
|
||||
match event {
|
||||
AppEvent::Input(Event::Key(event)) => {
|
||||
for (code, modifiers, _, _, command) in keymap.iter() {
|
||||
if *code == event.code && modifiers.bits() == event.modifiers.bits() {
|
||||
return command(state)
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! key {
|
||||
($k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr) => {
|
||||
(KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! keymap {
|
||||
($T:ty { $([$k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr]),* $(,)? }) => {
|
||||
&[
|
||||
$((KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f as KeyHandler<$T>)),*
|
||||
] as &'static [KeyBinding<$T>]
|
||||
}
|
||||
}
|
||||
121
src/core/mod.rs
Normal file
121
src/core/mod.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
pub type Usually<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
macro_rules! submod {
|
||||
($($name:ident)*) => { $(mod $name; pub use self::$name::*;)* };
|
||||
}
|
||||
|
||||
submod!( device handle jack keymap note port process render time );
|
||||
|
||||
pub use std::error::Error;
|
||||
pub use std::io::{stdout, Stdout, Write};
|
||||
pub use std::thread::{spawn, JoinHandle};
|
||||
pub use std::time::Duration;
|
||||
pub use std::collections::BTreeMap;
|
||||
pub use std::sync::{
|
||||
Arc,
|
||||
Mutex, MutexGuard,
|
||||
atomic::{
|
||||
Ordering,
|
||||
AtomicBool,
|
||||
AtomicUsize
|
||||
},
|
||||
mpsc::{self, channel, Sender, Receiver}
|
||||
};
|
||||
|
||||
pub use ::crossterm::{
|
||||
ExecutableCommand, QueueableCommand,
|
||||
event::{Event, KeyEvent, KeyCode, KeyModifiers},
|
||||
terminal::{
|
||||
self,
|
||||
Clear, ClearType,
|
||||
EnterAlternateScreen, LeaveAlternateScreen,
|
||||
enable_raw_mode, disable_raw_mode
|
||||
},
|
||||
};
|
||||
|
||||
pub use ::ratatui::{
|
||||
prelude::{
|
||||
Buffer, Rect, Style, Color, CrosstermBackend, Layout, Stylize, Direction,
|
||||
Line, Constraint
|
||||
},
|
||||
widgets::{Widget, WidgetRef},
|
||||
//style::Stylize,
|
||||
};
|
||||
|
||||
pub use ::midly::{
|
||||
MidiMessage,
|
||||
live::LiveEvent,
|
||||
num::u7
|
||||
};
|
||||
|
||||
pub use crate::{key, keymap};
|
||||
|
||||
/// Run a device as the root of the app.
|
||||
pub fn run (device: impl Device + Send + Sync + 'static) -> Result<(), Box<dyn Error>> {
|
||||
let device = Arc::new(Mutex::new(device));
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// Spawn input (handle) thread
|
||||
let _input_thread = {
|
||||
let poll = std::time::Duration::from_millis(100);
|
||||
let exited = exited.clone();
|
||||
let device = device.clone();
|
||||
spawn(move || loop {
|
||||
// Exit if flag is set
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
// Listen for events and send them to the main thread
|
||||
if ::crossterm::event::poll(poll).is_ok() {
|
||||
let event = ::crossterm::event::read().unwrap();
|
||||
match event {
|
||||
Event::Key(KeyEvent {
|
||||
code: KeyCode::Char('c'),
|
||||
modifiers: KeyModifiers::CONTROL,
|
||||
..
|
||||
}) => {
|
||||
exited.store(true, Ordering::Relaxed);
|
||||
},
|
||||
_ => if device.lock().unwrap().handle(&AppEvent::Input(event)).is_err() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
// Set up terminal
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
|
||||
// Set up panic hook
|
||||
let better_panic_handler = better_panic::Settings::auto()
|
||||
.verbosity(better_panic::Verbosity::Full)
|
||||
.create_panic_handler();
|
||||
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo|{
|
||||
stdout().execute(LeaveAlternateScreen).unwrap();
|
||||
crossterm::terminal::disable_raw_mode().unwrap();
|
||||
better_panic_handler(info);
|
||||
}));
|
||||
|
||||
// Main (render) loop
|
||||
let sleep = std::time::Duration::from_millis(16);
|
||||
loop {
|
||||
terminal.draw(|frame|{
|
||||
let area = frame.size();
|
||||
let buffer = frame.buffer_mut();
|
||||
device.lock().unwrap().render(buffer, area).expect("Failed to render content.");
|
||||
}).expect("Failed to render frame");
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
std::thread::sleep(sleep);
|
||||
};
|
||||
|
||||
// Cleanup
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
crossterm::terminal::disable_raw_mode()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
50
src/core/port.rs
Normal file
50
src/core/port.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that may expose JACK ports.
|
||||
pub trait PortList {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn connect (&mut self, _connect: bool, _source: &str, _target: &str)
|
||||
-> Usually<()>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
fn connect_all (&mut self, connections: &[(bool, &str, &str)])
|
||||
-> Usually<()>
|
||||
{
|
||||
for (connect, source, target) in connections.iter() {
|
||||
self.connect(*connect, source, target)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevicePort<T: PortSpec> {
|
||||
pub name: String,
|
||||
pub port: Port<T>,
|
||||
pub connect: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T: PortSpec + Default> DevicePort<T> {
|
||||
pub fn new (client: &Client, name: &str, connect: &[&str]) -> Usually<Self> {
|
||||
let mut connects = vec![];
|
||||
for port in connect.iter() {
|
||||
connects.push(port.to_string());
|
||||
}
|
||||
Ok(Self {
|
||||
name: name.to_string(),
|
||||
port: client.register_port(name, T::default())?,
|
||||
connect: connects,
|
||||
})
|
||||
}
|
||||
}
|
||||
0
src/core/process.rs
Normal file
0
src/core/process.rs
Normal file
54
src/core/render.rs
Normal file
54
src/core/render.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use crate::core::*;
|
||||
|
||||
/// Trait for things that render to the display.
|
||||
pub trait Render {
|
||||
// Render something to an area of the buffer.
|
||||
// Returns area used by component.
|
||||
// This is insufficient but for the most basic dynamic layout algorithms.
|
||||
fn render (&self, _b: &mut Buffer, _a: Rect) -> Usually<Rect> {
|
||||
Ok(Rect { x: 0, y: 0, width: 0, height: 0 })
|
||||
}
|
||||
fn min_width (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_width (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
fn min_height (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_height (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Box<dyn Device> {
|
||||
fn render (&self, b: &mut Buffer, a: Rect) -> Usually<Rect> {
|
||||
(**self).render(b, a)
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for &dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(*self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Blit {
|
||||
// Render something to X, Y coordinates in a buffer, ignoring width/height.
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>);
|
||||
}
|
||||
|
||||
impl<T: AsRef<str>> Blit for T {
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>) {
|
||||
if x < buf.area.width && y < buf.area.height {
|
||||
buf.set_string(x, y, self.as_ref(), style.unwrap_or(Style::default()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub struct Timebase {
|
||||
/// Frames per second
|
||||
|
|
@ -144,3 +144,4 @@ impl Timebase {
|
|||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
370
src/device.rs
370
src/device.rs
|
|
@ -1,370 +0,0 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
mod chain;
|
||||
mod launcher;
|
||||
mod looper;
|
||||
mod mixer;
|
||||
mod sequencer;
|
||||
mod track;
|
||||
mod transport;
|
||||
|
||||
pub use self::track::Track;
|
||||
pub use self::launcher::{Launcher, Scene};
|
||||
pub use self::sequencer::{Sequencer, Phrase};
|
||||
pub use self::chain::{Chain, Plugin, Sampler, Sample, Voice};
|
||||
|
||||
pub use self::looper::Looper;
|
||||
pub use self::mixer::Mixer;
|
||||
pub use self::transport::Transport;
|
||||
|
||||
use crossterm::event;
|
||||
use ::jack::{Port, PortSpec, Client};
|
||||
|
||||
/// A UI component that may have presence on the JACK grap.
|
||||
pub trait Device: Render + Handle + PortList + Send + Sync {
|
||||
fn boxed (self) -> Box<dyn Device> where Self: Sized + 'static {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// All things that implement the required traits can be treated as `Device`.
|
||||
impl<T: Render + Handle + PortList + Send + Sync> Device for T {}
|
||||
|
||||
/// Run a device as the root of the app.
|
||||
pub fn run (device: impl Device + Send + Sync + 'static) -> Result<(), Box<dyn Error>> {
|
||||
let device = Arc::new(Mutex::new(device));
|
||||
let exited = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// Spawn input (handle) thread
|
||||
let _input_thread = {
|
||||
let poll = std::time::Duration::from_millis(100);
|
||||
let exited = exited.clone();
|
||||
let device = device.clone();
|
||||
spawn(move || loop {
|
||||
// Exit if flag is set
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
// Listen for events and send them to the main thread
|
||||
if event::poll(poll).is_ok() {
|
||||
let event = event::read().unwrap();
|
||||
match event {
|
||||
Event::Key(KeyEvent {
|
||||
code: KeyCode::Char('c'),
|
||||
modifiers: KeyModifiers::CONTROL,
|
||||
..
|
||||
}) => {
|
||||
exited.store(true, Ordering::Relaxed);
|
||||
},
|
||||
_ => if device.lock().unwrap().handle(&AppEvent::Input(event)).is_err() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
// Set up terminal
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
|
||||
// Set up panic hook
|
||||
let better_panic_handler = better_panic::Settings::auto()
|
||||
.verbosity(better_panic::Verbosity::Full)
|
||||
.create_panic_handler();
|
||||
std::panic::set_hook(Box::new(move |info: &std::panic::PanicInfo|{
|
||||
stdout().execute(LeaveAlternateScreen).unwrap();
|
||||
crossterm::terminal::disable_raw_mode().unwrap();
|
||||
better_panic_handler(info);
|
||||
}));
|
||||
|
||||
// Main (render) loop
|
||||
let sleep = std::time::Duration::from_millis(16);
|
||||
loop {
|
||||
terminal.draw(|frame|{
|
||||
let area = frame.size();
|
||||
let buffer = frame.buffer_mut();
|
||||
device.lock().unwrap().render(buffer, area).expect("Failed to render content.");
|
||||
}).expect("Failed to render frame");
|
||||
if exited.fetch_and(true, Ordering::Relaxed) {
|
||||
break
|
||||
}
|
||||
std::thread::sleep(sleep);
|
||||
};
|
||||
|
||||
// Cleanup
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
crossterm::terminal::disable_raw_mode()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trait for things that handle input events.
|
||||
pub trait Handle {
|
||||
/// Handle an input event.
|
||||
/// Returns Ok(true) if the device handled the event.
|
||||
/// This is the mechanism which allows nesting of components;.
|
||||
fn handle (&mut self, _e: &AppEvent) -> Usually<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppEvent {
|
||||
/// Terminal input
|
||||
Input(::crossterm::event::Event),
|
||||
/// Update values but not the whole form.
|
||||
Update,
|
||||
/// Update the whole form.
|
||||
Redraw,
|
||||
/// Device gains focus
|
||||
Focus,
|
||||
/// Device loses focus
|
||||
Blur,
|
||||
/// JACK notification
|
||||
Jack(JackEvent)
|
||||
}
|
||||
|
||||
/// Trait for things that render to the display.
|
||||
pub trait Render {
|
||||
// Render something to an area of the buffer.
|
||||
// Returns area used by component.
|
||||
// This is insufficient but for the most basic dynamic layout algorithms.
|
||||
fn render (&self, _b: &mut Buffer, _a: Rect) -> Usually<Rect> {
|
||||
Ok(Rect { x: 0, y: 0, width: 0, height: 0 })
|
||||
}
|
||||
fn min_width (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_width (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
fn min_height (&self) -> u16 {
|
||||
0
|
||||
}
|
||||
fn max_height (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for Box<dyn Device> {
|
||||
fn render (&self, b: &mut Buffer, a: Rect) -> Usually<Rect> {
|
||||
(**self).render(b, a)
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for &dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(*self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
impl WidgetRef for dyn Render {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
Render::render(self, buf, area).expect("Failed to render device.");
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Blit {
|
||||
// Render something to X, Y coordinates in a buffer, ignoring width/height.
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>);
|
||||
}
|
||||
|
||||
impl<T: AsRef<str>> Blit for T {
|
||||
fn blit (&self, buf: &mut Buffer, x: u16, y: u16, style: Option<Style>) {
|
||||
if x < buf.area.width && y < buf.area.height {
|
||||
buf.set_string(x, y, self.as_ref(), style.unwrap_or(Style::default()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for things that may expose JACK ports.
|
||||
pub trait PortList {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![])
|
||||
}
|
||||
fn connect (&mut self, _connect: bool, _source: &str, _target: &str)
|
||||
-> Usually<()>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
fn connect_all (&mut self, connections: &[(bool, &str, &str)])
|
||||
-> Usually<()>
|
||||
{
|
||||
for (connect, source, target) in connections.iter() {
|
||||
self.connect(*connect, source, target)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevicePort<T: PortSpec> {
|
||||
pub name: String,
|
||||
pub port: Port<T>,
|
||||
pub connect: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T: PortSpec + Default> DevicePort<T> {
|
||||
pub fn new (client: &Client, name: &str, connect: &[&str]) -> Usually<Self> {
|
||||
let mut connects = vec![];
|
||||
for port in connect.iter() {
|
||||
connects.push(port.to_string());
|
||||
}
|
||||
Ok(Self {
|
||||
name: name.to_string(),
|
||||
port: client.register_port(name, T::default())?,
|
||||
connect: connects,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A device dynamicammy composed of state and handlers.
|
||||
pub struct DynamicDevice<T> {
|
||||
pub state: Arc<Mutex<T>>,
|
||||
pub render: Mutex<Box<dyn FnMut(&T, &mut Buffer, Rect)->Usually<Rect> + Send>>,
|
||||
pub handle: Arc<Mutex<Box<dyn FnMut(&mut T, &AppEvent)->Usually<bool> + Send>>>,
|
||||
pub process: Arc<Mutex<Box<dyn FnMut(&mut T, &Client, &ProcessScope)->Control + Send>>>,
|
||||
pub client: Option<DynamicAsyncClient>
|
||||
}
|
||||
|
||||
impl<T> Handle for DynamicDevice<T> {
|
||||
fn handle (&mut self, event: &AppEvent) -> Usually<bool> {
|
||||
self.handle.lock().unwrap()(&mut *self.state.lock().unwrap(), event)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Render for DynamicDevice<T> {
|
||||
fn render (&self, buf: &mut Buffer, area: Rect) -> Usually<Rect> {
|
||||
self.render.lock().unwrap()(&*self.state.lock().unwrap(), buf, area)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PortList + Send + Sync + 'static> PortList for DynamicDevice<T> {
|
||||
fn audio_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_ins()
|
||||
}
|
||||
fn audio_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().audio_outs()
|
||||
}
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_ins()
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
self.state().midi_outs()
|
||||
}
|
||||
}
|
||||
|
||||
type DynamicAsyncClient = AsyncClient<DynamicNotifications, DynamicProcessHandler>;
|
||||
type DynamicNotifications = Notifications<Box<dyn Fn(AppEvent) + Send + Sync>>;
|
||||
type DynamicProcessHandler = ClosureProcessHandler<BoxedProcessHandler>;
|
||||
|
||||
impl<T: Send + Sync + 'static> DynamicDevice<T> {
|
||||
fn new <'a, R, H, P> (render: R, handle: H, process: P, state: T) -> Self where
|
||||
R: FnMut(&T, &mut Buffer, Rect) -> Usually<Rect> + Send + 'static,
|
||||
H: FnMut(&mut T, &AppEvent) -> Usually<bool> + Send + 'static,
|
||||
P: FnMut(&mut T, &Client, &ProcessScope) -> Control + Send + 'static,
|
||||
{
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(state)),
|
||||
render: Mutex::new(Box::new(render)),
|
||||
handle: Arc::new(Mutex::new(Box::new(handle))),
|
||||
process: Arc::new(Mutex::new(Box::new(process))),
|
||||
client: None,
|
||||
}
|
||||
}
|
||||
pub fn state (&self) -> std::sync::MutexGuard<'_, T> {
|
||||
self.state.lock().unwrap()
|
||||
}
|
||||
fn activate (mut self, client: Client) -> Usually<Self> {
|
||||
self.client = Some(client.activate_async(Notifications(Box::new({
|
||||
let state = self.state.clone();
|
||||
let handle = self.handle.clone();
|
||||
move|event|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut handle = handle.lock().unwrap();
|
||||
handle(&mut state, &event).unwrap();
|
||||
}
|
||||
}) as Box<dyn Fn(AppEvent) + Send + Sync>), ClosureProcessHandler::new(Box::new({
|
||||
let state = self.state.clone();
|
||||
let process = self.process.clone();
|
||||
move|client: &Client, scope: &ProcessScope|{
|
||||
let mut state = state.lock().unwrap();
|
||||
let mut process = process.lock().unwrap();
|
||||
(process)(&mut state, client, scope)
|
||||
}
|
||||
}) as BoxedProcessHandler))?);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum JackEvent {
|
||||
ThreadInit,
|
||||
Shutdown(ClientStatus, String),
|
||||
Freewheel(bool),
|
||||
SampleRate(Frames),
|
||||
ClientRegistration(String, bool),
|
||||
PortRegistration(PortId, bool),
|
||||
PortRename(PortId, String, String),
|
||||
PortsConnected(PortId, PortId, bool),
|
||||
GraphReorder,
|
||||
XRun,
|
||||
}
|
||||
|
||||
pub struct Notifications<T: Fn(AppEvent) + Send>(T);
|
||||
|
||||
impl<T: Fn(AppEvent) + Send> NotificationHandler for Notifications<T> {
|
||||
fn thread_init (&self, _: &Client) {
|
||||
self.0(AppEvent::Jack(JackEvent::ThreadInit));
|
||||
}
|
||||
|
||||
fn shutdown (&mut self, status: ClientStatus, reason: &str) {
|
||||
self.0(AppEvent::Jack(JackEvent::Shutdown(status, reason.into())));
|
||||
}
|
||||
|
||||
fn freewheel (&mut self, _: &Client, enabled: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::Freewheel(enabled)));
|
||||
}
|
||||
|
||||
fn sample_rate (&mut self, _: &Client, frames: Frames) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::SampleRate(frames)));
|
||||
Control::Quit
|
||||
}
|
||||
|
||||
fn client_registration (&mut self, _: &Client, name: &str, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::ClientRegistration(name.into(), reg)));
|
||||
}
|
||||
|
||||
fn port_registration (&mut self, _: &Client, id: PortId, reg: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRegistration(id, reg)));
|
||||
}
|
||||
|
||||
fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::PortRename(id, old.into(), new.into())));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn ports_connected (&mut self, _: &Client, a: PortId, b: PortId, are: bool) {
|
||||
self.0(AppEvent::Jack(JackEvent::PortsConnected(a, b, are)));
|
||||
}
|
||||
|
||||
fn graph_reorder (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::GraphReorder));
|
||||
Control::Continue
|
||||
}
|
||||
|
||||
fn xrun (&mut self, _: &Client) -> Control {
|
||||
self.0(AppEvent::Jack(JackEvent::XRun));
|
||||
Control::Continue
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
Device.inputs is Port[]
|
||||
Device.outputs is Port[]
|
||||
|
||||
Transport is Device
|
||||
Transport.session is Device
|
||||
|
||||
Mixer is Device
|
||||
Mixer.tracks is Device[]
|
||||
|
||||
Chain is Device
|
||||
Chain.devices is Device[]
|
||||
|
||||
Sequencer is Device
|
||||
|
||||
Sampler is Device
|
||||
|
||||
Plugin is Device
|
||||
|
||||
Mixer -> [Track1, Track2... TrackN]
|
||||
|
||||
Track -> [Device1, Device2... N]
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
mod plugin;
|
||||
pub use self::plugin::*;
|
||||
mod sampler;
|
||||
pub use self::sampler::*;
|
||||
mod plugin; pub use self::plugin::*;
|
||||
mod sampler; pub use self::sampler::*;
|
||||
|
||||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::layout::*;
|
||||
|
||||
pub struct Chain {
|
||||
pub name: String,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
mod lv2;
|
||||
mod vst2;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
pub fn plug (uri: &str) -> Usually<PluginKind> {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
impl ::vst::host::Host for Plugin {}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub struct Voice {
|
||||
sample: Arc<Sample>,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
pub struct LauncherGridView<'a> {
|
||||
state: &'a Launcher,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
pub fn handle (state: &mut Launcher, event: &AppEvent) -> Usually<bool> {
|
||||
Ok(handle_keymap(state, event, KEYMAP)? || match state.view {
|
||||
|
|
@ -54,13 +54,13 @@ fn activate (state: &mut Launcher) -> Usually<bool> {
|
|||
Some((track_id, track)),
|
||||
) = (state.scene(), state.track()) {
|
||||
// Launch clip
|
||||
if let Some(Some(phrase_id)) = scene.clips.get(track_id) {
|
||||
if let Some(phrase_id) = scene.clips.get(track_id) {
|
||||
track.sequencer.state().sequence = *phrase_id;
|
||||
}
|
||||
} else if let Some((scene_id, scene)) = state.scene() {
|
||||
// Launch scene
|
||||
for (track_id, track) in state.tracks.iter().enumerate() {
|
||||
if let Some(Some(phrase_id)) = scene.clips.get(track_id) {
|
||||
if let Some(phrase_id) = scene.clips.get(track_id) {
|
||||
track.sequencer.state().sequence = *phrase_id;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::layout::*;
|
||||
use crate::device::*;
|
||||
mod grid;
|
||||
pub use self::grid::*;
|
||||
mod handle;
|
||||
pub use self::grid::*; mod handle;
|
||||
pub use self::handle::*;
|
||||
pub struct Launcher {
|
||||
name: String,
|
||||
timebase: Arc<Timebase>,
|
||||
transport: Transport,
|
||||
transport: ::jack::Transport,
|
||||
playing: TransportState,
|
||||
monitoring: bool,
|
||||
recording: bool,
|
||||
|
|
@ -185,10 +186,10 @@ pub fn render (state: &Launcher, buf: &mut Buffer, mut area: Rect) -> Usually<Re
|
|||
//area.width = 80; // DOS mode
|
||||
//area.height = 25;
|
||||
let Rect { x, y, width, height } = area;
|
||||
crate::device::sequencer::draw_play_stop(buf, x + 1, y, &state.playing);
|
||||
crate::device::sequencer::draw_rec(buf, x + 12, y, state.recording);
|
||||
crate::device::sequencer::draw_mon(buf, x + 19, y, state.monitoring);
|
||||
crate::device::sequencer::draw_dub(buf, x + 26, y, state.overdub);
|
||||
crate::device::transport::draw_play_stop(buf, x + 1, y, &state.playing);
|
||||
crate::device::transport::draw_rec(buf, x + 12, y, state.recording);
|
||||
crate::device::transport::draw_mon(buf, x + 19, y, state.monitoring);
|
||||
crate::device::transport::draw_dub(buf, x + 26, y, state.overdub);
|
||||
draw_bpm(buf, x + 33, y, state.timebase.tempo());
|
||||
draw_timer(buf, x + width - 1, y, &state.timebase, state.position);
|
||||
let mut y = y + 1;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub struct Looper {
|
||||
name: String
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::layout::*;
|
||||
|
||||
pub struct Mixer {
|
||||
name: String,
|
||||
|
|
|
|||
7
src/device/mod.rs
Normal file
7
src/device/mod.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
mod chain; pub use self::chain::{Chain, Plugin, Sampler, Sample, Voice};
|
||||
mod launcher; pub use self::launcher::{Launcher, Scene};
|
||||
mod looper; pub use self::looper::Looper;
|
||||
mod mixer; pub use self::mixer::Mixer;
|
||||
mod sequencer; pub use self::sequencer::{Sequencer, Phrase};
|
||||
mod track; pub use self::track::Track;
|
||||
mod transport; pub use self::transport::Transport;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
pub fn handle (s: &mut Sequencer, event: &AppEvent) -> Usually<bool> {
|
||||
handle_keymap(s, event, KEYMAP)
|
||||
|
|
@ -39,7 +39,7 @@ pub const KEYMAP: &'static [KeyBinding<Sequencer>] = keymap!(Sequencer {
|
|||
});
|
||||
const fn focus_seq (i: usize) -> impl Fn(&mut Sequencer)->Usually<bool> {
|
||||
move |s: &mut Sequencer| {
|
||||
s.sequence = i;
|
||||
s.sequence = Some(i);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
|
@ -47,13 +47,16 @@ fn nop (_: &mut Sequencer) -> Usually<bool> {
|
|||
Ok(false)
|
||||
}
|
||||
fn note_add (s: &mut Sequencer) -> Usually<bool> {
|
||||
if s.sequence.is_none() {
|
||||
return Ok(false)
|
||||
}
|
||||
let step = (s.time_axis.0 + s.time_cursor) as u32;
|
||||
let start = (step as usize * s.timebase.ppq() / s.resolution) as u32;
|
||||
let end = ((step + 1) as usize * s.timebase.ppq() / s.resolution) as u32;
|
||||
let key = u7::from_int_lossy((s.note_cursor + s.note_axis.0) as u8);
|
||||
let note_on = MidiMessage::NoteOn { key, vel: 100.into() };
|
||||
let note_off = MidiMessage::NoteOff { key, vel: 100.into() };
|
||||
let sequence = &mut s.phrases[s.sequence].notes;
|
||||
let sequence = &mut s.phrases[s.sequence.unwrap()].notes;
|
||||
if sequence.contains_key(&start) {
|
||||
sequence.get_mut(&start).unwrap().push(note_on.clone());
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
pub fn draw (
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use super::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub const KEY_WHITE: Style = Style {
|
||||
fg: Some(Color::Gray),
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::layout::*;
|
||||
|
||||
mod keys; use self::keys::*;
|
||||
mod handle; pub use self::handle::*;
|
||||
|
|
@ -22,7 +23,7 @@ pub struct Sequencer {
|
|||
/// FIXME: play start / end / loop in ppm
|
||||
pub steps: usize,
|
||||
/// Phrase selector
|
||||
pub sequence: usize,
|
||||
pub sequence: Option<usize>,
|
||||
/// Map: tick -> MIDI events at tick
|
||||
pub phrases: Vec<Phrase>,
|
||||
/// Red keys on piano roll.
|
||||
|
|
@ -51,12 +52,7 @@ pub struct Sequencer {
|
|||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SequencerView {
|
||||
Tiny,
|
||||
Compact,
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
pub enum SequencerView { Tiny, Compact, Horizontal, Vertical, }
|
||||
|
||||
impl Sequencer {
|
||||
pub fn new (
|
||||
|
|
@ -74,8 +70,10 @@ impl Sequencer {
|
|||
timebase: timebase.clone(),
|
||||
steps: 16,
|
||||
resolution: 4,
|
||||
sequence: 0,
|
||||
phrases: phrases.unwrap_or(vec![]),
|
||||
sequence: Some(0),
|
||||
phrases: phrases.unwrap_or(vec![
|
||||
Phrase::new("Phrase0", 4*timebase.ppq() as u32, None)
|
||||
]),
|
||||
notes_on: vec![false;128],
|
||||
|
||||
playing: TransportState::Starting,
|
||||
|
|
@ -93,12 +91,12 @@ impl Sequencer {
|
|||
}
|
||||
|
||||
pub fn phrase <'a> (&'a self) -> Option<&'a Phrase> {
|
||||
self.phrases.get(self.sequence)
|
||||
self.sequence.map(|s|self.phrases.get(s))?
|
||||
}
|
||||
}
|
||||
|
||||
impl PortList for Sequencer {
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
fn midi_ins (&self) -> Usually<Vec<String>> {
|
||||
Ok(vec![self.midi_in.name()?])
|
||||
}
|
||||
fn midi_outs (&self) -> Usually<Vec<String>> {
|
||||
|
|
@ -117,22 +115,22 @@ fn render (s: &Sequencer, buf: &mut Buffer, area: Rect) -> Usually<Rect> {
|
|||
let steps = usecs / ustep;
|
||||
let header = draw_header(s, buf, area, steps)?;
|
||||
let piano = match s.mode {
|
||||
SequencerView::Tiny =>
|
||||
Rect { x, y, width, height: 0 },
|
||||
SequencerView::Compact =>
|
||||
Rect { x, y, width, height: 0 },
|
||||
SequencerView::Vertical => self::vertical::draw(s, buf, Rect {
|
||||
x,
|
||||
y: y + header.height,
|
||||
width: 3 + note1 - note0,
|
||||
height: 3 + time1 - time0,
|
||||
}, steps)?,
|
||||
SequencerView::Horizontal => self::horizontal::draw(s, buf, Rect {
|
||||
x,
|
||||
y: y + header.height,
|
||||
width: area.width.max(3 + time1 - time0),
|
||||
height: 3 + note1 - note0,
|
||||
}, steps)?,
|
||||
SequencerView::Tiny => Rect { x, y, width, height: 0 },
|
||||
SequencerView::Compact => Rect { x, y, width, height: 0 },
|
||||
SequencerView::Vertical =>
|
||||
self::vertical::draw(s, buf, Rect {
|
||||
x,
|
||||
y: y + header.height,
|
||||
width: 3 + note1 - note0,
|
||||
height: 3 + time1 - time0,
|
||||
}, steps)?,
|
||||
SequencerView::Horizontal =>
|
||||
self::horizontal::draw(s, buf, Rect {
|
||||
x,
|
||||
y: y + header.height,
|
||||
width: area.width.max(3 + time1 - time0),
|
||||
height: 3 + note1 - note0,
|
||||
}, steps)?,
|
||||
};
|
||||
Ok(draw_box(buf, Rect {
|
||||
x,
|
||||
|
|
@ -150,12 +148,12 @@ pub fn draw_header (s: &Sequencer, buf: &mut Buffer, area: Rect, beat: usize) ->
|
|||
let steps = s.steps % s.resolution;
|
||||
draw_timer(buf, x + width - 2, y + 1, &format!("{rep}.{step:02} / {reps}.{steps}"));
|
||||
let style = Style::default().gray();
|
||||
draw_play_stop(buf, x + 2, y + 1, &s.playing);
|
||||
crate::device::transport::draw_play_stop(buf, x + 2, y + 1, &s.playing);
|
||||
let separator = format!("├{}┤", "-".repeat((area.width - 2).into()));
|
||||
separator.blit(buf, x, y + 2, Some(style.dim()));
|
||||
draw_rec(buf, x + 13, y + 1, s.recording);
|
||||
draw_dub(buf, x + 20, y + 1, s.overdub);
|
||||
draw_mon(buf, x + 27, y + 1, s.monitoring);
|
||||
crate::device::transport::draw_rec(buf, x + 13, y + 1, s.recording);
|
||||
crate::device::transport::draw_dub(buf, x + 20, y + 1, s.overdub);
|
||||
crate::device::transport::draw_mon(buf, x + 27, y + 1, s.monitoring);
|
||||
let _ = draw_clips(s, buf, area)?;
|
||||
Ok(Rect { x, y, width: area.width, height: 3 })
|
||||
}
|
||||
|
|
@ -165,45 +163,12 @@ pub fn draw_timer (
|
|||
let style = Some(Style::default().gray().bold().not_dim());
|
||||
timer.blit(buf, x - timer.len() as u16, y, style);
|
||||
}
|
||||
pub fn draw_play_stop (buf: &mut Buffer, x: u16, y: u16, state: &TransportState) {
|
||||
let style = Style::default().gray();
|
||||
match state {
|
||||
TransportState::Rolling => "▶ PLAYING",
|
||||
TransportState::Starting => "READY ...",
|
||||
TransportState::Stopped => "⏹ STOPPED",
|
||||
}.blit(buf, x, y, Some(match state {
|
||||
TransportState::Stopped => style.dim().bold(),
|
||||
TransportState::Starting => style.not_dim().bold(),
|
||||
TransportState::Rolling => style.not_dim().white().bold()
|
||||
}));
|
||||
}
|
||||
pub fn draw_rec (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ REC".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().red()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
pub fn draw_dub (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ DUB".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().yellow()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
pub fn draw_mon (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ MON".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().green()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
fn draw_clips (s: &Sequencer, buf: &mut Buffer, area: Rect) -> Usually<Rect> {
|
||||
let Rect { x, y, .. } = area;
|
||||
let style = Style::default().gray();
|
||||
for (i, sequence) in s.phrases.iter().enumerate() {
|
||||
let label = format!("▶ {}", &sequence.name);
|
||||
label.blit(buf, x + 2, y + 3 + (i as u16)*2, Some(if i == s.sequence {
|
||||
label.blit(buf, x + 2, y + 3 + (i as u16)*2, Some(if Some(i) == s.sequence {
|
||||
match s.playing {
|
||||
TransportState::Rolling => style.white().bold(),
|
||||
_ => style.not_dim().bold()
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use super::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub type PhraseData = BTreeMap<u32, Vec<MidiMessage>>;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
pub fn process (state: &mut Sequencer, _: &Client, scope: &ProcessScope) -> Control {
|
||||
// Get currently playing sequence
|
||||
let sequence = state.phrases.get_mut(state.sequence);
|
||||
if state.sequence.is_none() {
|
||||
return Control::Continue
|
||||
}
|
||||
let sequence = state.phrases.get_mut(state.sequence.unwrap());
|
||||
if sequence.is_none() {
|
||||
return Control::Continue
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
pub fn draw (
|
||||
|
|
@ -18,6 +18,9 @@ pub fn draw (
|
|||
}
|
||||
|
||||
pub fn steps (s: &Sequencer, buf: &mut Buffer, area: Rect, beat: usize) {
|
||||
if s.sequence.is_none() {
|
||||
return
|
||||
}
|
||||
let ppq = s.timebase.ppq() as u32;
|
||||
let bg = Style::default();
|
||||
let bw = bg.dim();
|
||||
|
|
@ -41,8 +44,8 @@ pub fn steps (s: &Sequencer, buf: &mut Buffer, area: Rect, beat: usize) {
|
|||
(step + 2) as u32 * ppq / s.resolution as u32,
|
||||
);
|
||||
let (character, style) = match (
|
||||
contains_note_on(&s.phrases[s.sequence], key, a, b),
|
||||
contains_note_on(&s.phrases[s.sequence], key, b, c),
|
||||
contains_note_on(&s.phrases[s.sequence.unwrap()], key, a, b),
|
||||
contains_note_on(&s.phrases[s.sequence.unwrap()], key, b, c),
|
||||
) {
|
||||
(true, true) => ("█", wh),
|
||||
(true, false) => ("▀", wh),
|
||||
|
|
@ -106,8 +109,8 @@ pub fn keys (s: &Sequencer, buf: &mut Buffer, area: Rect, beat: usize) {
|
|||
(step + 2) as u32 * ppq / s.resolution as u32,
|
||||
);
|
||||
let key = ::midly::num::u7::from(key as u8);
|
||||
is_on = is_on || contains_note_on(&s.phrases[s.sequence], key, a, b);
|
||||
is_on = is_on || contains_note_on(&s.phrases[s.sequence], key, b, c);
|
||||
is_on = is_on || contains_note_on(&s.phrases[s.sequence.unwrap()], key, a, b);
|
||||
is_on = is_on || contains_note_on(&s.phrases[s.sequence.unwrap()], key, b, c);
|
||||
if is_on {
|
||||
color = Style::default().red();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::device::*;
|
||||
use crate::layout::*;
|
||||
pub struct Track {
|
||||
pub name: String,
|
||||
pub sequencer: DynamicDevice<Sequencer>,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,39 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::layout::*;
|
||||
|
||||
pub fn draw_play_stop (buf: &mut Buffer, x: u16, y: u16, state: &TransportState) {
|
||||
let style = Style::default().gray();
|
||||
match state {
|
||||
TransportState::Rolling => "▶ PLAYING",
|
||||
TransportState::Starting => "READY ...",
|
||||
TransportState::Stopped => "⏹ STOPPED",
|
||||
}.blit(buf, x, y, Some(match state {
|
||||
TransportState::Stopped => style.dim().bold(),
|
||||
TransportState::Starting => style.not_dim().bold(),
|
||||
TransportState::Rolling => style.not_dim().white().bold()
|
||||
}));
|
||||
}
|
||||
pub fn draw_rec (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ REC".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().red()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
pub fn draw_dub (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ DUB".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().yellow()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
pub fn draw_mon (buf: &mut Buffer, x: u16, y: u16, on: bool) {
|
||||
"⏺ MON".blit(buf, x, y, Some(if on {
|
||||
Style::default().bold().green()
|
||||
} else {
|
||||
Style::default().bold().dim()
|
||||
}))
|
||||
}
|
||||
|
||||
pub struct Transport {
|
||||
name: String,
|
||||
|
|
|
|||
111
src/draw.rs
111
src/draw.rs
|
|
@ -1,111 +0,0 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
//let render_with_actions = |actions| |state, frame: &mut Frame| {
|
||||
//let layout = Layout::default()
|
||||
//.direction(Direction::Horizontal)
|
||||
//.constraints(vec![
|
||||
//Constraint::Percentage(30),
|
||||
//Constraint::Percentage(70),
|
||||
//])
|
||||
//.split(frame.size());
|
||||
//frame.render_widget_ref(ActionBar(actions), layout[0]);
|
||||
//frame.render_widget_ref(state, layout[1]);
|
||||
//Ok(())
|
||||
//};
|
||||
|
||||
pub struct ActionBar<'a>(pub &'a [(&'static str, &'static str)]);
|
||||
|
||||
impl<'a> WidgetRef for ActionBar<'a> {
|
||||
fn render_ref (&self, area: Rect, buf: &mut Buffer) {
|
||||
let layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints(self.0.iter().map(|_|Constraint::Length(3)).collect::<Vec<_>>())
|
||||
.split(area);
|
||||
for (index, action) in self.0.iter().enumerate() {
|
||||
Line::raw(action.0).render(layout[index], buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_leaf (buffer: &mut Buffer, area: Rect, y: u16, x: u16, text: &str) {
|
||||
let border = Style::default().gray().dim();
|
||||
let label = Style::default();
|
||||
let side = String::from("│");
|
||||
let bottom = format!("╰{}╯", "─".repeat(text.len() as usize));
|
||||
buffer.set_string(area.x + x, area.y + y, &side, border);
|
||||
buffer.set_string(area.x + x + 1, area.y + y, format!("{text}"), label);
|
||||
buffer.set_string(area.x + x + text.len() as u16 + 1, area.y + y, &side, border);
|
||||
buffer.set_string(area.x + x, area.y + 1 + y, bottom, border);
|
||||
}
|
||||
|
||||
pub fn draw_corners (buffer: &mut Buffer, area: Rect, style: Option<Style>) -> Rect {
|
||||
let style = style.unwrap_or(Style::default());
|
||||
buffer.set_string(area.x, area.y, "╭", style);
|
||||
buffer.set_string(area.x + area.width - 1, area.y, "╮", style);
|
||||
buffer.set_string(area.x, area.y + area.height - 1, "╰", style);
|
||||
buffer.set_string(area.x + area.width - 1, area.y + area.height - 1, "╯", style);
|
||||
area
|
||||
}
|
||||
|
||||
pub fn draw_focus_corners (buffer: &mut Buffer, area: Rect) -> Rect {
|
||||
draw_corners(buffer, area, Some(Style::default().yellow().bold().not_dim()))
|
||||
}
|
||||
|
||||
//pub fn render_toolbar_vertical (
|
||||
//stdout: &mut std::io::Stdout,
|
||||
//offset: (u16, u16),
|
||||
//actions: &[(&str, &str)],
|
||||
//) -> Result<(u16, u16), Box<dyn Error>> {
|
||||
//let move_to = |col, row| MoveTo(offset.0 + col, offset.1 + row);
|
||||
//let mut x: u16 = 1;
|
||||
//let mut y: u16 = 0;
|
||||
//for (name, description) in actions.iter() {
|
||||
//stdout.queue(move_to(1, y))?.queue(
|
||||
//PrintStyledContent(name.yellow().bold())
|
||||
//)?.queue(move_to(1, y + 1))?.queue(
|
||||
//PrintStyledContent(description.yellow())
|
||||
//)?;
|
||||
//y = y + 3;
|
||||
//x = u16::max(x, usize::max(name.len(), description.len()) as u16);
|
||||
//}
|
||||
//Ok((x, y))
|
||||
//}
|
||||
|
||||
//pub fn render_box (
|
||||
//stdout: &mut std::io::Stdout,
|
||||
//title: Option<&str>,
|
||||
//x: u16,
|
||||
//y: u16,
|
||||
//mut w: u16,
|
||||
//h: u16,
|
||||
//active: bool
|
||||
//) -> Result<(), Box<dyn Error>> {
|
||||
//if let Some(title) = title {
|
||||
//w = u16::max(w, title.len() as u16 + 4);
|
||||
//}
|
||||
//let back: String = std::iter::repeat(" ").take(w.saturating_sub(2) as usize).collect();
|
||||
//if active {
|
||||
//let edge: String = std::iter::repeat("━").take(w.saturating_sub(2) as usize).collect();
|
||||
//stdout.queue(MoveTo(x, y))?.queue(PrintStyledContent(format!("┏{edge}┓").bold().yellow()))?;
|
||||
//if let Some(title) = title {
|
||||
//stdout.queue(MoveTo(x+1, y))?.queue(PrintStyledContent(format!(" {title} ").yellow()))?;
|
||||
//}
|
||||
//for row in y+1..y+h {
|
||||
//stdout.queue(MoveTo(x, row))?.queue(PrintStyledContent("┃".bold().yellow()))?;
|
||||
//stdout.queue(MoveTo(x+w-1, row))?.queue(PrintStyledContent("┃".bold().yellow()))?;
|
||||
//}
|
||||
//stdout.queue(MoveTo(x, y+h))?.queue(PrintStyledContent(format!("┗{edge}┛").bold().yellow()))?;
|
||||
//} else {
|
||||
//let edge: String = std::iter::repeat("─").take(w.saturating_sub(2) as usize).collect();
|
||||
//stdout.queue(MoveTo(x, y))?.queue(PrintStyledContent(format!("┌{edge}┐").grey().dim()))?;
|
||||
//if let Some(title) = title {
|
||||
//stdout.queue(MoveTo(x+1, y))?.queue(Print(format!(" {title} ")))?;
|
||||
//}
|
||||
//for row in y+1..y+h {
|
||||
//stdout.queue(MoveTo(x, row))?.queue(PrintStyledContent("│".grey().dim()))?;
|
||||
//stdout.queue(MoveTo(x+w-1, row))?.queue(PrintStyledContent("│".grey().dim()))?;
|
||||
//}
|
||||
//stdout.queue(MoveTo(x, y+h))?.queue(PrintStyledContent(format!("└{edge}┘").grey().dim()))?;
|
||||
//}
|
||||
//Ok(())
|
||||
//}
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use super::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub struct Column(pub Vec<Box<dyn Device>>);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use super::*;
|
||||
|
||||
pub trait Focus {
|
||||
fn unfocus (&mut self);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
const LOZENGE: [[&'static str;3];3] = [
|
||||
["╭", "─", "╮"],
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
mod focus;
|
||||
pub use focus::*;
|
||||
mod container;
|
||||
pub use container::*;
|
||||
mod scroll;
|
||||
pub use scroll::*;
|
||||
mod table;
|
||||
pub use table::*;
|
||||
mod lozenge;
|
||||
pub use lozenge::*;
|
||||
mod focus; pub use self::focus::*;
|
||||
mod container; pub use self::container::*;
|
||||
mod scroll; pub use self::scroll::*;
|
||||
mod table; pub use self::table::*;
|
||||
mod lozenge; pub use self::lozenge::*;
|
||||
|
||||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub trait MaxHeight: Device {
|
||||
fn max_height (&self) -> u16 {
|
||||
u16::MAX
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Device> MaxHeight for T {}
|
||||
|
||||
pub fn draw_box (buffer: &mut Buffer, area: Rect) -> Rect {
|
||||
draw_box_styled(buffer, area, Some(Style::default().gray().dim()))
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
use crate::prelude::*;
|
||||
|
||||
pub struct ScrollY;
|
||||
|
||||
pub struct ScrollX;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
|
||||
pub struct Cell<T> {
|
||||
text: String,
|
||||
|
|
|
|||
11
src/main.rs
11
src/main.rs
|
|
@ -1,3 +1,5 @@
|
|||
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
|
||||
|
||||
extern crate clap;
|
||||
extern crate jack;
|
||||
extern crate crossterm;
|
||||
|
|
@ -5,15 +7,14 @@ extern crate crossterm;
|
|||
use clap::{Parser};
|
||||
use std::error::Error;
|
||||
|
||||
pub mod core;
|
||||
pub mod cli;
|
||||
pub mod device;
|
||||
pub mod prelude;
|
||||
pub mod draw;
|
||||
pub mod config;
|
||||
pub mod device;
|
||||
pub mod layout;
|
||||
pub mod time;
|
||||
|
||||
use crate::prelude::*;
|
||||
use crate::core::*;
|
||||
use crate::device::*;
|
||||
|
||||
macro_rules! sample {
|
||||
($note:expr, $name:expr, $src:expr) => {
|
||||
|
|
|
|||
26
src/note.rs
26
src/note.rs
|
|
@ -1,26 +0,0 @@
|
|||
pub const C_4: u8 = 0;
|
||||
pub const C_3: u8 = 12;
|
||||
pub const C_2: u8 = 24;
|
||||
pub const C_1: u8 = 36;
|
||||
pub const C0: u8 = 48;
|
||||
pub const C1: u8 = 60;
|
||||
pub const C2: u8 = 72;
|
||||
pub const C3: u8 = 84;
|
||||
pub const C4: u8 = 96;
|
||||
pub const C5: u8 = 108;
|
||||
pub const C6: u8 = 120;
|
||||
|
||||
pub enum Pitch {
|
||||
C = 0,
|
||||
Cs,
|
||||
D,
|
||||
Ds,
|
||||
E,
|
||||
F,
|
||||
Fs,
|
||||
G,
|
||||
Gs,
|
||||
A,
|
||||
As,
|
||||
B
|
||||
}
|
||||
112
src/prelude.rs
112
src/prelude.rs
|
|
@ -1,112 +0,0 @@
|
|||
pub type Usually<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
pub use crate::draw::*;
|
||||
pub use crate::device::*;
|
||||
pub use crate::time::*;
|
||||
pub use crate::layout::*;
|
||||
|
||||
pub use std::error::Error;
|
||||
pub use std::io::{stdout, Stdout, Write};
|
||||
pub use std::thread::{spawn, JoinHandle};
|
||||
pub use std::time::Duration;
|
||||
pub use std::collections::BTreeMap;
|
||||
pub use std::sync::{
|
||||
Arc,
|
||||
Mutex, MutexGuard,
|
||||
atomic::{
|
||||
Ordering,
|
||||
AtomicBool,
|
||||
AtomicUsize
|
||||
},
|
||||
mpsc::{self, channel, Sender, Receiver}
|
||||
};
|
||||
|
||||
pub use crossterm::{
|
||||
ExecutableCommand, QueueableCommand,
|
||||
event::{Event, KeyEvent, KeyCode, KeyModifiers},
|
||||
terminal::{
|
||||
self,
|
||||
Clear, ClearType,
|
||||
EnterAlternateScreen, LeaveAlternateScreen,
|
||||
enable_raw_mode, disable_raw_mode
|
||||
},
|
||||
};
|
||||
|
||||
pub use ratatui::{
|
||||
prelude::{
|
||||
Buffer, Rect, Style, Color, CrosstermBackend, Layout, Stylize, Direction,
|
||||
Line, Constraint
|
||||
},
|
||||
widgets::{Widget, WidgetRef},
|
||||
//style::Stylize,
|
||||
};
|
||||
|
||||
pub use ::midly::{MidiMessage, live::LiveEvent, num::u7};
|
||||
|
||||
pub use jack::{
|
||||
AsyncClient,
|
||||
AudioIn,
|
||||
AudioOut,
|
||||
Client,
|
||||
ClientOptions,
|
||||
ClientStatus,
|
||||
ClosureProcessHandler,
|
||||
Control,
|
||||
Frames,
|
||||
MidiIn,
|
||||
MidiOut,
|
||||
NotificationHandler,
|
||||
Port,
|
||||
PortFlags,
|
||||
PortId,
|
||||
ProcessHandler,
|
||||
ProcessScope,
|
||||
RawMidi,
|
||||
Transport,
|
||||
TransportState,
|
||||
TransportStatePosition
|
||||
};
|
||||
|
||||
pub type BoxedNotificationHandler = Box<dyn Fn(AppEvent) + Send>;
|
||||
|
||||
pub type BoxedProcessHandler = Box<dyn FnMut(&Client, &ProcessScope)-> Control + Send>;
|
||||
|
||||
pub type Jack<N> = AsyncClient<N, ClosureProcessHandler<BoxedProcessHandler>>;
|
||||
|
||||
pub type KeyHandler<T> = &'static dyn Fn(&mut T)->Usually<bool>;
|
||||
|
||||
pub type KeyBinding<T> = (
|
||||
KeyCode, KeyModifiers, &'static str, &'static str, KeyHandler<T>
|
||||
);
|
||||
|
||||
#[macro_export] macro_rules! key {
|
||||
($k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr) => {
|
||||
(KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! keymap {
|
||||
($T:ty { $([$k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr]),* $(,)? }) => {
|
||||
&[
|
||||
$((KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f as KeyHandler<$T>)),*
|
||||
] as &'static [KeyBinding<$T>]
|
||||
}
|
||||
}
|
||||
|
||||
pub use crate::{key, keymap};
|
||||
|
||||
pub fn handle_keymap <T> (
|
||||
state: &mut T, event: &AppEvent, keymap: &[KeyBinding<T>],
|
||||
) -> Usually<bool> {
|
||||
match event {
|
||||
AppEvent::Input(Event::Key(event)) => {
|
||||
for (code, modifiers, _, _, command) in keymap.iter() {
|
||||
if *code == event.code && modifiers.bits() == event.modifiers.bits() {
|
||||
return command(state)
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
};
|
||||
Ok(false)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue