begin work on TUI
This commit is contained in:
parent
edbbae3368
commit
cbd07a159a
|
@ -0,0 +1,9 @@
|
|||
Config(
|
||||
keybinds: {
|
||||
Home: {
|
||||
"<q>": Quit,
|
||||
"<Ctrl-c>": Quit,
|
||||
"<esc>": Quit,
|
||||
},
|
||||
}
|
||||
)
|
File diff suppressed because it is too large
Load Diff
26
Cargo.toml
26
Cargo.toml
|
@ -4,20 +4,18 @@ version = "0.1.0"
|
|||
edition = "2021"
|
||||
authors = [ "Rowan S-L <r@fawkes.io>" ]
|
||||
description = "DMM - The Declarative Music Manager"
|
||||
repository = "https://git.fawkes.io/mtnash/dmm"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = { version = "1.0.75", features = ["backtrace"] }
|
||||
clap = { version = "4.4.8", features = ["derive", "wrap_help", "cargo"] }
|
||||
clap = { version = "4.4.8", features = ["derive", "wrap_help", "cargo", "unicode", "string", "unstable-styles"] }
|
||||
heck = "0.4.1"
|
||||
ron = "0.8.1"
|
||||
serde = { version = "1.0.193", features = ["derive"] }
|
||||
uuid = { version = "1.6.1", features = ["v4", "serde"] }
|
||||
notify-rust = "4.10.0"
|
||||
symphonia = { version = "0.5.3", features = ["mp3", "aac", "alac"] }
|
||||
log = "0.4.20"
|
||||
pretty_env_logger = "0.5.0"
|
||||
cpal = "0.15.2"
|
||||
arrayvec = "0.7.4"
|
||||
rb = "0.4.1"
|
||||
|
@ -25,9 +23,27 @@ rubato = "0.14.1"
|
|||
tokio = { version = "1.34.0", features = ["full"] }
|
||||
futures = "0.3.29"
|
||||
async-trait = "0.1.74"
|
||||
ratatui = { version = "0.24.0", features = ["all-widgets"] }
|
||||
ratatui = { version = "0.24.0", features = ["serde", "macros"] }
|
||||
flume = "0.11.0"
|
||||
fuzzy-matcher = "0.3.7"
|
||||
tracing = "0.1.40"
|
||||
tracing-error = "0.2.0"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "local-time"] }
|
||||
lazy_static = "1.4.0"
|
||||
directories = "5.0.1"
|
||||
color-eyre = "0.6.2"
|
||||
log = "0.4.20"
|
||||
better-panic = "0.3.0"
|
||||
libc = "0.2.148"
|
||||
strip-ansi-escapes = "0.2.0"
|
||||
human-panic = "1.2.0"
|
||||
tokio-util = "0.7.9"
|
||||
crossterm = { version = "0.27.0", features = ["serde", "event-stream"] }
|
||||
signal-hook = "0.3.17"
|
||||
config = "0.13.4"
|
||||
derive_deref = "1.1.1"
|
||||
serde_json = "1.0.108"
|
||||
json5 = "0.4.1"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
|
|
@ -0,0 +1,55 @@
|
|||
fn main() {
|
||||
let git_output = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--git-dir"])
|
||||
.output()
|
||||
.ok();
|
||||
let git_dir = git_output.as_ref().and_then(|output| {
|
||||
std::str::from_utf8(&output.stdout)
|
||||
.ok()
|
||||
.and_then(|s| s.strip_suffix('\n').or_else(|| s.strip_suffix("\r\n")))
|
||||
});
|
||||
|
||||
// Tell cargo to rebuild if the head or any relevant refs change.
|
||||
if let Some(git_dir) = git_dir {
|
||||
let git_path = std::path::Path::new(git_dir);
|
||||
let refs_path = git_path.join("refs");
|
||||
if git_path.join("HEAD").exists() {
|
||||
println!("cargo:rerun-if-changed={}/HEAD", git_dir);
|
||||
}
|
||||
if git_path.join("packed-refs").exists() {
|
||||
println!("cargo:rerun-if-changed={}/packed-refs", git_dir);
|
||||
}
|
||||
if refs_path.join("heads").exists() {
|
||||
println!("cargo:rerun-if-changed={}/refs/heads", git_dir);
|
||||
}
|
||||
if refs_path.join("tags").exists() {
|
||||
println!("cargo:rerun-if-changed={}/refs/tags", git_dir);
|
||||
}
|
||||
}
|
||||
|
||||
let git_output = std::process::Command::new("git")
|
||||
.args(["describe", "--always", "--tags", "--long", "--dirty"])
|
||||
.output()
|
||||
.ok();
|
||||
let git_info = git_output
|
||||
.as_ref()
|
||||
.and_then(|output| std::str::from_utf8(&output.stdout).ok().map(str::trim));
|
||||
let cargo_pkg_version = env!("CARGO_PKG_VERSION");
|
||||
|
||||
// Default git_describe to cargo_pkg_version
|
||||
let mut git_describe = String::from(cargo_pkg_version);
|
||||
|
||||
if let Some(git_info) = git_info {
|
||||
// If the `git_info` contains `CARGO_PKG_VERSION`, we simply use `git_info` as it is.
|
||||
// Otherwise, prepend `CARGO_PKG_VERSION` to `git_info`.
|
||||
if git_info.contains(cargo_pkg_version) {
|
||||
// Remove the 'g' before the commit sha
|
||||
let git_info = &git_info.replace('g', "");
|
||||
git_describe = git_info.to_string();
|
||||
} else {
|
||||
git_describe = format!("v{}-{}", cargo_pkg_version, git_info);
|
||||
}
|
||||
}
|
||||
|
||||
println!("cargo:rustc-env=_GIT_INFO={}", git_describe);
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
use std::fmt;
|
||||
|
||||
use serde::{
|
||||
de::{self, Deserializer, Visitor},
|
||||
Deserialize, Serialize,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Action {
|
||||
Tick,
|
||||
Render,
|
||||
Resize(u16, u16),
|
||||
Suspend,
|
||||
Resume,
|
||||
Quit,
|
||||
Refresh,
|
||||
Error(String),
|
||||
Help,
|
||||
}
|
||||
|
||||
// impl<'de> Deserialize<'de> for Action {
|
||||
// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
// where
|
||||
// D: Deserializer<'de>,
|
||||
// {
|
||||
// struct ActionVisitor;
|
||||
|
||||
// impl<'de> Visitor<'de> for ActionVisitor {
|
||||
// type Value = Action;
|
||||
|
||||
// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
// formatter.write_str("a valid string representation of Action")
|
||||
// }
|
||||
|
||||
// fn visit_str<E>(self, value: &str) -> Result<Action, E>
|
||||
// where
|
||||
// E: de::Error,
|
||||
// {
|
||||
// match value {
|
||||
// "Tick" => Ok(Action::Tick),
|
||||
// "Render" => Ok(Action::Render),
|
||||
// "Suspend" => Ok(Action::Suspend),
|
||||
// "Resume" => Ok(Action::Resume),
|
||||
// "Quit" => Ok(Action::Quit),
|
||||
// "Refresh" => Ok(Action::Refresh),
|
||||
// "Help" => Ok(Action::Help),
|
||||
// data if data.starts_with("Error(") => {
|
||||
// let error_msg = data.trim_start_matches("Error(").trim_end_matches(")");
|
||||
// Ok(Action::Error(error_msg.to_string()))
|
||||
// }
|
||||
// data if data.starts_with("Resize(") => {
|
||||
// let parts: Vec<&str> = data
|
||||
// .trim_start_matches("Resize(")
|
||||
// .trim_end_matches(")")
|
||||
// .split(',')
|
||||
// .collect();
|
||||
// if parts.len() == 2 {
|
||||
// let width: u16 = parts[0].trim().parse().map_err(E::custom)?;
|
||||
// let height: u16 = parts[1].trim().parse().map_err(E::custom)?;
|
||||
// Ok(Action::Resize(width, height))
|
||||
// } else {
|
||||
// Err(E::custom(format!("Invalid Resize format: {}", value)))
|
||||
// }
|
||||
// }
|
||||
// _ => Err(E::custom(format!("Unknown Action variant: {}", value))),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// deserializer.deserialize_str(ActionVisitor)
|
||||
// }
|
||||
// }
|
|
@ -0,0 +1,159 @@
|
|||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use ratatui::prelude::Rect;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::{
|
||||
action::Action,
|
||||
cfg::Config,
|
||||
components::{fps::FpsCounter, home::Home, Component},
|
||||
mode::Mode,
|
||||
tui,
|
||||
};
|
||||
|
||||
pub struct App {
|
||||
pub tick_rate: f64,
|
||||
pub frame_rate: f64,
|
||||
pub components: Vec<Box<dyn Component>>,
|
||||
pub should_quit: bool,
|
||||
pub should_suspend: bool,
|
||||
pub mode: Mode,
|
||||
pub last_tick_key_events: Vec<KeyEvent>,
|
||||
pub config: Config,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
|
||||
let home = Home::new();
|
||||
let config = Config::new()?;
|
||||
let fps = FpsCounter::default();
|
||||
let mode = Mode::Home;
|
||||
Ok(Self {
|
||||
tick_rate,
|
||||
frame_rate,
|
||||
components: vec![Box::new(home), Box::new(fps)],
|
||||
should_quit: false,
|
||||
should_suspend: false,
|
||||
mode,
|
||||
last_tick_key_events: Vec::new(),
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Result<()> {
|
||||
let (action_tx, mut action_rx) = mpsc::unbounded_channel();
|
||||
|
||||
let mut tui = tui::Tui::new()?
|
||||
.mouse(false)
|
||||
.paste(true)
|
||||
.tick_rate(self.tick_rate)
|
||||
.frame_rate(self.frame_rate);
|
||||
tui.enter()?;
|
||||
|
||||
for component in self.components.iter_mut() {
|
||||
component.register_action_handler(action_tx.clone())?;
|
||||
}
|
||||
|
||||
for component in self.components.iter_mut() {
|
||||
component.register_config_handler(self.config.clone())?;
|
||||
}
|
||||
|
||||
for component in self.components.iter_mut() {
|
||||
component.init(tui.size()?)?;
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Some(e) = tui.next().await {
|
||||
match e {
|
||||
tui::Event::Quit => action_tx.send(Action::Quit)?,
|
||||
tui::Event::Tick => action_tx.send(Action::Tick)?,
|
||||
tui::Event::Render => action_tx.send(Action::Render)?,
|
||||
tui::Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
|
||||
tui::Event::Key(key) => {
|
||||
if let Some(keymap) = self.config.keybinds.get(&self.mode) {
|
||||
if let Some(action) = keymap.get(&vec![key]) {
|
||||
log::info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
} else {
|
||||
// If the key was not handled as a single key action,
|
||||
// then consider it for multi-key combinations.
|
||||
self.last_tick_key_events.push(key);
|
||||
|
||||
// Check for multi-key combinations
|
||||
if let Some(action) = keymap.get(&self.last_tick_key_events) {
|
||||
log::info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for component in self.components.iter_mut() {
|
||||
if let Some(action) = component.handle_events(Some(e.clone()))? {
|
||||
action_tx.send(action)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while let Ok(action) = action_rx.try_recv() {
|
||||
if action != Action::Tick && action != Action::Render {
|
||||
log::debug!("{action:?}");
|
||||
}
|
||||
match action {
|
||||
Action::Tick => {
|
||||
self.last_tick_key_events.drain(..);
|
||||
}
|
||||
Action::Quit => self.should_quit = true,
|
||||
Action::Suspend => self.should_suspend = true,
|
||||
Action::Resume => self.should_suspend = false,
|
||||
Action::Resize(w, h) => {
|
||||
tui.resize(Rect::new(0, 0, w, h))?;
|
||||
tui.draw(|f| {
|
||||
for component in self.components.iter_mut() {
|
||||
let r = component.draw(f, f.size());
|
||||
if let Err(e) = r {
|
||||
action_tx
|
||||
.send(Action::Error(format!("Failed to draw: {:?}", e)))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Action::Render => {
|
||||
tui.draw(|f| {
|
||||
for component in self.components.iter_mut() {
|
||||
let r = component.draw(f, f.size());
|
||||
if let Err(e) = r {
|
||||
action_tx
|
||||
.send(Action::Error(format!("Failed to draw: {:?}", e)))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for component in self.components.iter_mut() {
|
||||
if let Some(action) = component.update(action.clone())? {
|
||||
action_tx.send(action)?
|
||||
};
|
||||
}
|
||||
}
|
||||
if self.should_suspend {
|
||||
tui.suspend()?;
|
||||
action_tx.send(Action::Resume)?;
|
||||
tui = tui::Tui::new()?
|
||||
.tick_rate(self.tick_rate)
|
||||
.frame_rate(self.frame_rate);
|
||||
// tui.mouse(true);
|
||||
tui.enter()?;
|
||||
} else if self.should_quit {
|
||||
tui.stop()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
tui.exit()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,257 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use derive_deref::{Deref, DerefMut};
|
||||
use serde::{de::Deserializer, Deserialize};
|
||||
|
||||
use crate::{action::Action, mode::Mode, project_meta::get_config_dir};
|
||||
|
||||
const CONFIG: &str = include_str!("../.config/config.ron");
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub keybinds: KeyBindings,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn new() -> Result<Self, config::ConfigError> {
|
||||
let default_config: Config = ron::from_str(CONFIG).unwrap();
|
||||
let config_dir = get_config_dir();
|
||||
let mut builder = config::Config::builder();
|
||||
|
||||
let config_files = [
|
||||
("config.ron", config::FileFormat::Ron),
|
||||
("config.json5", config::FileFormat::Json5),
|
||||
("config.json", config::FileFormat::Json),
|
||||
("config.yaml", config::FileFormat::Yaml),
|
||||
("config.toml", config::FileFormat::Toml),
|
||||
("config.ini", config::FileFormat::Ini),
|
||||
];
|
||||
let mut found_config = false;
|
||||
for (file, format) in &config_files {
|
||||
builder = builder.add_source(
|
||||
config::File::from(config_dir.join(file))
|
||||
.format(*format)
|
||||
.required(false),
|
||||
);
|
||||
if config_dir.join(file).exists() {
|
||||
found_config = true
|
||||
}
|
||||
}
|
||||
if !found_config {
|
||||
log::error!("No configuration file found. Application may not behave as expected");
|
||||
}
|
||||
|
||||
let mut cfg: Self = builder.build()?.try_deserialize()?;
|
||||
debug!("{default_config:?}");
|
||||
|
||||
for (mode, default_bindings) in default_config.keybinds.iter() {
|
||||
let user_bindings = cfg.keybinds.entry(*mode).or_default();
|
||||
for (key, cmd) in default_bindings.iter() {
|
||||
user_bindings
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| cmd.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deref, DerefMut)]
|
||||
pub struct KeyBindings(pub HashMap<Mode, HashMap<Vec<KeyEvent>, Action>>);
|
||||
|
||||
impl<'de> Deserialize<'de> for KeyBindings {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let parsed_map = HashMap::<Mode, HashMap<String, Action>>::deserialize(deserializer)?;
|
||||
|
||||
let keybindings = parsed_map
|
||||
.into_iter()
|
||||
.map(|(mode, inner_map)| {
|
||||
let converted_inner_map = inner_map
|
||||
.into_iter()
|
||||
.map(|(key_str, cmd)| (parse_key_sequence(&key_str).unwrap(), cmd))
|
||||
.collect();
|
||||
(mode, converted_inner_map)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(KeyBindings(keybindings))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_key_event(raw: &str) -> Result<KeyEvent, String> {
|
||||
let raw_lower = raw.to_ascii_lowercase();
|
||||
let (remaining, modifiers) = extract_modifiers(&raw_lower);
|
||||
parse_key_code_with_modifiers(remaining, modifiers)
|
||||
}
|
||||
|
||||
fn extract_modifiers(raw: &str) -> (&str, KeyModifiers) {
|
||||
let mut modifiers = KeyModifiers::empty();
|
||||
let mut current = raw;
|
||||
|
||||
loop {
|
||||
match current {
|
||||
rest if rest.starts_with("ctrl-") => {
|
||||
modifiers.insert(KeyModifiers::CONTROL);
|
||||
current = &rest[5..];
|
||||
}
|
||||
rest if rest.starts_with("alt-") => {
|
||||
modifiers.insert(KeyModifiers::ALT);
|
||||
current = &rest[4..];
|
||||
}
|
||||
rest if rest.starts_with("shift-") => {
|
||||
modifiers.insert(KeyModifiers::SHIFT);
|
||||
current = &rest[6..];
|
||||
}
|
||||
_ => break, // break out of the loop if no known prefix is detected
|
||||
};
|
||||
}
|
||||
|
||||
(current, modifiers)
|
||||
}
|
||||
|
||||
fn parse_key_code_with_modifiers(
|
||||
raw: &str,
|
||||
mut modifiers: KeyModifiers,
|
||||
) -> Result<KeyEvent, String> {
|
||||
let c = match raw {
|
||||
"esc" => KeyCode::Esc,
|
||||
"enter" => KeyCode::Enter,
|
||||
"left" => KeyCode::Left,
|
||||
"right" => KeyCode::Right,
|
||||
"up" => KeyCode::Up,
|
||||
"down" => KeyCode::Down,
|
||||
"home" => KeyCode::Home,
|
||||
"end" => KeyCode::End,
|
||||
"pageup" => KeyCode::PageUp,
|
||||
"pagedown" => KeyCode::PageDown,
|
||||
"backtab" => {
|
||||
modifiers.insert(KeyModifiers::SHIFT);
|
||||
KeyCode::BackTab
|
||||
}
|
||||
"backspace" => KeyCode::Backspace,
|
||||
"delete" => KeyCode::Delete,
|
||||
"insert" => KeyCode::Insert,
|
||||
"f1" => KeyCode::F(1),
|
||||
"f2" => KeyCode::F(2),
|
||||
"f3" => KeyCode::F(3),
|
||||
"f4" => KeyCode::F(4),
|
||||
"f5" => KeyCode::F(5),
|
||||
"f6" => KeyCode::F(6),
|
||||
"f7" => KeyCode::F(7),
|
||||
"f8" => KeyCode::F(8),
|
||||
"f9" => KeyCode::F(9),
|
||||
"f10" => KeyCode::F(10),
|
||||
"f11" => KeyCode::F(11),
|
||||
"f12" => KeyCode::F(12),
|
||||
"space" => KeyCode::Char(' '),
|
||||
"hyphen" => KeyCode::Char('-'),
|
||||
"minus" => KeyCode::Char('-'),
|
||||
"tab" => KeyCode::Tab,
|
||||
c if c.len() == 1 => {
|
||||
let mut c = c.chars().next().unwrap();
|
||||
if modifiers.contains(KeyModifiers::SHIFT) {
|
||||
c = c.to_ascii_uppercase();
|
||||
}
|
||||
KeyCode::Char(c)
|
||||
}
|
||||
_ => return Err(format!("Unable to parse {raw}")),
|
||||
};
|
||||
Ok(KeyEvent::new(c, modifiers))
|
||||
}
|
||||
|
||||
pub fn key_event_to_string(key_event: &KeyEvent) -> String {
|
||||
let char;
|
||||
let key_code = match key_event.code {
|
||||
KeyCode::Backspace => "backspace",
|
||||
KeyCode::Enter => "enter",
|
||||
KeyCode::Left => "left",
|
||||
KeyCode::Right => "right",
|
||||
KeyCode::Up => "up",
|
||||
KeyCode::Down => "down",
|
||||
KeyCode::Home => "home",
|
||||
KeyCode::End => "end",
|
||||
KeyCode::PageUp => "pageup",
|
||||
KeyCode::PageDown => "pagedown",
|
||||
KeyCode::Tab => "tab",
|
||||
KeyCode::BackTab => "backtab",
|
||||
KeyCode::Delete => "delete",
|
||||
KeyCode::Insert => "insert",
|
||||
KeyCode::F(c) => {
|
||||
char = format!("f({c})");
|
||||
&char
|
||||
}
|
||||
KeyCode::Char(c) if c == ' ' => "space",
|
||||
KeyCode::Char(c) => {
|
||||
char = c.to_string();
|
||||
&char
|
||||
}
|
||||
KeyCode::Esc => "esc",
|
||||
KeyCode::Null => "",
|
||||
KeyCode::CapsLock => "",
|
||||
KeyCode::Menu => "",
|
||||
KeyCode::ScrollLock => "",
|
||||
KeyCode::Media(_) => "",
|
||||
KeyCode::NumLock => "",
|
||||
KeyCode::PrintScreen => "",
|
||||
KeyCode::Pause => "",
|
||||
KeyCode::KeypadBegin => "",
|
||||
KeyCode::Modifier(_) => "",
|
||||
};
|
||||
|
||||
let mut modifiers = Vec::with_capacity(3);
|
||||
|
||||
if key_event.modifiers.intersects(KeyModifiers::CONTROL) {
|
||||
modifiers.push("ctrl");
|
||||
}
|
||||
|
||||
if key_event.modifiers.intersects(KeyModifiers::SHIFT) {
|
||||
modifiers.push("shift");
|
||||
}
|
||||
|
||||
if key_event.modifiers.intersects(KeyModifiers::ALT) {
|
||||
modifiers.push("alt");
|
||||
}
|
||||
|
||||
let mut key = modifiers.join("-");
|
||||
|
||||
if !key.is_empty() {
|
||||
key.push('-');
|
||||
}
|
||||
key.push_str(key_code);
|
||||
|
||||
key
|
||||
}
|
||||
|
||||
pub fn parse_key_sequence(raw: &str) -> Result<Vec<KeyEvent>, String> {
|
||||
if raw.chars().filter(|c| *c == '>').count() != raw.chars().filter(|c| *c == '<').count() {
|
||||
return Err(format!("Unable to parse `{}`", raw));
|
||||
}
|
||||
let raw = if !raw.contains("><") {
|
||||
let raw = raw.strip_prefix('<').unwrap_or(raw);
|
||||
let raw = raw.strip_prefix('>').unwrap_or(raw);
|
||||
raw
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let sequences = raw
|
||||
.split("><")
|
||||
.map(|seq| {
|
||||
if let Some(s) = seq.strip_prefix('<') {
|
||||
s
|
||||
} else if let Some(s) = seq.strip_suffix('>') {
|
||||
s
|
||||
} else {
|
||||
seq
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
sequences.into_iter().map(parse_key_event).collect()
|
||||
}
|
|
@ -0,0 +1,125 @@
|
|||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::{KeyEvent, MouseEvent};
|
||||
use ratatui::layout::Rect;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use crate::{
|
||||
action::Action,
|
||||
cfg::Config,
|
||||
tui::{Event, Frame},
|
||||
};
|
||||
|
||||
pub mod fps;
|
||||
pub mod home;
|
||||
|
||||
/// `Component` is a trait that represents a visual and interactive element of the user interface.
|
||||
/// Implementors of this trait can be registered with the main application loop and will be able to receive events,
|
||||
/// update state, and be rendered on the screen.
|
||||
pub trait Component {
|
||||
/// Register an action handler that can send actions for processing if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `tx` - An unbounded sender that can send actions.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<()>` - An Ok result or an error.
|
||||
#[allow(unused_variables)]
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Register a configuration handler that provides configuration settings if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `config` - Configuration settings.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<()>` - An Ok result or an error.
|
||||
#[allow(unused_variables)]
|
||||
fn register_config_handler(&mut self, config: Config) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Initialize the component with a specified area if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `area` - Rectangular area to initialize the component within.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<()>` - An Ok result or an error.
|
||||
#[allow(unused_variables)]
|
||||
fn init(&mut self, area: Rect) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Handle incoming events and produce actions if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `event` - An optional event to be processed.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<Option<Action>>` - An action to be processed or none.
|
||||
fn handle_events(&mut self, event: Option<Event>) -> Result<Option<Action>> {
|
||||
let r = match event {
|
||||
Some(Event::Key(key_event)) => self.handle_key_events(key_event)?,
|
||||
Some(Event::Mouse(mouse_event)) => self.handle_mouse_events(mouse_event)?,
|
||||
_ => None,
|
||||
};
|
||||
Ok(r)
|
||||
}
|
||||
/// Handle key events and produce actions if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `key` - A key event to be processed.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<Option<Action>>` - An action to be processed or none.
|
||||
#[allow(unused_variables)]
|
||||
fn handle_key_events(&mut self, key: KeyEvent) -> Result<Option<Action>> {
|
||||
Ok(None)
|
||||
}
|
||||
/// Handle mouse events and produce actions if necessary.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `mouse` - A mouse event to be processed.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<Option<Action>>` - An action to be processed or none.
|
||||
#[allow(unused_variables)]
|
||||
fn handle_mouse_events(&mut self, mouse: MouseEvent) -> Result<Option<Action>> {
|
||||
Ok(None)
|
||||
}
|
||||
/// Update the state of the component based on a received action. (REQUIRED)
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `action` - An action that may modify the state of the component.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<Option<Action>>` - An action to be processed or none.
|
||||
#[allow(unused_variables)]
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
Ok(None)
|
||||
}
|
||||
/// Render the component on the screen. (REQUIRED)
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `f` - A frame used for rendering.
|
||||
/// * `area` - The area in which the component should be drawn.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<()>` - An Ok result or an error.
|
||||
fn draw(&mut self, f: &mut Frame<'_>, area: Rect) -> Result<()>;
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
use std::time::Instant;
|
||||
|
||||
use color_eyre::eyre::Result;
|
||||
use ratatui::{prelude::*, widgets::*};
|
||||
|
||||
use super::Component;
|
||||
use crate::{action::Action, tui::Frame};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FpsCounter {
|
||||
app_start_time: Instant,
|
||||
app_frames: u32,
|
||||
app_fps: f64,
|
||||
|
||||
render_start_time: Instant,
|
||||
render_frames: u32,
|
||||
render_fps: f64,
|
||||
}
|
||||
|
||||
impl Default for FpsCounter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FpsCounter {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
app_start_time: Instant::now(),
|
||||
app_frames: 0,
|
||||
app_fps: 0.0,
|
||||
render_start_time: Instant::now(),
|
||||
render_frames: 0,
|
||||
render_fps: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn app_tick(&mut self) -> Result<()> {
|
||||
self.app_frames += 1;
|
||||
let now = Instant::now();
|
||||
let elapsed = (now - self.app_start_time).as_secs_f64();
|
||||
if elapsed >= 1.0 {
|
||||
self.app_fps = self.app_frames as f64 / elapsed;
|
||||
self.app_start_time = now;
|
||||
self.app_frames = 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render_tick(&mut self) -> Result<()> {
|
||||
self.render_frames += 1;
|
||||
let now = Instant::now();
|
||||
let elapsed = (now - self.render_start_time).as_secs_f64();
|
||||
if elapsed >= 1.0 {
|
||||
self.render_fps = self.render_frames as f64 / elapsed;
|
||||
self.render_start_time = now;
|
||||
self.render_frames = 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for FpsCounter {
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
if let Action::Tick = action {
|
||||
self.app_tick()?
|
||||
};
|
||||
if let Action::Render = action {
|
||||
self.render_tick()?
|
||||
};
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, f: &mut Frame<'_>, rect: Rect) -> Result<()> {
|
||||
let rects = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints(vec![
|
||||
Constraint::Length(1), // row 2
|
||||
Constraint::Min(0),
|
||||
])
|
||||
.horizontal_margin(1)
|
||||
.split(rect);
|
||||
|
||||
let rect = rects[0];
|
||||
|
||||
let s = format!(
|
||||
"{:.2} tps (app) {:.2} fps (render)",
|
||||
self.app_fps, self.render_fps
|
||||
);
|
||||
let block = Block::default().title(block::Title::from(s.dim()).alignment(Alignment::Right));
|
||||
f.render_widget(block, rect);
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
use color_eyre::eyre::Result;
|
||||
use ratatui::{prelude::*, widgets::*};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::{Component, Frame};
|
||||
use crate::{action::Action, symbol};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Home {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
}
|
||||
|
||||
impl Home {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Home {
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
self.command_tx = Some(tx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
match action {
|
||||
Action::Tick => {}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, f: &mut Frame<'_>, area: Rect) -> Result<()> {
|
||||
let main_layout = Layout::new()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(3), Constraint::Min(0)])
|
||||
.horizontal_margin(1)
|
||||
.split(area);
|
||||
|
||||
// Title bar
|
||||
let titlebar = Block::new()
|
||||
.title(Line::from(vec![Span::styled(
|
||||
"DMM ",
|
||||
Style::default().add_modifier(Modifier::BOLD),
|
||||
)]))
|
||||
.borders(Borders::TOP | Borders::BOTTOM)
|
||||
.border_style(Style::new().fg(Color::Yellow));
|
||||
// .title_position(block::Position::Bottom);
|
||||
let titlebar_content_area = titlebar.inner(main_layout[0]);
|
||||
f.render_widget(titlebar, main_layout[0]);
|
||||
|
||||
let titlebar_content = Paragraph::new(Line::from(vec![
|
||||
Span::styled(
|
||||
symbol::PAUSE,
|
||||
Style::default()
|
||||
.fg(Color::DarkGray)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
" ".into(),
|
||||
Span::styled(
|
||||
symbol::PLAY,
|
||||
Style::default()
|
||||
.fg(Color::LightGreen)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
" ".into(),
|
||||
format!("track {n}/{num}: ", n = 5, num = 25).into(),
|
||||
"It's The Most Wonderful Time Of The Year".into(),
|
||||
]))
|
||||
.fg(Color::Gray);
|
||||
f.render_widget(titlebar_content, titlebar_content_area);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
use color_eyre::eyre::Result;
|
||||
use tracing_error::ErrorLayer;
|
||||
use tracing_subscriber::{
|
||||
self, prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, Layer,
|
||||
};
|
||||
|
||||
use crate::project_meta::{get_data_dir, LOG_ENV, LOG_FILE};
|
||||
|
||||
pub fn initialize_logging() -> Result<()> {
|
||||
let directory = get_data_dir();
|
||||
std::fs::create_dir_all(directory.clone())?;
|
||||
let log_path = directory.join(LOG_FILE.clone());
|
||||
let log_file = std::fs::File::create(log_path)?;
|
||||
std::env::set_var(
|
||||
"RUST_LOG",
|
||||
std::env::var("RUST_LOG")
|
||||
.or_else(|_| std::env::var(LOG_ENV.clone()))
|
||||
.unwrap_or_else(|_| format!("{}=info", env!("CARGO_CRATE_NAME"))),
|
||||
);
|
||||
let file_subscriber = tracing_subscriber::fmt::layer()
|
||||
.with_file(true)
|
||||
.with_line_number(true)
|
||||
.with_writer(log_file)
|
||||
.with_target(false)
|
||||
.with_ansi(false)
|
||||
.with_filter(tracing_subscriber::filter::EnvFilter::from_default_env());
|
||||
tracing_subscriber::registry()
|
||||
.with(file_subscriber)
|
||||
.with(ErrorLayer::default())
|
||||
.init();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Similar to the `std::dbg!` macro, but generates `tracing` events rather
|
||||
/// than printing to stdout.
|
||||
///
|
||||
/// By default, the verbosity level for the generated events is `DEBUG`, but
|
||||
/// this can be customized.
|
||||
#[macro_export]
|
||||
macro_rules! trace_dbg {
|
||||
(target: $target:expr, level: $level:expr, $ex:expr) => {{
|
||||
match $ex {
|
||||
value => {
|
||||
tracing::event!(target: $target, $level, ?value, stringify!($ex));
|
||||
value
|
||||
}
|
||||
}
|
||||
}};
|
||||
(level: $level:expr, $ex:expr) => {
|
||||
trace_dbg!(target: module_path!(), level: $level, $ex)
|
||||
};
|
||||
(target: $target:expr, $ex:expr) => {
|
||||
trace_dbg!(target: $target, level: tracing::Level::DEBUG, $ex)
|
||||
};
|
||||
($ex:expr) => {
|
||||
trace_dbg!(level: tracing::Level::DEBUG, $ex)
|
||||
};
|
||||
}
|
27
src/main.rs
27
src/main.rs
|
@ -1,5 +1,5 @@
|
|||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate tracing;
|
||||
|
||||
use std::{
|
||||
env,
|
||||
|
@ -12,8 +12,8 @@ use std::{
|
|||
},
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
use color_eyre::eyre::{anyhow, bail, Result};
|
||||
use cpal::traits::{DeviceTrait, HostTrait};
|
||||
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
|
||||
use heck::ToSnakeCase;
|
||||
|
@ -27,9 +27,19 @@ use uuid::Uuid;
|
|||
|
||||
use crate::schema::DlPlaylist;
|
||||
|
||||
mod action;
|
||||
mod app;
|
||||
mod cfg;
|
||||
mod components;
|
||||
mod log;
|
||||
mod mode;
|
||||
mod output;
|
||||
mod panic;
|
||||
mod player;
|
||||
mod project_meta;
|
||||
mod schema;
|
||||
mod symbol;
|
||||
mod tui;
|
||||
mod waker;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
|
@ -53,20 +63,19 @@ enum Command {
|
|||
#[arg()]
|
||||
playlist: PathBuf,
|
||||
},
|
||||
UI {},
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
log::initialize_logging()?;
|
||||
panic::initialize_panic_handler()?;
|
||||
let args = Args::parse();
|
||||
pretty_env_logger::formatted_builder()
|
||||
.filter_level(log::LevelFilter::Trace)
|
||||
.filter_module("symphonia_core::probe", log::LevelFilter::Warn)
|
||||
.filter_module("async_io", log::LevelFilter::Warn)
|
||||
.filter_module("polling", log::LevelFilter::Warn)
|
||||
.try_init()?;
|
||||
let mut app = app::App::new(1.0, 60.0)?;
|
||||
match args.cmd {
|
||||
Command::Download { file } => download(file)?,
|
||||
Command::Play { playlist } => play(playlist).await?,
|
||||
Command::UI {} => app.run().await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
@ -268,7 +277,7 @@ async fn play(pl_dir: PathBuf) -> Result<()> {
|
|||
_ => warn!("Unknown command {line:?}"),
|
||||
}
|
||||
}
|
||||
anyhow::Ok(())
|
||||
Ok::<(), color_eyre::eyre::Error>(())
|
||||
});
|
||||
player.run().await?;
|
||||
cmd_task.abort();
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Mode {
|
||||
#[default]
|
||||
Home,
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
use anyhow::{bail, Result};
|
||||
use color_eyre::eyre::{bail, Result};
|
||||
use rb::{RbConsumer, RbProducer, SpscRb, RB};
|
||||
use symphonia::core::audio::{AudioBufferRef, RawSample, SampleBuffer, SignalSpec};
|
||||
use symphonia::core::conv::{ConvertibleSample, IntoSample};
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
use color_eyre::eyre::Result;
|
||||
use tracing::error;
|
||||
|
||||
pub fn initialize_panic_handler() -> Result<()> {
|
||||
let (panic_hook, eyre_hook) = color_eyre::config::HookBuilder::default()
|
||||
.panic_section(format!(
|
||||
"This is a bug. Consider reporting it at {}",
|
||||
env!("CARGO_PKG_REPOSITORY")
|
||||
))
|
||||
.capture_span_trace_by_default(false)
|
||||
.display_location_section(false)
|
||||
.display_env_section(false)
|
||||
.into_hooks();
|
||||
eyre_hook.install()?;
|
||||
std::panic::set_hook(Box::new(move |panic_info| {
|
||||
if let Ok(mut t) = crate::tui::Tui::new() {
|
||||
if let Err(r) = t.exit() {
|
||||
error!("Unable to exit Terminal: {:?}", r);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
use human_panic::{handle_dump, print_msg, Metadata};
|
||||
let meta = Metadata {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
name: env!("CARGO_PKG_NAME").into(),
|
||||
authors: env!("CARGO_PKG_AUTHORS").replace(':', ", ").into(),
|
||||
homepage: env!("CARGO_PKG_HOMEPAGE").into(),
|
||||
};
|
||||
|
||||
let file_path = handle_dump(&meta, panic_info);
|
||||
// prints human-panic message
|
||||
print_msg(file_path, &meta)
|
||||
.expect("human-panic: printing error message to console failed");
|
||||
eprintln!("{}", panic_hook.panic_report(panic_info)); // prints color-eyre stack trace to stderr
|
||||
}
|
||||
let msg = format!("{}", panic_hook.panic_report(panic_info));
|
||||
log::error!("Error: {}", strip_ansi_escapes::strip_str(msg));
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
// Better Panic stacktrace that is only enabled when debugging.
|
||||
better_panic::Settings::auto()
|
||||
.most_recent_first(false)
|
||||
.lineno_suffix(true)
|
||||
.verbosity(better_panic::Verbosity::Full)
|
||||
.create_panic_handler()(panic_info);
|
||||
}
|
||||
|
||||
std::process::exit(libc::EXIT_FAILURE);
|
||||
}));
|
||||
Ok(())
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
use anyhow::{bail, Result};
|
||||
use color_eyre::eyre::{bail, Result};
|
||||
use cpal::{Device, SupportedStreamConfig};
|
||||
use flume::{Receiver, Sender};
|
||||
use symphonia::core::{
|
||||
|
|
|
@ -0,0 +1,66 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use directories::ProjectDirs;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
pub static GIT_COMMIT_HASH: &'static str = env!("_GIT_INFO");
|
||||
|
||||
lazy_static! {
|
||||
pub static ref PROJECT_NAME: String = env!("CARGO_CRATE_NAME").to_uppercase().to_string();
|
||||
pub static ref DATA_FOLDER: Option<PathBuf> =
|
||||
std::env::var(format!("{}_DATA", PROJECT_NAME.clone()))
|
||||
.ok()
|
||||
.map(PathBuf::from);
|
||||
pub static ref CONFIG_FOLDER: Option<PathBuf> =
|
||||
std::env::var(format!("{}_CONFIG", PROJECT_NAME.clone()))
|
||||
.ok()
|
||||
.map(PathBuf::from);
|
||||
pub static ref LOG_ENV: String = format!("{}_LOGLEVEL", PROJECT_NAME.clone());
|
||||
pub static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
|
||||
}
|
||||
|
||||
fn project_directory() -> Option<ProjectDirs> {
|
||||
ProjectDirs::from("io", "fawkes", env!("CARGO_PKG_NAME"))
|
||||
}
|
||||
|
||||
pub fn get_data_dir() -> PathBuf {
|
||||
let directory = if let Some(s) = DATA_FOLDER.clone() {
|
||||
s
|
||||
} else if let Some(proj_dirs) = project_directory() {
|
||||
proj_dirs.data_local_dir().to_path_buf()
|
||||
} else {
|
||||
PathBuf::from(".").join(".data")
|
||||
};
|
||||
directory
|
||||
}
|
||||
|
||||
pub fn get_config_dir() -> PathBuf {
|
||||
let directory = if let Some(s) = CONFIG_FOLDER.clone() {
|
||||
s
|
||||
} else if let Some(proj_dirs) = project_directory() {
|
||||
proj_dirs.config_local_dir().to_path_buf()
|
||||
} else {
|
||||
PathBuf::from(".").join(".config")
|
||||
};
|
||||
directory
|
||||
}
|
||||
|
||||
pub fn version() -> String {
|
||||
let author = clap::crate_authors!();
|
||||
|
||||
let commit_hash = GIT_COMMIT_HASH;
|
||||
|
||||
// let current_exe_path = PathBuf::from(clap::crate_name!()).display().to_string();
|
||||
let config_dir_path = get_config_dir().display().to_string();
|
||||
let data_dir_path = get_data_dir().display().to_string();
|
||||
|
||||
format!(
|
||||
"\
|
||||
{commit_hash}
|
||||
|
||||
Authors: {author}
|
||||
|
||||
Config directory: {config_dir_path}
|
||||
Data directory: {data_dir_path}"
|
||||
)
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
use std::{collections::HashMap, path::Path, process::Command};
|
||||
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use color_eyre::eyre::{anyhow, bail, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
@ -203,6 +203,7 @@ pub struct DlTrack {
|
|||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct Playlist {
|
||||
pub name: String,
|
||||
pub import: Vec<Import>,
|
||||
pub sources: Vec<Source>,
|
||||
pub tracks: Vec<Track>,
|
||||
}
|
||||
|
@ -213,6 +214,11 @@ impl Playlist {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub enum Import {
|
||||
Source(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
pub struct Source {
|
||||
pub name: String,
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
macro_rules! sym {
|
||||
($id:ident, $val:literal) => {
|
||||
pub const $id: &'static str = $val;
|
||||
};
|
||||
}
|
||||
|
||||
sym!(PAUSE, "");
|
||||
sym!(PLAY, "");
|
|
@ -0,0 +1,249 @@
|
|||
use std::{
|
||||
ops::{Deref, DerefMut},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use color_eyre::eyre::Result;
|
||||
use crossterm::{
|
||||
cursor,
|
||||
event::{
|
||||
DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
|
||||
Event as CrosstermEvent, KeyEvent, KeyEventKind, MouseEvent,
|
||||
},
|
||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen},
|
||||
};
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use ratatui::backend::CrosstermBackend as Backend;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::{
|
||||
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
|
||||
task::JoinHandle,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub type IO = std::io::Stdout;
|
||||
pub fn io() -> IO {
|
||||
std::io::stdout()
|
||||
}
|
||||
pub type Frame<'a> = ratatui::Frame<'a>;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum Event {
|
||||
Init,
|
||||
Quit,
|
||||
Error,
|
||||
Closed,
|
||||
Tick,
|
||||
Render,
|
||||
FocusGained,
|
||||
FocusLost,
|
||||
Paste(String),
|
||||
Key(KeyEvent),
|
||||
Mouse(MouseEvent),
|
||||
Resize(u16, u16),
|
||||
}
|
||||
|
||||
pub struct Tui {
|
||||
pub terminal: ratatui::Terminal<Backend<IO>>,
|
||||
pub task: JoinHandle<()>,
|
||||
pub cancellation_token: CancellationToken,
|
||||
pub event_rx: UnboundedReceiver<Event>,
|
||||
pub event_tx: UnboundedSender<Event>,
|
||||
pub frame_rate: f64,
|
||||
pub tick_rate: f64,
|
||||
pub mouse: bool,
|
||||
pub paste: bool,
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
pub fn new() -> Result<Self> {
|
||||
let tick_rate = 4.0;
|
||||
let frame_rate = 60.0;
|
||||
let terminal = ratatui::Terminal::new(Backend::new(io()))?;
|
||||
let (event_tx, event_rx) = mpsc::unbounded_channel();
|
||||
let cancellation_token = CancellationToken::new();
|
||||
let task = tokio::spawn(async {});
|
||||
let mouse = false;
|
||||
let paste = false;
|
||||
Ok(Self {
|
||||
terminal,
|
||||
task,
|
||||
cancellation_token,
|
||||
event_rx,
|
||||
event_tx,
|
||||
frame_rate,
|
||||
tick_rate,
|
||||
mouse,
|
||||
paste,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn tick_rate(mut self, tick_rate: f64) -> Self {
|
||||
self.tick_rate = tick_rate;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn frame_rate(mut self, frame_rate: f64) -> Self {
|
||||
self.frame_rate = frame_rate;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn mouse(mut self, mouse: bool) -> Self {
|
||||
self.mouse = mouse;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn paste(mut self, paste: bool) -> Self {
|
||||
self.paste = paste;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
let tick_delay = std::time::Duration::from_secs_f64(1.0 / self.tick_rate);
|
||||
let render_delay = std::time::Duration::from_secs_f64(1.0 / self.frame_rate);
|
||||
self.cancel();
|
||||
self.cancellation_token = CancellationToken::new();
|
||||
let _cancellation_token = self.cancellation_token.clone();
|
||||
let _event_tx = self.event_tx.clone();
|
||||
self.task = tokio::spawn(async move {
|
||||
let mut reader = crossterm::event::EventStream::new();
|
||||
let mut tick_interval = tokio::time::interval(tick_delay);
|
||||
let mut render_interval = tokio::time::interval(render_delay);
|
||||
_event_tx.send(Event::Init).unwrap();
|
||||
loop {
|
||||
let tick_delay = tick_interval.tick();
|
||||
let render_delay = render_interval.tick();
|
||||
let crossterm_event = reader.next().fuse();
|
||||
tokio::select! {
|
||||
_ = _cancellation_token.cancelled() => {
|
||||
break;
|
||||
}
|
||||
maybe_event = crossterm_event => {
|
||||
match maybe_event {
|
||||
Some(Ok(evt)) => {
|
||||
match evt {
|
||||
CrosstermEvent::Key(key) => {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
_event_tx.send(Event::Key(key)).unwrap();
|
||||
}
|
||||
},
|
||||
CrosstermEvent::Mouse(mouse) => {
|
||||
_event_tx.send(Event::Mouse(mouse)).unwrap();
|
||||
},
|
||||
CrosstermEvent::Resize(x, y) => {
|
||||
_event_tx.send(Event::Resize(x, y)).unwrap();
|
||||
},
|
||||
CrosstermEvent::FocusLost => {
|
||||
_event_tx.send(Event::FocusLost).unwrap();
|
||||
},
|
||||
CrosstermEvent::FocusGained => {
|
||||
_event_tx.send(Event::FocusGained).unwrap();
|
||||
},
|
||||
CrosstermEvent::Paste(s) => {
|
||||
_event_tx.send(Event::Paste(s)).unwrap();
|
||||
},
|
||||
}
|
||||
}
|
||||
Some(Err(_)) => {
|
||||
_event_tx.send(Event::Error).unwrap();
|
||||
}
|
||||
None => {},
|
||||
}
|
||||
},
|
||||
_ = tick_delay => {
|
||||
_event_tx.send(Event::Tick).unwrap();
|
||||
},
|
||||
_ = render_delay => {
|
||||
_event_tx.send(Event::Render).unwrap();
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&self) -> Result<()> {
|
||||
self.cancel();
|
||||
let mut counter = 0;
|
||||
while !self.task.is_finished() {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
counter += 1;
|
||||
if counter > 50 {
|
||||
self.task.abort();
|
||||
}
|
||||
if counter > 100 {
|
||||
log::error!("Failed to abort task in 100 milliseconds for unknown reason");
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn enter(&mut self) -> Result<()> {
|
||||
crossterm::terminal::enable_raw_mode()?;
|
||||
crossterm::execute!(io(), EnterAlternateScreen, cursor::Hide)?;
|
||||
if self.mouse {
|
||||
crossterm::execute!(io(), EnableMouseCapture)?;
|
||||
}
|
||||
if self.paste {
|
||||
crossterm::execute!(io(), EnableBracketedPaste)?;
|
||||
}
|
||||
self.start();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn exit(&mut self) -> Result<()> {
|
||||
self.stop()?;
|
||||
if crossterm::terminal::is_raw_mode_enabled()? {
|
||||
self.flush()?;
|
||||
if self.paste {
|
||||
crossterm::execute!(io(), DisableBracketedPaste)?;
|
||||
}
|
||||
if self.mouse {
|
||||
crossterm::execute!(io(), DisableMouseCapture)?;
|
||||
}
|
||||
crossterm::execute!(io(), LeaveAlternateScreen, cursor::Show)?;
|
||||
crossterm::terminal::disable_raw_mode()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
self.cancellation_token.cancel();
|
||||
}
|
||||
|
||||
pub fn suspend(&mut self) -> Result<()> {
|
||||
self.exit()?;
|
||||
#[cfg(not(windows))]
|
||||
signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn resume(&mut self) -> Result<()> {
|
||||
self.enter()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn next(&mut self) -> Option<Event> {
|
||||
self.event_rx.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Tui {
|
||||
type Target = ratatui::Terminal<Backend<IO>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.terminal
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for Tui {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.terminal
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tui {
|
||||
fn drop(&mut self) {
|
||||
self.exit().unwrap();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue