mirror of
https://codeberg.org/unspeaker/tek.git
synced 2026-04-04 05:10:44 +02:00
modularize core
This commit is contained in:
parent
a4061535b5
commit
2837ffff4a
43 changed files with 629 additions and 770 deletions
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
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue