From 01932dca007bb6d039fd72ab32cbc9d800d8da7a Mon Sep 17 00:00:00 2001 From: Nick Dowsett Date: Thu, 30 Nov 2023 23:39:52 +0800 Subject: [PATCH] Tidied up compiler warnings --- src/app.rs | 20 +++-------------- src/app/component.rs | 1 - src/app/component/actionhandler.rs | 4 ++-- src/app/component/contextpane.rs | 18 --------------- src/app/musiccache.rs | 21 ++++++++++------- src/app/server.rs | 7 +++--- src/app/server/api.rs | 36 +++++++++++++++++++++--------- src/app/server/player.rs | 22 ++++-------------- src/app/structures.rs | 10 +++------ src/app/taskmanager.rs | 32 ++------------------------ src/app/ui.rs | 24 ++------------------ src/app/ui/browser.rs | 8 ++++--- src/app/ui/browser/artistalbums.rs | 5 ++--- src/app/ui/draw.rs | 3 +-- src/app/ui/footer.rs | 6 +---- src/app/ui/header.rs | 2 +- src/app/ui/logger.rs | 28 +++++++++++------------ src/app/ui/playlist.rs | 11 +-------- src/app/view.rs | 13 +++++------ src/config.rs | 6 ++--- src/error.rs | 9 ++------ src/main.rs | 19 ++++++---------- 22 files changed, 99 insertions(+), 206 deletions(-) delete mode 100644 src/app/component/contextpane.rs diff --git a/src/app.rs b/src/app.rs index 602e72d7..cf3f176f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3,9 +3,8 @@ use self::taskmanager::{AppRequest, TaskManager}; use self::ui::WindowContext; use super::appevent::{AppEvent, EventHandler}; use super::Result; -use crate::core::send_or_error; use crate::error::Error; -use crate::{get_data_dir, RuntimeInfo}; +use crate::RuntimeInfo; use crossterm::{ event::{DisableMouseCapture, EnableMouseCapture}, execute, @@ -30,7 +29,7 @@ mod view; const CALLBACK_CHANNEL_SIZE: usize = 64; const EVENT_CHANNEL_SIZE: usize = 256; -const LOG_FILE_NAME: &str = "debug.log"; +const _LOG_FILE_NAME: &str = "debug.log"; pub struct Youtui { status: AppStatus, @@ -56,8 +55,6 @@ pub enum AppCallback { GetProgress(ListSongID), Quit, ChangeContext(WindowContext), - Next, - Prev, // Perhaps shiould not be here. HandleApiError(Error), IncreaseVolume(i8), @@ -69,7 +66,6 @@ pub enum AppCallback { PlaySong(Arc>, ListSongID), PausePlay(ListSongID), Stop(ListSongID), - StopAll, } impl Youtui { @@ -126,8 +122,6 @@ impl Youtui { self.handle_next_event().await; // Process any callbacks in the queue. self.process_callbacks().await; - // If any requests are in the queue, queue up the tasks on the server. - self.queue_server_tasks().await; // Get the state update events from the task manager and apply them to the window state. self.synchronize_state().await; // Write to terminal, using UI state as the input @@ -164,9 +158,6 @@ impl Youtui { None => panic!("Channel closed"), } } - async fn queue_server_tasks(&mut self) { - self.task_manager.process_requests().await; - } pub async fn process_callbacks(&mut self) { while let Ok(msg) = self.callback_rx.try_recv() { match msg { @@ -183,11 +174,9 @@ impl Youtui { AppCallback::ChangeContext(context) => { self.window_state.handle_change_context(context) } - AppCallback::Next => self.window_state.handle_next().await, - AppCallback::Prev => self.window_state.handle_previous().await, AppCallback::IncreaseVolume(i) => { // Update state first for immediate visual feedback - self.window_state.increase_volume(i).await; + self.window_state.increase_volume(i); self.task_manager .send_request(AppRequest::IncreaseVolume(i)) .await; @@ -229,9 +218,6 @@ impl Youtui { AppCallback::Stop(id) => { self.task_manager.send_request(AppRequest::Stop(id)).await; } - AppCallback::StopAll => { - self.task_manager.send_request(AppRequest::StopAll).await; - } AppCallback::GetVolume => { self.task_manager.send_request(AppRequest::GetVolume).await; } diff --git a/src/app/component.rs b/src/app/component.rs index 6067f2cb..dc7c6492 100644 --- a/src/app/component.rs +++ b/src/app/component.rs @@ -1,3 +1,2 @@ pub mod actionhandler; -pub mod contextpane; pub mod messagehandler; diff --git a/src/app/component/actionhandler.rs b/src/app/component/actionhandler.rs index 805a779d..639a753d 100644 --- a/src/app/component/actionhandler.rs +++ b/src/app/component/actionhandler.rs @@ -72,7 +72,7 @@ impl Mode { ) -> Box, Cow)> + 'a> { Box::new(self.key_binds.iter().map(|bind| bind.as_readable_short())) } - pub fn as_readable_iter<'a>( + pub fn _as_readable_iter<'a>( &'a self, ) -> Box, Cow, Cow)> + 'a> { Box::new(self.key_binds.iter().map(|bind| bind.as_readable())) @@ -262,7 +262,7 @@ pub trait ActionProcessor: ActionHandler + KeyHandler { pub trait MouseHandler { /// Not implemented yet! - fn handle_mouse_event(&mut self, mouse_event: MouseEvent) { + fn handle_mouse_event(&mut self, _mouse_event: MouseEvent) { unimplemented!() } } diff --git a/src/app/component/contextpane.rs b/src/app/component/contextpane.rs deleted file mode 100644 index 8c0e8a78..00000000 --- a/src/app/component/contextpane.rs +++ /dev/null @@ -1,18 +0,0 @@ -use super::{ - super::view::Drawable, - actionhandler::{Action, ActionProcessor, KeyRouter}, -}; - -enum Direction { - Up, - Down, - Left, - Right, -} - -// A window context containing multiple panes for which input should be easily swapped. -trait MultiPane { - fn select(&mut self, dir: Direction); - // For example, tabcycling - fn select_next(&mut self); -} diff --git a/src/app/musiccache.rs b/src/app/musiccache.rs index a287d0c7..e946195a 100644 --- a/src/app/musiccache.rs +++ b/src/app/musiccache.rs @@ -1,23 +1,28 @@ +use crate::Result; use std::{path::PathBuf, sync::Arc}; -const MUSIC_DIR: &str = "music/"; +const _MUSIC_DIR: &str = "music/"; -pub struct MusicCache { +pub struct _MusicCache { songs: Vec, } -impl MusicCache { - fn cache_song(&mut self, song: Arc>, path: PathBuf) { +impl _MusicCache { + fn _cache_song(&mut self, song: Arc>, path: PathBuf) -> Result<()> { let mut p = PathBuf::new(); - p.push(MUSIC_DIR); + p.push(_MUSIC_DIR); p.push(&path); self.songs.push(path); - std::fs::write(p, &*song); + std::fs::write(p, &*song)?; + Ok(()) } - fn retrieve_song(&self, path: PathBuf) -> std::result::Result>, std::io::Error> { + fn _retrieve_song( + &self, + path: PathBuf, + ) -> std::result::Result>, std::io::Error> { if self.songs.contains(&path) { let mut p = PathBuf::new(); - p.push(MUSIC_DIR); + p.push(_MUSIC_DIR); p.push(&path); return std::fs::read(p).map(|v| Some(v)); } diff --git a/src/app/server.rs b/src/app/server.rs index 10386b73..bb03a235 100644 --- a/src/app/server.rs +++ b/src/app/server.rs @@ -68,17 +68,18 @@ impl Server { _response_tx: response_tx, }) } - pub async fn run(&mut self) { + pub async fn run(&mut self) -> Result<()> { // Could be a while let // Consider parallelism. while let Some(request) = self.request_rx.recv().await { match request { // TODO: Error handling for the queues. - Request::Api(rx) => self.api.handle_request(rx).await, + Request::Api(rx) => self.api.handle_request(rx).await?, Request::Downloader(rx) => self.downloader.handle_request(rx).await, - Request::Player(rx) => self.player.handle_request(rx).await, + Request::Player(rx) => self.player.handle_request(rx).await?, } } + Ok(()) } } // Consider using this instead of macro above. diff --git a/src/app/server/api.rs b/src/app/server/api.rs index 003fc800..8ea3f85e 100644 --- a/src/app/server/api.rs +++ b/src/app/server/api.rs @@ -78,7 +78,7 @@ impl Api { Err(Error::UnknownAPIError) } } - pub async fn handle_request(&mut self, request: Request) { + pub async fn handle_request(&mut self, request: Request) -> Result<()> { match request { Request::NewArtistSearch(a, task) => self.handle_new_artist_search(a, task).await, Request::GetSearchSuggestions(text, task) => { @@ -89,7 +89,11 @@ impl Api { } } } - async fn handle_get_search_suggestions(&mut self, text: String, task: KillableTask) { + async fn handle_get_search_suggestions( + &mut self, + text: String, + task: KillableTask, + ) -> Result<()> { let KillableTask { id, kill_rx } = task; // Give the task a clone of the API. Not ideal but works. // The largest part of the API is Reqwest::Client which contains an Arc @@ -102,8 +106,11 @@ impl Api { Err(e) => { error!("Error {e} connecting to API"); tx.send(crate::app::server::Response::Api(Response::ApiError(e))) - .await; - return; + .await?; + // Rough guard against the case of sending an unkown api error. + // TODO: Better handling for this edge case. + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + return Err(Error::UnknownAPIError); } } .clone(); @@ -129,9 +136,10 @@ impl Api { kill_rx, ) .await; + Ok(()) } - async fn handle_new_artist_search(&mut self, artist: String, task: KillableTask) { + async fn handle_new_artist_search(&mut self, artist: String, task: KillableTask) -> Result<()> { let KillableTask { id, kill_rx } = task; // Give the task a clone of the API. Not ideal but works. // The largest part of the API is Reqwest::Client which contains an Arc @@ -144,8 +152,11 @@ impl Api { Err(e) => { error!("Error {e} connecting to API"); tx.send(crate::app::server::Response::Api(Response::ApiError(e))) - .await; - return; + .await?; + // Rough guard against the case of sending an unkown api error. + // TODO: Better handling for this edge case. + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + return Err(Error::UnknownAPIError); } } .clone(); @@ -189,12 +200,13 @@ impl Api { kill_rx, ) .await; + Ok(()) } async fn handle_search_selected_artist( &mut self, browse_id: ChannelID<'static>, task: KillableTask, - ) { + ) -> Result<()> { let KillableTask { id, kill_rx } = task; // See above note let tx = self.response_tx.clone(); @@ -203,8 +215,11 @@ impl Api { Err(e) => { error!("Error {e} connecting to API"); tx.send(crate::app::server::Response::Api(Response::ApiError(e))) - .await; - return; + .await?; + // Rough guard against the case of sending an unkown api error. + // TODO: Better handling for this edge case. + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + return Err(Error::UnknownAPIError); } } .clone(); @@ -357,5 +372,6 @@ impl Api { kill_rx, ) .await; + Ok(()) } } diff --git a/src/app/server/player.rs b/src/app/server/player.rs index 12719cc0..d5318b61 100644 --- a/src/app/server/player.rs +++ b/src/app/server/player.rs @@ -28,7 +28,6 @@ pub enum Request { PlaySong(Arc>, ListSongID, TaskID), GetPlayProgress(ListSongID, TaskID), // Should give ID? Stop(ListSongID, TaskID), - StopAll(TaskID), PausePlay(ListSongID, TaskID), } @@ -38,7 +37,6 @@ pub enum Response { Paused(ListSongID, TaskID), Playing(ListSongID, TaskID), Stopped(ListSongID, TaskID), - StoppedAll(TaskID), ProgressUpdate(f64, ListSongID, TaskID), VolumeUpdate(Percentage, TaskID), // Should be Percentage } @@ -61,8 +59,8 @@ impl PlayerManager { _rodio: rodio, }) } - pub async fn handle_request(&self, request: Request) { - self.msg_tx.send(request).await; + pub async fn handle_request(&self, request: Request) -> Result<()> { + Ok(self.msg_tx.send(request).await?) } } @@ -78,7 +76,7 @@ pub fn spawn_rodio_thread( let _gag = match gag::Gag::stderr() { Ok(gag) => gag, Err(e) => { - warn!("Error gagging stderr output"); + warn!("Error <{e}> gagging stderr output"); return; } }; @@ -132,18 +130,6 @@ pub fn spawn_rodio_thread( ); thinks_is_playing = false; } - // TODO: Refactor with above. - Request::StopAll(id) => { - info!("Got message to stop playing all"); - if !sink.empty() { - sink.stop() - } - blocking_send_or_error( - &response_tx, - super::Response::Player(Response::StoppedAll(id)), - ); - thinks_is_playing = false; - } Request::PausePlay(song_id, id) => { info!("Got message to pause / play {:?}", id); if cur_song_id != song_id { @@ -215,7 +201,7 @@ pub fn spawn_rodio_thread( last_tick_time = std::time::Instant::now(); std::thread::sleep(EVENT_POLL_INTERVAL); if !sink.empty() && !sink.is_paused() { - std::thread::sleep(EVENT_POLL_INTERVAL.saturating_sub(EVENT_POLL_INTERVAL)); + std::thread::sleep(PROGRESS_UPDATE_INTERVAL.saturating_sub(EVENT_POLL_INTERVAL)); let passed = std::time::Instant::now() - last_tick_time; cur_song_elapsed = cur_song_elapsed + passed; } diff --git a/src/app/structures.rs b/src/app/structures.rs index 61b3d437..174624a3 100644 --- a/src/app/structures.rs +++ b/src/app/structures.rs @@ -1,8 +1,6 @@ -use ratatui::widgets::{ListState, ScrollbarState, TableState}; use std::borrow::Cow; use std::rc::Rc; use std::sync::Arc; -use tracing::{info, warn}; use ytmapi_rs::common::youtuberesult::{ResultCore, YoutubeResult}; use ytmapi_rs::parse::SongResult; @@ -55,7 +53,6 @@ pub enum DownloadStatus { pub enum PlayState { NotPlaying, Playing(ListSongID), - Transitioning, Paused(ListSongID), // May be the same as NotPlaying? Stopped, @@ -68,7 +65,6 @@ impl PlayState { PlayState::Buffering(_) => '', PlayState::NotPlaying => '', PlayState::Playing(_) => '', - PlayState::Transitioning => '', PlayState::Paused(_) => '', PlayState::Stopped => '', } @@ -88,16 +84,16 @@ impl DownloadStatus { } impl ListSong { - fn set_year(&mut self, year: Rc) { + fn _set_year(&mut self, year: Rc) { self.year = year; } - fn set_album(&mut self, album: Rc) { + fn _set_album(&mut self, album: Rc) { self.album = album; } pub fn get_year(&self) -> &String { &self.year } - fn set_artists(&mut self, artists: Vec>) { + fn _set_artists(&mut self, artists: Vec>) { self.artists = artists; } pub fn get_artists(&self) -> &Vec> { diff --git a/src/app/taskmanager.rs b/src/app/taskmanager.rs index e1725aeb..b6c5539d 100644 --- a/src/app/taskmanager.rs +++ b/src/app/taskmanager.rs @@ -1,7 +1,6 @@ use super::server::{api, downloader, player}; use super::structures::ListSongID; use super::ui::YoutuiWindow; -use super::Youtui; use crate::app::server::KillRequest; use crate::app::server::{self, KillableTask}; use crate::config::ApiKey; @@ -21,11 +20,9 @@ pub struct TaskManager { _server_handle: tokio::task::JoinHandle>, server_request_tx: mpsc::Sender, server_response_rx: mpsc::Receiver, - request_tx: mpsc::Sender, - request_rx: mpsc::Receiver, } -enum TaskType { +enum _TaskType { Killable(KillableTask), // A task that can be called by the caller. Once killed, the caller will stop receiving messages to prevent race conditions. Blockable(TaskID), // A task that the caller can block from receiving further messages, but cannot be killed. Completable(TaskID), // A task that cannot be killed or blocked. Will always run until completion. @@ -52,7 +49,6 @@ pub enum AppRequest { PlaySong(Arc>, ListSongID), GetPlayProgress(ListSongID), Stop(ListSongID), - StopAll, PausePlay(ListSongID), } @@ -68,7 +64,6 @@ impl AppRequest { AppRequest::PlaySong(..) => RequestCategory::PlayPauseStop, AppRequest::GetPlayProgress(_) => RequestCategory::ProgressUpdate, AppRequest::Stop(_) => RequestCategory::PlayPauseStop, - AppRequest::StopAll => RequestCategory::PlayPauseStop, AppRequest::PausePlay(_) => RequestCategory::PlayPauseStop, } } @@ -92,10 +87,9 @@ impl TaskManager { pub fn new(api_key: ApiKey) -> Self { let (server_request_tx, server_request_rx) = mpsc::channel(MESSAGE_QUEUE_LENGTH); let (server_response_tx, server_response_rx) = mpsc::channel(MESSAGE_QUEUE_LENGTH); - let (request_tx, request_rx) = mpsc::channel(MESSAGE_QUEUE_LENGTH); let _server_handle = tokio::spawn(async { let mut a = server::Server::new(api_key, server_response_tx, server_request_rx)?; - a.run().await; + a.run().await?; Ok(()) }); Self { @@ -104,13 +98,6 @@ impl TaskManager { _server_handle, server_request_tx, server_response_rx, - request_tx, - request_rx, - } - } - pub async fn process_requests(&mut self) { - while let Ok(msg) = self.request_rx.try_recv() { - self.send_request(msg).await; } } pub async fn send_request(&mut self, request: AppRequest) { @@ -131,7 +118,6 @@ impl TaskManager { AppRequest::PlaySong(song, song_id) => self.spawn_play_song(song, song_id, id).await, AppRequest::GetPlayProgress(song_id) => self.spawn_get_play_progress(song_id, id).await, AppRequest::Stop(song_id) => self.spawn_stop(song_id, id).await, - AppRequest::StopAll => self.spawn_stop_all(id).await, AppRequest::PausePlay(song_id) => self.spawn_pause_play(song_id, id).await, }; } @@ -240,14 +226,6 @@ impl TaskManager { ) .await } - pub async fn spawn_stop_all(&mut self, id: TaskID) { - self.block_all_task_type_except_id(RequestCategory::PlayPauseStop, id); - send_or_error( - &self.server_request_tx, - server::Request::Player(server::player::Request::StopAll(id)), - ) - .await - } pub async fn spawn_pause_play(&mut self, song_id: ListSongID, id: TaskID) { self.block_all_task_type_except_id(RequestCategory::PlayPauseStop, id); send_or_error( @@ -431,12 +409,6 @@ impl TaskManager { } ui_state.handle_set_to_stopped(song_id).await; } - player::Response::StoppedAll(id) => { - if !self.is_task_valid(id) { - return; - } - ui_state.handle_set_all_to_stopped().await; - } player::Response::ProgressUpdate(perc, song_id, id) => { if !self.is_task_valid(id) { return; diff --git a/src/app/ui.rs b/src/app/ui.rs index a87a7387..00349879 100644 --- a/src/app/ui.rs +++ b/src/app/ui.rs @@ -5,8 +5,6 @@ mod header; mod logger; mod playlist; -use self::browser::BrowserAction; -use self::playlist::PlaylistAction; use self::{browser::Browser, logger::Logger, playlist::Playlist}; use super::component::actionhandler::{ Action, ActionHandler, ActionProcessor, DisplayableKeyRouter, KeyHandleOutcome, KeyHandler, @@ -24,7 +22,6 @@ use tokio::sync::mpsc; use ytmapi_rs::common::SearchSuggestion; use ytmapi_rs::parse::{SearchResultArtist, SongResult}; -const PAGE_KEY_SCROLL_AMOUNT: isize = 10; const VOL_TICK: i8 = 5; // Which app level keyboard shortcuts function. @@ -47,8 +44,6 @@ pub enum UIAction { Pause, StepVolUp, StepVolDown, - Browser(BrowserAction), - Playlist(PlaylistAction), ToggleHelp, ViewLogs, } @@ -150,8 +145,6 @@ impl ActionHandler for YoutuiWindow { UIAction::Pause => self.playlist.pauseplay().await, UIAction::StepVolUp => self.handle_increase_volume(VOL_TICK).await, UIAction::StepVolDown => self.handle_increase_volume(-VOL_TICK).await, - UIAction::Browser(b) => self.browser.handle_action(b).await, - UIAction::Playlist(b) => self.playlist.handle_action(b).await, UIAction::Quit => send_or_error(&self.callback_tx, AppCallback::Quit).await, UIAction::ToggleHelp => self.help_shown = !self.help_shown, UIAction::ViewLogs => self.handle_change_context(WindowContext::Logs), @@ -165,8 +158,6 @@ impl Action for UIAction { UIAction::Next | UIAction::Prev | UIAction::StepVolUp | UIAction::StepVolDown => { "Global".into() } - UIAction::Browser(a) => a.context(), - UIAction::Playlist(a) => a.context(), UIAction::Quit => "Global".into(), UIAction::ToggleHelp => "Global".into(), UIAction::ViewLogs => "Global".into(), @@ -183,8 +174,6 @@ impl Action for UIAction { UIAction::StepVolDown => "Vol Down".into(), UIAction::ToggleHelp => "Toggle Help".into(), UIAction::ViewLogs => "View Logs".into(), - UIAction::Browser(a) => a.describe(), - UIAction::Playlist(a) => a.describe(), } } } @@ -286,18 +275,9 @@ impl YoutuiWindow { pub async fn handle_set_to_stopped(&mut self, id: ListSongID) { self.playlist.handle_set_to_stopped(id) } - pub async fn handle_set_all_to_stopped(&mut self) { - self.playlist.handle_set_all_to_stopped() - } pub fn handle_set_volume(&mut self, p: Percentage) { self.playlist.handle_set_volume(p) } - pub async fn handle_next(&mut self) { - self.playlist.handle_next().await; - } - pub async fn handle_previous(&mut self) { - self.playlist.handle_previous().await; - } pub fn handle_set_song_play_progress(&mut self, f: f64, id: ListSongID) { self.playlist.handle_set_song_play_progress(f, id); } @@ -376,14 +356,14 @@ impl YoutuiWindow { } /// Visually increment the volume, note, does not actually change the volume. - pub async fn increase_volume(&mut self, inc: i8) { + pub fn increase_volume(&mut self, inc: i8) { self.playlist.increase_volume(inc); } pub fn handle_change_context(&mut self, new_context: WindowContext) { std::mem::swap(&mut self.context, &mut self.prev_context); self.context = new_context; } - fn revert_context(&mut self) { + fn _revert_context(&mut self) { std::mem::swap(&mut self.context, &mut self.prev_context); } // TODO: also return Mode description. diff --git a/src/app/ui/browser.rs b/src/app/ui/browser.rs index 4717f174..b34a346f 100644 --- a/src/app/ui/browser.rs +++ b/src/app/ui/browser.rs @@ -8,7 +8,7 @@ use crate::app::{ Action, ActionHandler, ActionProcessor, KeyHandler, KeyRouter, Suggestable, TextHandler, }, structures::ListStatus, - view::{DrawableMut, ListView, Scrollable}, + view::{DrawableMut, Scrollable}, }; use crate::{app::component::actionhandler::Keybind, core::send_or_error}; use crossterm::event::KeyCode; @@ -20,6 +20,8 @@ use ytmapi_rs::{ parse::{SearchResultArtist, SongResult}, }; +const PAGE_KEY_LINES: isize = 10; + mod artistalbums; mod draw; @@ -197,8 +199,8 @@ impl ActionHandler for Browser { ArtistSongsAction::AddSongsToPlaylist => self.add_songs_to_playlist().await, ArtistSongsAction::Up => self.album_songs_list.increment_list(-1), ArtistSongsAction::Down => self.album_songs_list.increment_list(1), - ArtistSongsAction::PageUp => self.album_songs_list.increment_list(-10), - ArtistSongsAction::PageDown => self.album_songs_list.increment_list(10), + ArtistSongsAction::PageUp => self.album_songs_list.increment_list(-PAGE_KEY_LINES), + ArtistSongsAction::PageDown => self.album_songs_list.increment_list(PAGE_KEY_LINES), } } } diff --git a/src/app/ui/browser/artistalbums.rs b/src/app/ui/browser/artistalbums.rs index 56a70b2f..bd750ba9 100644 --- a/src/app/ui/browser/artistalbums.rs +++ b/src/app/ui/browser/artistalbums.rs @@ -2,13 +2,12 @@ use crate::app::ui::browser::BrowserAction; use crate::app::{ component::actionhandler::{Action, KeyHandler, KeyRouter, Keybind, Suggestable, TextHandler}, structures::{AlbumSongsList, ListStatus, Percentage}, - view::{BasicConstraint, Drawable, ListView, Loadable, Scrollable, SortableList, TableView}, + view::{BasicConstraint, ListView, Loadable, Scrollable, SortableList, TableView}, }; use crossterm::event::KeyCode; -use ratatui::widgets::ListState; use std::borrow::Cow; use ytmapi_rs::common::SearchSuggestion; -use ytmapi_rs::{common::TextRun, parse::SearchResultArtist}; +use ytmapi_rs::parse::SearchResultArtist; #[derive(Clone, Debug, Default, PartialEq)] pub enum ArtistInputRouting { diff --git a/src/app/ui/draw.rs b/src/app/ui/draw.rs index 6aaef81a..65fa46eb 100644 --- a/src/app/ui/draw.rs +++ b/src/app/ui/draw.rs @@ -6,10 +6,9 @@ use ratatui::{ layout::{Constraint, Direction, Layout}, terminal::Frame, }; -use tracing::info; use super::{footer, header, WindowContext, YoutuiWindow}; -use crate::app::component::actionhandler::{Action, DisplayableKeyRouter}; +use crate::app::component::actionhandler::DisplayableKeyRouter; use crate::app::view::{Drawable, DrawableMut}; use crate::drawutils::left_bottom_corner_rect; diff --git a/src/app/ui/footer.rs b/src/app/ui/footer.rs index 36fe29bb..c0c3fdd2 100644 --- a/src/app/ui/footer.rs +++ b/src/app/ui/footer.rs @@ -63,7 +63,6 @@ where .unwrap_or("No title".to_string()), PlayState::NotPlaying => "Not playing".to_string(), PlayState::Stopped => "Not playing".to_string(), - PlayState::Transitioning => "Not playing".to_string(), }; let album_title = match w.playlist.play_status { PlayState::Playing(id) | PlayState::Paused(id) | PlayState::Buffering(id) => w @@ -73,7 +72,6 @@ where .unwrap_or("".to_string()), PlayState::NotPlaying => "".to_string(), PlayState::Stopped => "".to_string(), - PlayState::Transitioning => "".to_string(), }; let artist_title = match w.playlist.play_status { PlayState::Playing(id) | PlayState::Paused(id) | PlayState::Buffering(id) => w @@ -91,16 +89,14 @@ where .unwrap_or("".to_string()), PlayState::NotPlaying => "".to_string(), PlayState::Stopped => "".to_string(), - PlayState::Transitioning => "".to_string(), }; let song_title_string = match w.playlist.play_status { - PlayState::Playing(id) | PlayState::Paused(id) | PlayState::Buffering(id) => format!( + PlayState::Playing(_) | PlayState::Paused(_) | PlayState::Buffering(_) => format!( "{} {song_title} - {artist_title}", w.playlist.play_status.list_icon() ), PlayState::NotPlaying => "".to_string(), PlayState::Stopped => "".to_string(), - PlayState::Transitioning => "".to_string(), }; let footer = Paragraph::new(vec![Line::from(song_title_string), Line::from(album_title)]); let block = Block::default() diff --git a/src/app/ui/header.rs b/src/app/ui/header.rs index c5c34513..eac4b365 100644 --- a/src/app/ui/header.rs +++ b/src/app/ui/header.rs @@ -13,7 +13,7 @@ use crate::app::component::actionhandler::{ Action, DisplayableKeyRouter, KeyHandler, KeybindVisibility, }; -pub fn context_global_keybinds_and_descriptions<'a, C, A>( +pub fn _context_global_keybinds_and_descriptions<'a, C, A>( context: &'a C, ) -> Box, String)> + 'a> where diff --git a/src/app/ui/logger.rs b/src/app/ui/logger.rs index 8ad67ca6..7a390813 100644 --- a/src/app/ui/logger.rs +++ b/src/app/ui/logger.rs @@ -1,16 +1,3 @@ -use std::borrow::Cow; - -use crossterm::event::{KeyCode, KeyEvent}; -use draw::draw_logger; -use ratatui::{ - prelude::{Backend, Rect}, - Frame, -}; -use tokio::sync::mpsc::Sender; -use tui_logger::TuiWidgetEvent; - -use crate::{app::view::DrawableMut, core::send_or_error}; - use crate::app::{ component::actionhandler::{ Action, ActionHandler, ActionProcessor, KeyHandler, KeyRouter, Keybind, TextHandler, @@ -18,6 +5,16 @@ use crate::app::{ ui::AppCallback, view::Drawable, }; +use crate::core::send_or_error; +use crossterm::event::KeyCode; +use draw::draw_logger; +use ratatui::{ + prelude::{Backend, Rect}, + Frame, +}; +use std::borrow::Cow; +use tokio::sync::mpsc::Sender; +use tui_logger::TuiWidgetEvent; #[derive(Clone, Debug, PartialEq)] pub enum LoggerAction { @@ -42,7 +39,8 @@ impl Action for LoggerAction { fn describe(&self) -> Cow { match self { LoggerAction::ViewBrowser => "View Browser".into(), - x => format!("{:?}", self).into(), + // TODO: Improve this from Debug implementation + _ => format!("{:?}", self).into(), } } } @@ -195,7 +193,7 @@ pub mod draw { f.render_widget(log, chunk); } /// helper function to create a centered rect using up certain percentage of the available rect `r` - fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect { + fn _centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect { let popup_layout = Layout::default() .direction(Direction::Vertical) .constraints( diff --git a/src/app/ui/playlist.rs b/src/app/ui/playlist.rs index 6943dee3..3097daf8 100644 --- a/src/app/ui/playlist.rs +++ b/src/app/ui/playlist.rs @@ -96,7 +96,7 @@ impl TextHandler for Playlist { fn take_text(&mut self) -> String { Default::default() } - fn replace_text(&mut self, text: String) {} + fn replace_text(&mut self, _text: String) {} } impl DrawableMut for Playlist { @@ -284,9 +284,6 @@ impl Playlist { self.play_status = PlayState::Stopped } } - pub fn handle_set_all_to_stopped(&mut self) { - self.play_status = PlayState::Stopped - } pub async fn play_selected(&mut self) { let Some(index) = self.list.cur_selected else { return; @@ -417,9 +414,6 @@ impl Playlist { PlayState::NotPlaying | PlayState::Stopped => { warn!("Asked to play next, but not currently playing"); } - PlayState::Transitioning => { - tracing::error!("Asked to play next, but between states. Should not be here!"); - } PlayState::Paused(id) | PlayState::Playing(id) | PlayState::Buffering(id) => { // Guard against duplicate message received. if id > &prev_id { @@ -494,9 +488,6 @@ impl Playlist { PlayState::NotPlaying | PlayState::Stopped => { warn!("Asked to play prev, but not currently playing"); } - PlayState::Transitioning => { - tracing::error!("Asked to play prev, but between states. Should not be here!"); - } PlayState::Paused(id) | PlayState::Playing(id) | PlayState::Buffering(id) => { let prev_song_id = self .get_index_from_id(*id) diff --git a/src/app/view.rs b/src/app/view.rs index 182f5f1a..6316fb74 100644 --- a/src/app/view.rs +++ b/src/app/view.rs @@ -1,14 +1,11 @@ pub mod draw; -use std::{borrow::Cow, fmt::Display}; +use super::{structures::Percentage, ui::YoutuiMutableState}; use ratatui::{ prelude::{Backend, Constraint, Rect}, - widgets::{ListState, ScrollbarState, TableState}, Frame, }; -use tracing::info; - -use super::{structures::Percentage, ui::YoutuiMutableState}; +use std::{borrow::Cow, fmt::Display}; struct _TableSort { column: usize, @@ -19,10 +16,10 @@ enum _SortDirection { Desc, } enum _TableFilter { - All(Filter), - Column { filter: Filter, column: usize }, + All(_Filter), + Column { filter: _Filter, column: usize }, } -enum Filter { +enum _Filter { Contains(String), } diff --git a/src/config.rs b/src/config.rs index 7716a9c5..b33868a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,9 +1,7 @@ +use crate::get_config_dir; use crate::Result; use serde::{Deserialize, Serialize}; -use std::path::Path; -use ytmapi_rs::auth::{BrowserToken, OAuthToken}; - -use crate::get_config_dir; +use ytmapi_rs::auth::OAuthToken; const CONFIG_FILE_NAME: &str = "config.toml"; diff --git a/src/error.rs b/src/error.rs index ee868e98..02aa1dfd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,11 +1,6 @@ -use std::{ - fmt::Display, - path::{Path, PathBuf}, -}; - -use tokio::{sync::mpsc, task::JoinError}; - use crate::config::AuthType; +use std::{fmt::Display, path::PathBuf}; +use tokio::{sync::mpsc, task::JoinError}; pub type Result = std::result::Result; diff --git a/src/main.rs b/src/main.rs index c6972bcd..3f507c72 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,19 +6,14 @@ mod core; mod drawutils; pub mod error; -use cli::{ - get_and_output_oauth_token, handle_cli_command, print_artist, print_artist_json, - print_library_artists, print_library_artists_json, print_library_playlists, - print_library_playlists_json, print_search_suggestions, print_search_suggestions_json, -}; -use config::{ApiKey, Config}; -pub use error::Result; - use clap::{Args, Parser, Subcommand}; +use cli::handle_cli_command; +use config::{ApiKey, Config}; use directories::ProjectDirs; use error::Error; -use std::path::{Path, PathBuf}; -use ytmapi_rs::auth::{BrowserToken, OAuthToken}; +pub use error::Result; +use std::path::PathBuf; +use ytmapi_rs::auth::OAuthToken; pub const COOKIE_FILENAME: &str = "cookie.txt"; pub const OAUTH_FILENAME: &str = "oauth.json"; @@ -64,7 +59,7 @@ enum Commands { } pub struct RuntimeInfo { - debug: bool, + _debug: bool, config: Config, api_key: ApiKey, } @@ -105,7 +100,7 @@ async fn try_main() -> Result<()> { // TODO: Remove delay, should be handled inside app instead. let api_key = load_api_key(&config).await?; let rt = RuntimeInfo { - debug, + _debug: debug, config, api_key, };