style(clippy): enforce clippy use_self lint

Clippy's `use_self` line ensures that `Self` is used instead of the real
name whenever possible. This makes searching easier and cleans up the
code a bit.
This commit is contained in:
Thomas Frans
2023-09-27 21:53:13 +02:00
committed by Henrik Friedrichsen
parent 01e01b59e4
commit fe8f8e78ee
25 changed files with 170 additions and 172 deletions

View File

@@ -39,7 +39,7 @@ pub enum MoveAmount {
impl Default for MoveAmount { impl Default for MoveAmount {
fn default() -> Self { fn default() -> Self {
MoveAmount::Integer(1) Self::Integer(1)
} }
} }
@@ -92,8 +92,8 @@ pub enum SeekDirection {
impl fmt::Display for SeekDirection { impl fmt::Display for SeekDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self { let repr = match self {
SeekDirection::Absolute(pos) => format!("{pos}"), Self::Absolute(pos) => format!("{pos}"),
SeekDirection::Relative(delta) => { Self::Relative(delta) => {
format!("{}{}", if delta > &0 { "+" } else { "" }, delta) format!("{}{}", if delta > &0 { "+" } else { "" }, delta)
} }
}; };
@@ -112,8 +112,8 @@ impl fmt::Display for InsertSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self { let repr = match self {
#[cfg(feature = "share_clipboard")] #[cfg(feature = "share_clipboard")]
InsertSource::Clipboard => "".into(), Self::Clipboard => "".into(),
InsertSource::Input(url) => url.to_string(), Self::Input(url) => url.to_string(),
}; };
write!(f, "{repr}") write!(f, "{repr}")
} }
@@ -169,23 +169,23 @@ impl fmt::Display for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut repr_tokens = vec![self.basename().to_owned()]; let mut repr_tokens = vec![self.basename().to_owned()];
let mut extras_args = match self { let mut extras_args = match self {
Command::Focus(tab) => vec![tab.to_owned()], Self::Focus(tab) => vec![tab.to_owned()],
Command::Seek(direction) => vec![direction.to_string()], Self::Seek(direction) => vec![direction.to_string()],
Command::VolumeUp(amount) => vec![amount.to_string()], Self::VolumeUp(amount) => vec![amount.to_string()],
Command::VolumeDown(amount) => vec![amount.to_string()], Self::VolumeDown(amount) => vec![amount.to_string()],
Command::Repeat(mode) => match mode { Self::Repeat(mode) => match mode {
Some(mode) => vec![mode.to_string()], Some(mode) => vec![mode.to_string()],
None => vec![], None => vec![],
}, },
Command::Shuffle(on) => match on { Self::Shuffle(on) => match on {
Some(b) => vec![(if *b { "on" } else { "off" }).into()], Some(b) => vec![(if *b { "on" } else { "off" }).into()],
None => vec![], None => vec![],
}, },
#[cfg(feature = "share_clipboard")] #[cfg(feature = "share_clipboard")]
Command::Share(mode) => vec![mode.to_string()], Self::Share(mode) => vec![mode.to_string()],
Command::Open(mode) => vec![mode.to_string()], Self::Open(mode) => vec![mode.to_string()],
Command::Goto(mode) => vec![mode.to_string()], Self::Goto(mode) => vec![mode.to_string()],
Command::Move(mode, amount) => match (mode, amount) { Self::Move(mode, amount) => match (mode, amount) {
(MoveMode::Playing, _) => vec!["playing".to_string()], (MoveMode::Playing, _) => vec!["playing".to_string()],
(MoveMode::Up, MoveAmount::Extreme) => vec!["top".to_string()], (MoveMode::Up, MoveAmount::Extreme) => vec!["top".to_string()],
(MoveMode::Down, MoveAmount::Extreme) => vec!["bottom".to_string()], (MoveMode::Down, MoveAmount::Extreme) => vec!["bottom".to_string()],
@@ -194,40 +194,40 @@ impl fmt::Display for Command {
(mode, MoveAmount::Float(amount)) => vec![mode.to_string(), amount.to_string()], (mode, MoveAmount::Float(amount)) => vec![mode.to_string(), amount.to_string()],
(mode, MoveAmount::Integer(amount)) => vec![mode.to_string(), amount.to_string()], (mode, MoveAmount::Integer(amount)) => vec![mode.to_string(), amount.to_string()],
}, },
Command::Shift(mode, amount) => vec![mode.to_string(), amount.unwrap_or(1).to_string()], Self::Shift(mode, amount) => vec![mode.to_string(), amount.unwrap_or(1).to_string()],
Command::Search(term) => vec![term.to_owned()], Self::Search(term) => vec![term.to_owned()],
Command::Jump(mode) => match mode { Self::Jump(mode) => match mode {
JumpMode::Previous | JumpMode::Next => vec![], JumpMode::Previous | JumpMode::Next => vec![],
JumpMode::Query(term) => vec![term.to_owned()], JumpMode::Query(term) => vec![term.to_owned()],
}, },
Command::Insert(source) => vec![source.to_string()], Self::Insert(source) => vec![source.to_string()],
Command::NewPlaylist(name) => vec![name.to_owned()], Self::NewPlaylist(name) => vec![name.to_owned()],
Command::Sort(key, direction) => vec![key.to_string(), direction.to_string()], Self::Sort(key, direction) => vec![key.to_string(), direction.to_string()],
Command::ShowRecommendations(mode) => vec![mode.to_string()], Self::ShowRecommendations(mode) => vec![mode.to_string()],
Command::Execute(cmd) => vec![cmd.to_owned()], Self::Execute(cmd) => vec![cmd.to_owned()],
Command::Quit Self::Quit
| Command::TogglePlay | Self::TogglePlay
| Command::Stop | Self::Stop
| Command::Previous | Self::Previous
| Command::Next | Self::Next
| Command::Clear | Self::Clear
| Command::Queue | Self::Queue
| Command::PlayNext | Self::PlayNext
| Command::Play | Self::Play
| Command::UpdateLibrary | Self::UpdateLibrary
| Command::Save | Self::Save
| Command::SaveCurrent | Self::SaveCurrent
| Command::SaveQueue | Self::SaveQueue
| Command::Add | Self::Add
| Command::AddCurrent | Self::AddCurrent
| Command::Delete | Self::Delete
| Command::Back | Self::Back
| Command::Help | Self::Help
| Command::ReloadConfig | Self::ReloadConfig
| Command::Noop | Self::Noop
| Command::Logout | Self::Logout
| Command::Reconnect | Self::Reconnect
| Command::Redraw => vec![], | Self::Redraw => vec![],
}; };
repr_tokens.append(&mut extras_args); repr_tokens.append(&mut extras_args);
write!(f, "{}", repr_tokens.join(" ")) write!(f, "{}", repr_tokens.join(" "))
@@ -237,50 +237,50 @@ impl fmt::Display for Command {
impl Command { impl Command {
pub fn basename(&self) -> &str { pub fn basename(&self) -> &str {
match self { match self {
Command::Quit => "quit", Self::Quit => "quit",
Command::TogglePlay => "playpause", Self::TogglePlay => "playpause",
Command::Stop => "stop", Self::Stop => "stop",
Command::Previous => "previous", Self::Previous => "previous",
Command::Next => "next", Self::Next => "next",
Command::Clear => "clear", Self::Clear => "clear",
Command::Queue => "queue", Self::Queue => "queue",
Command::PlayNext => "playnext", Self::PlayNext => "playnext",
Command::Play => "play", Self::Play => "play",
Command::UpdateLibrary => "update", Self::UpdateLibrary => "update",
Command::Save => "save", Self::Save => "save",
Command::SaveCurrent => "save current", Self::SaveCurrent => "save current",
Command::SaveQueue => "save queue", Self::SaveQueue => "save queue",
Command::Add => "add", Self::Add => "add",
Command::AddCurrent => "add current", Self::AddCurrent => "add current",
Command::Delete => "delete", Self::Delete => "delete",
Command::Focus(_) => "focus", Self::Focus(_) => "focus",
Command::Seek(_) => "seek", Self::Seek(_) => "seek",
Command::VolumeUp(_) => "volup", Self::VolumeUp(_) => "volup",
Command::VolumeDown(_) => "voldown", Self::VolumeDown(_) => "voldown",
Command::Repeat(_) => "repeat", Self::Repeat(_) => "repeat",
Command::Shuffle(_) => "shuffle", Self::Shuffle(_) => "shuffle",
#[cfg(feature = "share_clipboard")] #[cfg(feature = "share_clipboard")]
Command::Share(_) => "share", Self::Share(_) => "share",
Command::Back => "back", Self::Back => "back",
Command::Open(_) => "open", Self::Open(_) => "open",
Command::Goto(_) => "goto", Self::Goto(_) => "goto",
Command::Move(_, _) => "move", Self::Move(_, _) => "move",
Command::Shift(_, _) => "shift", Self::Shift(_, _) => "shift",
Command::Search(_) => "search", Self::Search(_) => "search",
Command::Jump(JumpMode::Previous) => "jumpprevious", Self::Jump(JumpMode::Previous) => "jumpprevious",
Command::Jump(JumpMode::Next) => "jumpnext", Self::Jump(JumpMode::Next) => "jumpnext",
Command::Jump(JumpMode::Query(_)) => "jump", Self::Jump(JumpMode::Query(_)) => "jump",
Command::Help => "help", Self::Help => "help",
Command::ReloadConfig => "reload", Self::ReloadConfig => "reload",
Command::Noop => "noop", Self::Noop => "noop",
Command::Insert(_) => "insert", Self::Insert(_) => "insert",
Command::NewPlaylist(_) => "newplaylist", Self::NewPlaylist(_) => "newplaylist",
Command::Sort(_, _) => "sort", Self::Sort(_, _) => "sort",
Command::Logout => "logout", Self::Logout => "logout",
Command::ShowRecommendations(_) => "similar", Self::ShowRecommendations(_) => "similar",
Command::Redraw => "redraw", Self::Redraw => "redraw",
Command::Execute(_) => "exec", Self::Execute(_) => "exec",
Command::Reconnect => "reconnect", Self::Reconnect => "reconnect",
} }
} }
} }

View File

@@ -51,9 +51,9 @@ impl CommandManager {
library: Arc<Library>, library: Arc<Library>,
config: Arc<Config>, config: Arc<Config>,
events: EventManager, events: EventManager,
) -> CommandManager { ) -> Self {
let bindings = RefCell::new(Self::get_bindings(&config)); let bindings = RefCell::new(Self::get_bindings(&config));
CommandManager { Self {
aliases: HashMap::new(), aliases: HashMap::new(),
bindings, bindings,
spotify, spotify,

View File

@@ -47,7 +47,7 @@ pub struct TrackFormat {
impl TrackFormat { impl TrackFormat {
pub fn default() -> Self { pub fn default() -> Self {
TrackFormat { Self {
left: Some(String::from("%artists - %title")), left: Some(String::from("%artists - %title")),
center: Some(String::from("%album")), center: Some(String::from("%album")),
right: Some(String::from("%saved %duration")), right: Some(String::from("%saved %duration")),
@@ -64,7 +64,7 @@ pub struct NotificationFormat {
impl NotificationFormat { impl NotificationFormat {
pub fn default() -> Self { pub fn default() -> Self {
NotificationFormat { Self {
title: Some(String::from("%title")), title: Some(String::from("%title")),
body: Some(String::from("%artists")), body: Some(String::from("%artists")),
} }
@@ -163,7 +163,7 @@ pub struct UserState {
impl Default for UserState { impl Default for UserState {
fn default() -> Self { fn default() -> Self {
UserState { Self {
volume: u16::MAX, volume: u16::MAX,
shuffle: false, shuffle: false,
repeat: queue::RepeatSetting::None, repeat: queue::RepeatSetting::None,

View File

@@ -21,10 +21,10 @@ pub struct EventManager {
} }
impl EventManager { impl EventManager {
pub fn new(cursive_sink: CbSink) -> EventManager { pub fn new(cursive_sink: CbSink) -> Self {
let (tx, rx) = unbounded(); let (tx, rx) = unbounded();
EventManager { Self {
tx, tx,
rx, rx,
cursive_sink, cursive_sink,

View File

@@ -14,7 +14,7 @@ pub trait CursiveExt {
impl CursiveExt for cursive::Cursive { impl CursiveExt for cursive::Cursive {
fn on_layout<F, R>(&mut self, cb: F) -> R fn on_layout<F, R>(&mut self, cb: F) -> R
where where
F: FnOnce(&mut cursive::Cursive, ViewRef<Layout>) -> R, F: FnOnce(&mut Self, ViewRef<Layout>) -> R,
{ {
let layout = self let layout = self
.find_name::<Layout>("main") .find_name::<Layout>("main")

View File

@@ -32,7 +32,7 @@ impl Drop for IpcSocket {
} }
impl IpcSocket { impl IpcSocket {
pub fn new(handle: &Handle, path: PathBuf, ev: EventManager) -> io::Result<IpcSocket> { pub fn new(handle: &Handle, path: PathBuf, ev: EventManager) -> io::Result<Self> {
let path = if path.exists() && Self::is_open_socket(&path) { let path = if path.exists() && Self::is_open_socket(&path) {
let mut new_path = path; let mut new_path = path;
new_path.set_file_name(format!("ncspot.{}.sock", std::process::id())); new_path.set_file_name(format!("ncspot.{}.sock", std::process::id()));
@@ -59,7 +59,7 @@ impl IpcSocket {
Self::worker(listener, ev, rx.clone()).await; Self::worker(listener, ev, rx.clone()).await;
}); });
Ok(IpcSocket { tx, path }) Ok(Self { tx, path })
} }
fn is_open_socket(path: &PathBuf) -> bool { fn is_open_socket(path: &PathBuf) -> bool {

View File

@@ -1,3 +1,5 @@
#![deny(clippy::use_self)]
#[macro_use] #[macro_use]
extern crate cursive; extern crate cursive;
#[macro_use] #[macro_use]

View File

@@ -15,7 +15,7 @@ pub struct Category {
impl From<&rspotify::model::Category> for Category { impl From<&rspotify::model::Category> for Category {
fn from(c: &rspotify::model::Category) -> Self { fn from(c: &rspotify::model::Category) -> Self {
Category { Self {
id: c.id.clone(), id: c.id.clone(),
name: c.name.clone(), name: c.name.clone(),
} }

View File

@@ -20,7 +20,7 @@ pub enum Playable {
} }
impl Playable { impl Playable {
pub fn format(playable: &Playable, formatting: &str, library: &Library) -> String { pub fn format(playable: &Self, formatting: &str, library: &Library) -> String {
formatting formatting
.replace( .replace(
"%artists", "%artists",
@@ -38,15 +38,15 @@ impl Playable {
.replace( .replace(
"%title", "%title",
match playable.clone() { match playable.clone() {
Playable::Episode(episode) => episode.name, Self::Episode(episode) => episode.name,
Playable::Track(track) => track.title, Self::Track(track) => track.title,
} }
.as_str(), .as_str(),
) )
.replace( .replace(
"%album", "%album",
match playable.clone() { match playable.clone() {
Playable::Track(track) => track.album.unwrap_or_default(), Self::Track(track) => track.album.unwrap_or_default(),
_ => String::new(), _ => String::new(),
} }
.as_str(), .as_str(),
@@ -54,8 +54,8 @@ impl Playable {
.replace( .replace(
"%saved", "%saved",
if library.is_saved_track(&match playable.clone() { if library.is_saved_track(&match playable.clone() {
Playable::Episode(episode) => Playable::Episode(episode), Self::Episode(episode) => Self::Episode(episode),
Playable::Track(track) => Playable::Track(track), Self::Track(track) => Self::Track(track),
}) { }) {
if library.cfg.values().use_nerdfont.unwrap_or_default() { if library.cfg.values().use_nerdfont.unwrap_or_default() {
"\u{f012c}" "\u{f012c}"
@@ -71,50 +71,50 @@ impl Playable {
pub fn id(&self) -> Option<String> { pub fn id(&self) -> Option<String> {
match self { match self {
Playable::Track(track) => track.id.clone(), Self::Track(track) => track.id.clone(),
Playable::Episode(episode) => Some(episode.id.clone()), Self::Episode(episode) => Some(episode.id.clone()),
} }
} }
pub fn uri(&self) -> String { pub fn uri(&self) -> String {
match self { match self {
Playable::Track(track) => track.uri.clone(), Self::Track(track) => track.uri.clone(),
Playable::Episode(episode) => episode.uri.clone(), Self::Episode(episode) => episode.uri.clone(),
} }
} }
pub fn cover_url(&self) -> Option<String> { pub fn cover_url(&self) -> Option<String> {
match self { match self {
Playable::Track(track) => track.cover_url.clone(), Self::Track(track) => track.cover_url.clone(),
Playable::Episode(episode) => episode.cover_url.clone(), Self::Episode(episode) => episode.cover_url.clone(),
} }
} }
pub fn duration(&self) -> u32 { pub fn duration(&self) -> u32 {
match self { match self {
Playable::Track(track) => track.duration, Self::Track(track) => track.duration,
Playable::Episode(episode) => episode.duration, Self::Episode(episode) => episode.duration,
} }
} }
pub fn list_index(&self) -> usize { pub fn list_index(&self) -> usize {
match self { match self {
Playable::Track(track) => track.list_index, Self::Track(track) => track.list_index,
Playable::Episode(episode) => episode.list_index, Self::Episode(episode) => episode.list_index,
} }
} }
pub fn set_list_index(&mut self, index: usize) { pub fn set_list_index(&mut self, index: usize) {
match self { match self {
Playable::Track(track) => track.list_index = index, Self::Track(track) => track.list_index = index,
Playable::Episode(episode) => episode.list_index = index, Self::Episode(episode) => episode.list_index = index,
} }
} }
pub fn set_added_at(&mut self, added_at: Option<DateTime<Utc>>) { pub fn set_added_at(&mut self, added_at: Option<DateTime<Utc>>) {
match self { match self {
Playable::Track(track) => track.added_at = added_at, Self::Track(track) => track.added_at = added_at,
Playable::Episode(episode) => episode.added_at = added_at, Self::Episode(episode) => episode.added_at = added_at,
} }
} }
@@ -124,8 +124,8 @@ impl Playable {
pub fn as_listitem(&self) -> Box<dyn ListItem> { pub fn as_listitem(&self) -> Box<dyn ListItem> {
match self { match self {
Playable::Track(track) => track.as_listitem(), Self::Track(track) => track.as_listitem(),
Playable::Episode(episode) => episode.as_listitem(), Self::Episode(episode) => episode.as_listitem(),
} }
} }
} }
@@ -133,8 +133,8 @@ impl Playable {
impl From<&PlayableItem> for Playable { impl From<&PlayableItem> for Playable {
fn from(item: &PlayableItem) -> Self { fn from(item: &PlayableItem) -> Self {
match item { match item {
PlayableItem::Episode(episode) => Playable::Episode(episode.into()), PlayableItem::Episode(episode) => Self::Episode(episode.into()),
PlayableItem::Track(track) => Playable::Track(track.into()), PlayableItem::Track(track) => Self::Track(track.into()),
} }
} }
} }
@@ -157,8 +157,8 @@ impl From<&Playable> for Option<rspotify::prelude::PlayableId<'_>> {
impl fmt::Display for Playable { impl fmt::Display for Playable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Playable::Track(track) => track.fmt(f), Self::Track(track) => track.fmt(f),
Playable::Episode(episode) => episode.fmt(f), Self::Episode(episode) => episode.fmt(f),
} }
} }
} }

View File

@@ -147,7 +147,7 @@ impl Playlist {
impl From<&SimplifiedPlaylist> for Playlist { impl From<&SimplifiedPlaylist> for Playlist {
fn from(list: &SimplifiedPlaylist) -> Self { fn from(list: &SimplifiedPlaylist) -> Self {
Playlist { Self {
id: list.id.id().to_string(), id: list.id.id().to_string(),
name: list.name.clone(), name: list.name.clone(),
owner_id: list.owner.id.id().to_string(), owner_id: list.owner.id.id().to_string(),
@@ -162,7 +162,7 @@ impl From<&SimplifiedPlaylist> for Playlist {
impl From<&FullPlaylist> for Playlist { impl From<&FullPlaylist> for Playlist {
fn from(list: &FullPlaylist) -> Self { fn from(list: &FullPlaylist) -> Self {
Playlist { Self {
id: list.id.id().to_string(), id: list.id.id().to_string(),
name: list.name.clone(), name: list.name.clone(),
owner_id: list.owner.id.id().to_string(), owner_id: list.owner.id.id().to_string(),

View File

@@ -37,7 +37,7 @@ pub struct Track {
} }
impl Track { impl Track {
pub fn from_simplified_track(track: &SimplifiedTrack, album: &FullAlbum) -> Track { pub fn from_simplified_track(track: &SimplifiedTrack, album: &FullAlbum) -> Self {
let artists = track let artists = track
.artists .artists
.iter() .iter()
@@ -270,12 +270,12 @@ impl ListItem for Track {
) -> Option<Box<dyn ViewExt>> { ) -> Option<Box<dyn ViewExt>> {
let spotify = queue.get_spotify(); let spotify = queue.get_spotify();
let recommendations: Option<Vec<Track>> = if let Some(id) = &self.id { let recommendations: Option<Vec<Self>> = if let Some(id) = &self.id {
spotify spotify
.api .api
.recommendations(None, None, Some(vec![id])) .recommendations(None, None, Some(vec![id]))
.map(|r| r.tracks) .map(|r| r.tracks)
.map(|tracks| tracks.iter().map(Track::from).collect()) .map(|tracks| tracks.iter().map(Self::from).collect())
} else { } else {
None None
}; };

View File

@@ -491,7 +491,7 @@ impl MprisManager {
} }
}); });
MprisManager { tx } Self { tx }
} }
async fn serve( async fn serve(

View File

@@ -49,10 +49,10 @@ pub struct Queue {
} }
impl Queue { impl Queue {
pub fn new(spotify: Spotify, cfg: Arc<Config>, library: Arc<Library>) -> Queue { pub fn new(spotify: Spotify, cfg: Arc<Config>, library: Arc<Library>) -> Self {
let queue_state = cfg.state().queuestate.clone(); let queue_state = cfg.state().queuestate.clone();
let playback_state = cfg.state().playback_state.clone(); let playback_state = cfg.state().playback_state.clone();
let queue = Queue { let queue = Self {
queue: Arc::new(RwLock::new(queue_state.queue)), queue: Arc::new(RwLock::new(queue_state.queue)),
spotify: spotify.clone(), spotify: spotify.clone(),
current_track: RwLock::new(queue_state.current_track), current_track: RwLock::new(queue_state.current_track),

View File

@@ -56,12 +56,8 @@ pub struct Spotify {
} }
impl Spotify { impl Spotify {
pub fn new( pub fn new(events: EventManager, credentials: Credentials, cfg: Arc<config::Config>) -> Self {
events: EventManager, let mut spotify = Self {
credentials: Credentials,
cfg: Arc<config::Config>,
) -> Spotify {
let mut spotify = Spotify {
events, events,
credentials, credentials,
cfg: cfg.clone(), cfg: cfg.clone(),
@@ -402,19 +398,19 @@ pub enum UriType {
} }
impl UriType { impl UriType {
pub fn from_uri(s: &str) -> Option<UriType> { pub fn from_uri(s: &str) -> Option<Self> {
if s.starts_with("spotify:album:") { if s.starts_with("spotify:album:") {
Some(UriType::Album) Some(Self::Album)
} else if s.starts_with("spotify:artist:") { } else if s.starts_with("spotify:artist:") {
Some(UriType::Artist) Some(Self::Artist)
} else if s.starts_with("spotify:track:") { } else if s.starts_with("spotify:track:") {
Some(UriType::Track) Some(Self::Track)
} else if s.starts_with("spotify:") && s.contains(":playlist:") { } else if s.starts_with("spotify:") && s.contains(":playlist:") {
Some(UriType::Playlist) Some(Self::Playlist)
} else if s.starts_with("spotify:show:") { } else if s.starts_with("spotify:show:") {
Some(UriType::Show) Some(Self::Show)
} else if s.starts_with("spotify:episode:") { } else if s.starts_with("spotify:episode:") {
Some(UriType::Episode) Some(Self::Episode)
} else { } else {
None None
} }

View File

@@ -56,7 +56,7 @@ impl Default for WebApi {
} }
impl WebApi { impl WebApi {
pub fn new() -> WebApi { pub fn new() -> Self {
Self::default() Self::default()
} }

View File

@@ -25,8 +25,8 @@ impl fmt::Display for SpotifyUrl {
} }
impl SpotifyUrl { impl SpotifyUrl {
pub fn new(id: &str, uri_type: UriType) -> SpotifyUrl { pub fn new(id: &str, uri_type: UriType) -> Self {
SpotifyUrl { Self {
id: id.to_string(), id: id.to_string(),
uri_type, uri_type,
} }
@@ -39,7 +39,7 @@ impl SpotifyUrl {
/// assert_eq!(result.id, "4uLU6hMCjMI75M1A2tKUQC"); /// assert_eq!(result.id, "4uLU6hMCjMI75M1A2tKUQC");
/// assert_eq!(result.uri_type, URIType::Track); /// assert_eq!(result.uri_type, URIType::Track);
/// ``` /// ```
pub fn from_url<S: AsRef<str>>(s: S) -> Option<SpotifyUrl> { pub fn from_url<S: AsRef<str>>(s: S) -> Option<Self> {
let url = Url::parse(s.as_ref()).ok()?; let url = Url::parse(s.as_ref()).ok()?;
if url.host() != Some(Host::Domain("open.spotify.com")) { if url.host() != Some(Host::Domain("open.spotify.com")) {
return None; return None;
@@ -71,7 +71,7 @@ impl SpotifyUrl {
let id = path_segments.next()?; let id = path_segments.next()?;
Some(SpotifyUrl::new(id, uri_type)) Some(Self::new(id, uri_type))
} }
} }

View File

@@ -50,8 +50,8 @@ impl Worker {
session: Session, session: Session,
player: Player, player: Player,
mixer: Box<dyn Mixer>, mixer: Box<dyn Mixer>,
) -> Worker { ) -> Self {
Worker { Self {
events, events,
player_events: UnboundedReceiverStream::new(player_events), player_events: UnboundedReceiverStream::new(player_events),
commands: UnboundedReceiverStream::new(commands), commands: UnboundedReceiverStream::new(commands),

View File

@@ -17,7 +17,7 @@ pub struct HelpView {
} }
impl HelpView { impl HelpView {
pub fn new(bindings: HashMap<String, Vec<Command>>) -> HelpView { pub fn new(bindings: HashMap<String, Vec<Command>>) -> Self {
let mut text = StyledString::styled("Keybindings\n\n", Effect::Bold); let mut text = StyledString::styled("Keybindings\n\n", Effect::Bold);
let note = format!( let note = format!(
@@ -43,7 +43,7 @@ impl HelpView {
text.append(binding); text.append(binding);
} }
HelpView { Self {
view: ScrollView::new(TextView::new(text)), view: ScrollView::new(TextView::new(text)),
} }
} }

View File

@@ -42,7 +42,7 @@ impl Layout {
ev: &events::EventManager, ev: &events::EventManager,
theme: Theme, theme: Theme,
configuration: Arc<Config>, configuration: Arc<Config>,
) -> Layout { ) -> Self {
let style = ColorStyle::new( let style = ColorStyle::new(
ColorType::Color(*theme.palette.custom("cmdline_bg").unwrap()), ColorType::Color(*theme.palette.custom("cmdline_bg").unwrap()),
ColorType::Color(*theme.palette.custom("cmdline").unwrap()), ColorType::Color(*theme.palette.custom("cmdline").unwrap()),
@@ -89,7 +89,7 @@ impl Layout {
event_manager.trigger(); event_manager.trigger();
}); });
Layout { Self {
screens: HashMap::new(), screens: HashMap::new(),
stack: HashMap::new(), stack: HashMap::new(),
statusbar: status.into_boxed_view(), statusbar: status.into_boxed_view(),

View File

@@ -8,13 +8,13 @@ pub struct Modal<T: View> {
impl<T: View> Modal<T> { impl<T: View> Modal<T> {
pub fn new(inner: T) -> Self { pub fn new(inner: T) -> Self {
Modal { Self {
block_events: true, block_events: true,
inner, inner,
} }
} }
pub fn new_ext(inner: T) -> Self { pub fn new_ext(inner: T) -> Self {
Modal { Self {
block_events: false, block_events: false,
inner, inner,
} }

View File

@@ -18,7 +18,7 @@ pub struct ApiResult<I> {
} }
impl<I: ListItem + Clone> ApiResult<I> { impl<I: ListItem + Clone> ApiResult<I> {
pub fn new(limit: u32, fetch_page: Arc<FetchPageFn<I>>) -> ApiResult<I> { pub fn new(limit: u32, fetch_page: Arc<FetchPageFn<I>>) -> Self {
let items = Arc::new(RwLock::new(Vec::new())); let items = Arc::new(RwLock::new(Vec::new()));
if let Some(first_page) = fetch_page(0) { if let Some(first_page) = fetch_page(0) {
debug!( debug!(
@@ -27,7 +27,7 @@ impl<I: ListItem + Clone> ApiResult<I> {
first_page.total first_page.total
); );
items.write().unwrap().extend(first_page.items); items.write().unwrap().extend(first_page.items);
ApiResult { Self {
offset: Arc::new(RwLock::new(first_page.offset)), offset: Arc::new(RwLock::new(first_page.offset)),
limit, limit,
total: first_page.total, total: first_page.total,
@@ -35,7 +35,7 @@ impl<I: ListItem + Clone> ApiResult<I> {
fetch_page: fetch_page.clone(), fetch_page: fetch_page.clone(),
} }
} else { } else {
ApiResult { Self {
offset: Arc::new(RwLock::new(0)), offset: Arc::new(RwLock::new(0)),
limit, limit,
total: 0, total: 0,
@@ -102,7 +102,7 @@ pub struct Pagination<I: ListItem> {
impl<I: ListItem> Default for Pagination<I> { impl<I: ListItem> Default for Pagination<I> {
fn default() -> Self { fn default() -> Self {
Pagination { Self {
loaded_content: Arc::new(RwLock::new(0)), loaded_content: Arc::new(RwLock::new(0)),
max_content: Arc::new(RwLock::new(None)), max_content: Arc::new(RwLock::new(None)),
callback: Arc::new(RwLock::new(None)), callback: Arc::new(RwLock::new(None)),

View File

@@ -22,10 +22,10 @@ pub struct QueueView {
} }
impl QueueView { impl QueueView {
pub fn new(queue: Arc<Queue>, library: Arc<Library>) -> QueueView { pub fn new(queue: Arc<Queue>, library: Arc<Library>) -> Self {
let list = ListView::new(queue.queue.clone(), queue.clone(), library.clone()); let list = ListView::new(queue.queue.clone(), queue.clone(), library.clone());
QueueView { Self {
list, list,
library, library,
queue, queue,

View File

@@ -37,7 +37,7 @@ pub struct SearchView {
pub const EDIT_ID: &str = "search_edit"; pub const EDIT_ID: &str = "search_edit";
impl SearchView { impl SearchView {
pub fn new(events: EventManager, queue: Arc<Queue>, library: Arc<Library>) -> SearchView { pub fn new(events: EventManager, queue: Arc<Queue>, library: Arc<Library>) -> Self {
let searchfield = EditView::new() let searchfield = EditView::new()
.on_submit(move |s, input| { .on_submit(move |s, input| {
if !input.is_empty() { if !input.is_empty() {
@@ -52,7 +52,7 @@ impl SearchView {
}) })
.with_name(EDIT_ID); .with_name(EDIT_ID);
SearchView { Self {
edit: searchfield, edit: searchfield,
edit_focused: true, edit_focused: true,
} }

View File

@@ -49,7 +49,7 @@ impl SearchResultsView {
events: EventManager, events: EventManager,
queue: Arc<Queue>, queue: Arc<Queue>,
library: Arc<Library>, library: Arc<Library>,
) -> SearchResultsView { ) -> Self {
let results_tracks = Arc::new(RwLock::new(Vec::new())); let results_tracks = Arc::new(RwLock::new(Vec::new()));
let results_albums = Arc::new(RwLock::new(Vec::new())); let results_albums = Arc::new(RwLock::new(Vec::new()));
let results_artists = Arc::new(RwLock::new(Vec::new())); let results_artists = Arc::new(RwLock::new(Vec::new()));
@@ -79,7 +79,7 @@ impl SearchResultsView {
.tab("shows", list_shows.with_title("Podcasts")) .tab("shows", list_shows.with_title("Podcasts"))
.tab("episodes", list_episodes.with_title("Podcast Episodes")); .tab("episodes", list_episodes.with_title("Podcast Episodes"));
let mut view = SearchResultsView { let mut view = Self {
search_term, search_term,
results_tracks, results_tracks,
pagination_tracks, pagination_tracks,

View File

@@ -22,10 +22,10 @@ pub struct StatusBar {
} }
impl StatusBar { impl StatusBar {
pub fn new(queue: Arc<Queue>, library: Arc<Library>) -> StatusBar { pub fn new(queue: Arc<Queue>, library: Arc<Library>) -> Self {
let spotify = queue.get_spotify(); let spotify = queue.get_spotify();
StatusBar { Self {
queue, queue,
spotify, spotify,
library, library,