Skip to content

Commit

Permalink
Tidied up compiler warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
nick42d committed Nov 30, 2023
1 parent 326efae commit 01932dc
Show file tree
Hide file tree
Showing 22 changed files with 99 additions and 206 deletions.
20 changes: 3 additions & 17 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -56,8 +55,6 @@ pub enum AppCallback {
GetProgress(ListSongID),
Quit,
ChangeContext(WindowContext),
Next,
Prev,
// Perhaps shiould not be here.
HandleApiError(Error),
IncreaseVolume(i8),
Expand All @@ -69,7 +66,6 @@ pub enum AppCallback {
PlaySong(Arc<Vec<u8>>, ListSongID),
PausePlay(ListSongID),
Stop(ListSongID),
StopAll,
}

impl Youtui {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
1 change: 0 additions & 1 deletion src/app/component.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod actionhandler;
pub mod contextpane;
pub mod messagehandler;
4 changes: 2 additions & 2 deletions src/app/component/actionhandler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl<A: Action> Mode<A> {
) -> Box<dyn Iterator<Item = (Cow<str>, Cow<str>)> + '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<dyn Iterator<Item = (Cow<str>, Cow<str>, Cow<str>)> + 'a> {
Box::new(self.key_binds.iter().map(|bind| bind.as_readable()))
Expand Down Expand Up @@ -262,7 +262,7 @@ pub trait ActionProcessor<A: Action + Clone>: ActionHandler<A> + KeyHandler<A> {

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!()
}
}
Expand Down
18 changes: 0 additions & 18 deletions src/app/component/contextpane.rs

This file was deleted.

21 changes: 13 additions & 8 deletions src/app/musiccache.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf>,
}

impl MusicCache {
fn cache_song(&mut self, song: Arc<Vec<u8>>, path: PathBuf) {
impl _MusicCache {
fn _cache_song(&mut self, song: Arc<Vec<u8>>, 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<Option<Vec<u8>>, std::io::Error> {
fn _retrieve_song(
&self,
path: PathBuf,
) -> std::result::Result<Option<Vec<u8>>, 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));
}
Expand Down
7 changes: 4 additions & 3 deletions src/app/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
36 changes: 26 additions & 10 deletions src/app/server/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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
Expand All @@ -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();
Expand All @@ -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
Expand All @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand Down Expand Up @@ -357,5 +372,6 @@ impl Api {
kill_rx,
)
.await;
Ok(())
}
}
22 changes: 4 additions & 18 deletions src/app/server/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ pub enum Request {
PlaySong(Arc<Vec<u8>>, ListSongID, TaskID),
GetPlayProgress(ListSongID, TaskID), // Should give ID?
Stop(ListSongID, TaskID),
StopAll(TaskID),
PausePlay(ListSongID, TaskID),
}

Expand All @@ -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
}
Expand All @@ -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?)
}
}

Expand All @@ -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;
}
};
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
Expand Down
10 changes: 3 additions & 7 deletions src/app/structures.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -55,7 +53,6 @@ pub enum DownloadStatus {
pub enum PlayState {
NotPlaying,
Playing(ListSongID),
Transitioning,
Paused(ListSongID),
// May be the same as NotPlaying?
Stopped,
Expand All @@ -68,7 +65,6 @@ impl PlayState {
PlayState::Buffering(_) => '',
PlayState::NotPlaying => '',
PlayState::Playing(_) => '',
PlayState::Transitioning => '',
PlayState::Paused(_) => '',
PlayState::Stopped => '',
}
Expand All @@ -88,16 +84,16 @@ impl DownloadStatus {
}

impl ListSong {
fn set_year(&mut self, year: Rc<String>) {
fn _set_year(&mut self, year: Rc<String>) {
self.year = year;
}
fn set_album(&mut self, album: Rc<String>) {
fn _set_album(&mut self, album: Rc<String>) {
self.album = album;
}
pub fn get_year(&self) -> &String {
&self.year
}
fn set_artists(&mut self, artists: Vec<Rc<String>>) {
fn _set_artists(&mut self, artists: Vec<Rc<String>>) {
self.artists = artists;
}
pub fn get_artists(&self) -> &Vec<Rc<String>> {
Expand Down
Loading

0 comments on commit 01932dc

Please sign in to comment.