tek/src/device.rs
2024-07-04 01:36:31 +03:00

364 lines
12 KiB
Rust

use crate::prelude::*;
mod transport;
mod chain;
mod sequencer;
mod sampler;
mod mixer;
mod looper;
mod plugin;
mod launcher;
pub use self::transport::Transport;
pub use self::chain::Chain;
pub use self::sequencer::Sequencer;
pub use self::sampler::Sampler;
pub use self::mixer::Mixer;
pub use self::looper::Looper;
pub use self::plugin::Plugin;
pub use self::launcher::Launcher;
use crossterm::event;
use ::jack::{AudioIn, AudioOut, MidiIn, MidiOut, Port, PortSpec, Client};
pub trait Device: Render + Handle + PortList + Send + Sync {
fn boxed (self) -> Box<dyn Device> where Self: Sized + 'static {
Box::new(self)
}
}
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));
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
}
}
}
})
};
stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(stdout()))?;
//better_panic::install();
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(crossterm::terminal::LeaveAlternateScreen)
.unwrap();
crossterm::terminal::disable_raw_mode()
.unwrap();
better_panic_handler(info);
//writeln!(std::io::stderr(), "{}", info)
//.unwrap();
//writeln!(std::io::stderr(), "{:?}", ::backtrace::Backtrace::new())
//.unwrap();
}));
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);
};
//render_thread.join().expect("Failed to join render thread");
stdout()
.queue(crossterm::terminal::LeaveAlternateScreen)?
.flush()?;
crossterm::terminal::disable_raw_mode()?;
Ok(())
}
impl<T: Render + Handle + PortList + Send + Sync> Device for T {}
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)
}
}
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 })
}
}
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()))
}
}
}
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(())
}
}
impl Render for Box<dyn Device> {
fn render (&self, b: &mut Buffer, a: Rect) -> Usually<Rect> {
(**self).render(b, a)
}
}
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,
})
}
}
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 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 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)
}
fn panic_hook (info: &std::panic::PanicInfo) {
stdout()
.execute(crossterm::terminal::LeaveAlternateScreen)
.unwrap();
crossterm::terminal::disable_raw_mode()
.unwrap();
writeln!(std::io::stderr(), "{}", info)
.unwrap();
writeln!(std::io::stderr(), "{:?}", ::backtrace::Backtrace::new())
.unwrap();
}
#[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
}
}