feat: Now Playing view like the Apple TV app's

The cover large over a blurred copy of itself, what's playing beside it with the
line being sung, and the transport along the bottom; the queue and lyrics drawer
opens at its right edge. Opens from the player bar's cover, its expand button or
⌘P; closes with the chevron, Esc, ⌘P or Back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yuriy.pandClaude Opus 5.5 committed 2026-10-22 14:39:22 +06:00
1 parent 899ab223b9
commit e2ac2de9f4
16 files changed
+572 -46

No files matched your search

+2
View File
@@ -20,6 +20,8 @@ tokio = { version = "1", features = ["time", "rt", "fs", "sync"] }
directories = "6.0.0"
sys-locale = "0.3.2"
png = { version = "0.18.1", optional = true }
# Already built for iced's image widget; used directly to blur the Now Playing backdrop.
image = { version = "0.25", default-features = false }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6.3"
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.460.0 - ISC -->
<svg
class="lucide lucide-chevron-down"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>

After

Width:  |  Height:  |  Size: 320 B

+18
View File
@@ -0,0 +1,18 @@
<!-- @license lucide-static v0.460.0 - ISC -->
<svg
class="lucide lucide-maximize-2"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="15 3 21 3 21 9" />
<polyline points="9 21 3 21 3 15" />
<line x1="21" x2="14" y1="3" y2="10" />
<line x1="3" x2="10" y1="21" y2="14" />
</svg>

After

Width:  |  Height:  |  Size: 452 B

+100 -27
View File
@@ -30,7 +30,7 @@ use crate::store::{self, Appearance, Locale, Quality, Settings};
use crate::ui::theme::{self, shell};
use crate::widgets::drawer::{self, Panel};
use crate::widgets::menu::{self, Menu};
use crate::widgets::player_bar;
use crate::widgets::{now_playing, player_bar};
use crate::widgets::sheet::{self, Sheet};
use crate::widgets::track_list::{Drag, Env};
use crate::widgets::{sidebar, topbar};
@@ -54,6 +54,8 @@ pub struct App {
nav: Navigator,
search: Search,
drawer: Option<Panel>,
/// Now Playing covers the window, player bar included.
now_playing: bool,
player: Player,
library: Library,
/// Album, artist and playlist pages visited this session.
@@ -106,6 +108,7 @@ pub enum Message {
Search(search::Msg),
ToggleDrawer(Panel),
CloseDrawer,
ShowNowPlaying(bool),
Player(player::Msg),
PlayTracks { tracks: Arc<[Track]>, start: usize, shuffle: bool },
LoadLiked,
@@ -207,6 +210,7 @@ impl App {
nav: Navigator::new(Route::Home),
search: Search::default(),
drawer: None,
now_playing: false,
player: Player::default(),
library: Library::default(),
pages: HashMap::new(),
@@ -260,6 +264,11 @@ impl App {
app.pages.insert(Route::Playlist(crate::snapshot::OWN_PLAYLIST), Loadable::Loaded(config.sample_playlist()));
app.menu = config.menu();
app.drag = config.drag();
if config.now_playing {
app.now_playing = true;
let tracks = config.sample_liked().into();
let _ = app.player.update(player::Msg::Play { tracks, start: 0, shuffle: None });
}
if let Some(route) = config.route {
app.nav = Navigator::new(route);
}
@@ -368,6 +377,11 @@ impl App {
pub fn update(&mut self, message: Message) -> Task<Message> {
let traced = trace(&message);
let task = self.update_inner(message);
if self.now_playing
&& let Some(url) = self.player.track().and_then(|t| t.cover_url(crate::covers::LARGE))
{
self.covers.make_backdrop(&url);
}
if traced {
let now = self.player.track().map_or("-".to_owned(), |t| t.full_title());
let next: Vec<String> = self
@@ -494,6 +508,7 @@ impl App {
self.session = Session::SignedOut(Box::default());
self.nav = Navigator::new(Route::Home);
self.drawer = None;
self.now_playing = false;
self.player.reset();
self.mini_player.update(None, self.player.status());
self.library = Library::default();
@@ -509,6 +524,7 @@ impl App {
Message::Navigate(route) => {
self.sheet = None;
self.menu = None;
self.now_playing = false;
self.nav.go(route);
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
// Opening Search is a request to type.
@@ -525,6 +541,8 @@ impl App {
return task;
}
}
// Back from Now Playing returns to the page under it.
Message::Back if self.now_playing => self.now_playing = false,
Message::Back => {
self.nav.back();
return self.on_enter(self.nav.current());
@@ -544,6 +562,10 @@ impl App {
return self.want_lyrics();
}
Message::CloseDrawer => self.drawer = None,
Message::ShowNowPlaying(show) => {
self.now_playing = show;
return self.want_lyrics();
}
Message::Player(msg) => {
let before = self.player.track().map(|t| t.id.clone());
let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit);
@@ -1005,7 +1027,7 @@ impl App {
Message::LikeTrack(track, !liked)
}
Shortcut::FocusSearch => return focus_search(),
Shortcut::Back if self.nav.can_go_back() => Message::Back,
Shortcut::Back if self.now_playing || self.nav.can_go_back() => Message::Back,
Shortcut::Back => return Task::none(),
Shortcut::Dismiss => {
if self.drag.is_some() {
@@ -1016,12 +1038,17 @@ impl App {
self.sheet = None;
} else if self.search.suggestions().is_some() {
return self.update(Message::Search(search::Msg::CloseSuggestions));
} else {
} else if self.drawer.is_some() {
self.drawer = None;
} else {
self.now_playing = false;
}
return Task::none();
}
Shortcut::Go(route) => Message::Navigate(route),
Shortcut::NowPlaying if self.now_playing => Message::ShowNowPlaying(false),
Shortcut::NowPlaying if self.player.track().is_some() => Message::ShowNowPlaying(true),
Shortcut::NowPlaying => return Task::none(),
Shortcut::MenuUp | Shortcut::MenuDown | Shortcut::MenuIn | Shortcut::MenuOut | Shortcut::MenuEnter => {
return self.menu_key(shortcut);
}
@@ -1227,6 +1254,42 @@ impl App {
}
fn shell<'a>(&'a self, t: &'static theme::Tokens, account: &'a Account) -> Element<'a, Message> {
let liked = self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id));
let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id));
let window = if self.now_playing {
now_playing::view(now_playing::Ctx {
t,
player: &self.player,
liked,
drawer: self.drawer,
covers: &self.covers,
lyrics,
})
} else {
self.browsing(t, account, liked, lyrics)
};
let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)];
if let Some((text, _)) = &self.toast {
layers = layers.push(sheet::toast(t, text));
}
if let Some(open) = &self.sheet {
layers = layers.push(sheet::overlay(t, open));
}
if let Some(open) = &self.menu {
layers = layers.push(menu::layer(t, open, self.menu_ctx(&open.target)));
}
layers.into()
}
/// Sidebar, page and drawer over the player bar.
fn browsing<'a>(
&'a self,
t: &'static theme::Tokens,
account: &'a Account,
liked: bool,
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
) -> Element<'a, Message> {
let route = self.nav.current();
let env = Env {
t,
@@ -1279,35 +1342,17 @@ impl App {
.height(Fill);
if let Some(panel) = self.drawer {
let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id));
body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers, lyrics));
}
let window = column![
column![
body,
hline(),
container(player_bar::view(
t,
&self.player,
self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id)),
self.drawer,
&self.covers,
))
.height(shell::PLAYER)
.style(theme::panel),
];
let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)];
if let Some((text, _)) = &self.toast {
layers = layers.push(sheet::toast(t, text));
}
if let Some(open) = &self.sheet {
layers = layers.push(sheet::overlay(t, open));
}
if let Some(open) = &self.menu {
layers = layers.push(menu::layer(t, open, self.menu_ctx(&open.target)));
}
layers.into()
container(player_bar::view(t, &self.player, liked, self.drawer, &self.covers))
.height(shell::PLAYER)
.style(theme::panel),
]
.into()
}
/// Runs the player's requests against the API.
@@ -1503,6 +1548,34 @@ mod tests {
assert_eq!(app.drawer, None);
}
#[test]
fn now_playing_opens_with_a_track_and_closes_after_the_drawer() {
let mut app = signed_in();
let _ = app.update(Message::Shortcut(Shortcut::NowPlaying));
assert!(!app.now_playing, "nothing to show yet");
let _ = app.update(Message::Player(player::Msg::Play { tracks: vec![track("a")].into(), start: 0, shuffle: None }));
let _ = app.update(Message::Shortcut(Shortcut::NowPlaying));
assert!(app.now_playing);
assert!(app.lyrics.contains_key("a"), "the lyric glance wants the lyrics");
let _ = app.update(Message::ToggleDrawer(Panel::Queue));
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
assert!(app.now_playing && app.drawer.is_none());
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
assert!(!app.now_playing);
// Back leaves Now Playing without leaving the page under it.
let _ = app.update(Message::Navigate(Route::Search));
let _ = app.update(Message::ShowNowPlaying(true));
let _ = app.update(Message::Shortcut(Shortcut::Back));
assert!(!app.now_playing);
assert_eq!(app.nav.current(), Route::Search);
// Going somewhere from its menu closes it.
let _ = app.update(Message::ShowNowPlaying(true));
let _ = app.update(Message::Navigate(Route::Album(1)));
assert!(!app.now_playing);
}
#[test]
fn shortcuts_drive_the_player_and_navigation() {
let mut app = signed_in();
+3 -2
View File
@@ -269,10 +269,11 @@ impl App {
}
}
/// Lyrics for the playing track, fetched once per track while the panel is open.
/// Lyrics for the playing track, fetched once per track while the panel or Now Playing is open.
pub(super) fn want_lyrics(&mut self) -> Task<Message> {
let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() };
if self.drawer != Some(crate::widgets::drawer::Panel::Lyrics) || self.lyrics.contains_key(&track.id) {
let shown = self.now_playing || self.drawer == Some(crate::widgets::drawer::Panel::Lyrics);
if !shown || self.lyrics.contains_key(&track.id) {
return Task::none();
}
let track = track.clone();
+49
View File
@@ -24,10 +24,15 @@ pub const LARGE: u32 = 400;
/// Downloads in flight at once.
const PARALLEL: usize = 8;
/// Side of the Now Playing backdrop in pixels; it is stretched over the window.
const BACKDROP: u32 = 32;
pub struct Covers {
images: HashMap<String, image::Handle>,
pending: HashSet<String>,
failed: HashSet<String>,
/// Blurred copies for the Now Playing backdrop, by cover url; `None` if it couldn't be decoded.
backdrops: HashMap<String, Option<image::Handle>>,
/// Bumped (debounced) when images arrive, so cached lists rebuild.
version: u64,
dirty: bool,
@@ -42,6 +47,7 @@ impl Default for Covers {
images: HashMap::new(),
pending: HashSet::new(),
failed: HashSet::new(),
backdrops: HashMap::new(),
version: 0,
dirty: false,
dir,
@@ -55,6 +61,20 @@ impl Covers {
self.images.get(url).cloned()
}
pub fn backdrop(&self, url: &str) -> Option<image::Handle> {
self.backdrops.get(url).cloned().flatten()
}
/// Blurs a loaded cover for the Now Playing backdrop, once per url.
pub fn make_backdrop(&mut self, url: &str) {
if self.backdrops.contains_key(url) {
return;
}
let Some(image::Handle::Bytes(_, bytes)) = self.images.get(url) else { return };
let blurred = blur(bytes);
self.backdrops.insert(url.to_owned(), blurred);
}
pub fn version(&self) -> u64 {
self.version
}
@@ -136,6 +156,14 @@ async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semapho
Some(bytes.into())
}
/// Shrunk and blurred, so stretched over the window it reads as the cover's colours out of focus.
fn blur(bytes: &[u8]) -> Option<image::Handle> {
let cover = ::image::load_from_memory(bytes).ok()?;
let small = cover.thumbnail_exact(BACKDROP, BACKDROP).to_rgba8();
let soft = ::image::imageops::blur(&small, 3.0);
Some(image::Handle::from_rgba(BACKDROP, BACKDROP, soft.into_raw()))
}
/// A stable, filesystem-safe name for a URL (64-bit FNV-1a).
fn file_name(url: &str) -> String {
let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
@@ -176,6 +204,27 @@ mod tests {
assert!(a.ends_with(".img") && a.len() == 20);
}
#[test]
fn backdrops_are_blurred_once_from_loaded_covers() {
let mut png = Vec::new();
::image::RgbaImage::from_fn(100, 100, |x, _| ::image::Rgba([if x < 50 { 255 } else { 0 }, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), ::image::ImageFormat::Png)
.expect("encode");
let mut covers = Covers { dir: None, ..Covers::default() };
covers.make_backdrop("u");
assert!(covers.backdrop("u").is_none(), "nothing to blur before the cover loads");
covers.loaded("u".into(), Some(Arc::from(png)));
covers.make_backdrop("u");
let Some(image::Handle::Rgba { width, pixels, .. }) = covers.backdrop("u") else { panic!("no backdrop") };
assert_eq!(width, BACKDROP);
// The hard edge in the middle is softened into intermediate reds.
let red = |x: usize| pixels[(BACKDROP as usize * 16 + x) * 4];
assert!(red(0) > 200 && red(31) < 50 && (60..200).contains(&red(16)));
covers.loaded("bad".into(), Some(Arc::from(vec![1u8, 2, 3])));
covers.make_backdrop("bad");
assert!(covers.backdrop("bad").is_none());
}
#[test]
fn arrivals_bump_version_only_on_flush() {
let mut covers = Covers { dir: None, ..Covers::default() };
+1
View File
@@ -17,6 +17,7 @@ pub fn get(english: &str) -> Option<&'static str> {
"Skip 10 seconds forward or back" => "Перемотать на 10 секунд вперёд или назад",
"Volume up or down" => "Громче или тише",
"Like or unlike the track playing" => "«Мне нравится» для играющего трека",
"Open or close Now Playing" => "Открыть или закрыть «Сейчас играет»",
"Go back" => "Назад",
"Close a menu or panel" => "Закрыть меню или панель",
"Home, My Wave, Search, Collection, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Подкасты",
+6 -1
View File
@@ -28,9 +28,11 @@ pub enum Shortcut {
ToggleLike,
FocusSearch,
Back,
/// Esc: closes the menu, then the search suggestions, then the drawer.
/// Esc: closes the menu, then the search suggestions, then the drawer, then Now Playing.
Dismiss,
Go(Route),
/// Opens or closes Now Playing.
NowPlaying,
/// Plain arrows and Enter move through an open menu; without one they do nothing.
MenuUp,
MenuDown,
@@ -92,6 +94,7 @@ pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) ->
Some(match c {
'f' => S::FocusSearch,
'l' => S::ToggleLike,
'p' => S::NowPlaying,
'[' => S::Back,
',' => S::Go(Route::Settings),
'1'..='5' => S::Go(Route::NAV[c as usize - '1' as usize]),
@@ -127,6 +130,7 @@ pub fn help() -> Vec<(&'static str, Vec<String>)> {
(tr("Skip 10 seconds forward or back"), vec![with(shift, "→"), with(shift, "←")]),
(tr("Volume up or down"), vec![with(cmd, "↑"), with(cmd, "↓")]),
(tr("Like or unlike the track playing"), vec![with(cmd, "L")]),
(tr("Open or close Now Playing"), vec![with(cmd, "P")]),
(tr("Search"), vec![with(cmd, "F"), "/".to_owned()]),
(tr("Go back"), vec![with(cmd, "["), with(alt, "←")]),
(tr("Close a menu or panel"), vec!["Esc".to_owned()]),
@@ -179,6 +183,7 @@ mod tests {
// ⌘ plus the key that types "а" in the Russian layout is ⌘F.
assert_eq!(press(ch("а"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch));
assert_eq!(press(ch("д"), Code::KeyL, Modifiers::COMMAND), Some(Shortcut::ToggleLike));
assert_eq!(press(ch("з"), Code::KeyP, Modifiers::COMMAND), Some(Shortcut::NowPlaying));
assert_eq!(press(ch("х"), Code::BracketLeft, Modifiers::COMMAND), Some(Shortcut::Back));
assert_eq!(press(ch("."), Code::Slash, Modifiers::empty()), Some(Shortcut::FocusSearch));
}
+5 -2
View File
@@ -8,7 +8,8 @@
//! `MUSYX_SNAPSHOT_MENU` opens a track menu: `row` (right-click on a row), `sub`
//! (with the playlist list), `edge` (near the bottom-right corner) or `more`
//! (under a row's "…"). `MUSYX_SNAPSHOT_DRAG=1` with `ROUTE=playlist` shows a
//! row of the sample own playlist mid-drag.
//! row of the sample own playlist mid-drag. `MUSYX_SNAPSHOT_ROUTE=nowplaying` opens Now Playing
//! on the first sample track.
//! iced's own `window::screenshot` is used, so it needs no screen-recording permission.
use std::path::PathBuf;
@@ -41,6 +42,7 @@ pub struct Config {
pub delay: Duration,
pub menu: Option<String>,
pub drag: bool,
pub now_playing: bool,
}
/// The sample own playlist for `MUSYX_SNAPSHOT_ROUTE=playlist`.
@@ -51,6 +53,7 @@ impl Config {
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
let var = |k: &str| std::env::var(k).ok().map(|v| v.to_ascii_lowercase());
let signed_out = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("signin");
let now_playing = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("nowplaying");
let route = var("MUSYX_SNAPSHOT_ROUTE").and_then(|r| {
Some(match r.as_str() {
"home" => Route::Home,
@@ -83,7 +86,7 @@ impl Config {
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis);
let menu = var("MUSYX_SNAPSHOT_MENU");
let drag = var("MUSYX_SNAPSHOT_DRAG").is_some_and(|v| v == "1");
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay, menu, drag })
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay, menu, drag, now_playing })
}
/// A made-up account so the shell renders without a network or keychain.
+2
View File
@@ -68,6 +68,8 @@ icons! {
MoveTop => "arrow-up-to-line",
MoveBottom => "arrow-down-to-line",
Artist => "user",
Expand => "maximize-2",
Collapse => "chevron-down",
}
impl Icon {
+34 -6
View File
@@ -222,6 +222,29 @@ pub fn avatar(theme: &Theme) -> container::Style {
}
}
/// Washes the Now Playing backdrop with the ground, more towards the transport.
pub fn backdrop_wash(theme: &Theme) -> container::Style {
let t = tokens(theme);
container::Style {
background: Some(Background::Gradient(
iced::gradient::Linear::new(std::f32::consts::PI)
.add_stop(0.0, t.bg.scale_alpha(0.55))
.add_stop(1.0, t.bg.scale_alpha(0.92))
.into(),
)),
..container::Style::default()
}
}
/// The large cover on Now Playing, which floats over its own blurred copy.
pub fn stage_cover(_: &Theme) -> container::Style {
container::Style {
border: Border { radius: radius::HERO.into(), ..Border::default() },
shadow: Shadow { color: Color::BLACK.scale_alpha(0.35), offset: Vector::new(0.0, 18.0), blur_radius: 50.0 },
..container::Style::default()
}
}
/// Placeholder art for an item without a cover yet: two hues on a diagonal.
pub fn cover(h1: f32, h2: f32, corner: f32) -> impl Fn(&Theme) -> container::Style {
move |_| container::Style {
@@ -402,24 +425,29 @@ pub fn search_field(theme: &Theme, status: text_input::Status) -> text_input::St
/// Thin seek bar: amber fill, knob only while hovered or dragged.
pub fn seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
thin_slider(theme, status, tokens(theme).accent)
thin_slider(theme, status, tokens(theme).accent, 4.0)
}
/// The wider seek bar on Now Playing.
pub fn stage_seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
thin_slider(theme, status, tokens(theme).accent, 6.0)
}
pub fn volume_bar(theme: &Theme, status: slider::Status) -> slider::Style {
thin_slider(theme, status, tokens(theme).fg)
thin_slider(theme, status, tokens(theme).fg, 4.0)
}
fn thin_slider(theme: &Theme, status: slider::Status, fill: Color) -> slider::Style {
fn thin_slider(theme: &Theme, status: slider::Status, fill: Color, width: f32) -> slider::Style {
let t = tokens(theme);
let engaged = matches!(status, slider::Status::Hovered | slider::Status::Dragged);
slider::Style {
rail: slider::Rail {
backgrounds: (fill.into(), t.raised.into()),
width: 4.0,
border: Border { radius: 2.0.into(), ..Border::default() },
width,
border: Border { radius: (width / 2.0).into(), ..Border::default() },
},
handle: slider::Handle {
shape: slider::HandleShape::Circle { radius: if engaged { 6.0 } else { 0.0 } },
shape: slider::HandleShape::Circle { radius: if engaged { width + 2.0 } else { 0.0 } },
background: t.fg.into(),
border_width: 0.0,
border_color: Color::TRANSPARENT,
+1
View File
@@ -2,6 +2,7 @@ pub mod anchor;
pub mod card;
pub mod drawer;
pub mod menu;
pub mod now_playing;
pub mod player_bar;
pub mod sheet;
pub mod sidebar;
+298
View File
@@ -0,0 +1,298 @@
//! Now Playing: the cover large over a blurred copy of itself, what's playing beside it and
//! the transport along the bottom. It takes the whole window, player bar included; the queue
//! and lyrics drawer opens at its right edge.
use std::sync::Arc;
use iced::widget::image::FilterMethod;
use iced::widget::{button, column, container, image, responsive, row, slider, space, stack, text};
use iced::{Alignment, ContentFit, Element, Fill, Padding, Size};
use ym_api::{Lyrics, Track};
use crate::app::Message;
use crate::covers::{self, Covers};
use crate::i18n::tr;
use crate::player::{Msg, Player, Repeat, Status};
use crate::screens::Loadable;
use crate::ui::icons::{Icon, icon, sized};
use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::theme::space as gap;
use crate::ui::{line, para};
use crate::widgets::anchor::anchor;
use crate::widgets::drawer::{self, Panel};
use crate::widgets::menu::{Anchor, Menu, Source, Target};
use crate::widgets::player_bar::clock;
/// The cover never grows past this, nor shrinks below the second.
const COVER_MAX: f32 = 520.0;
const COVER_MIN: f32 = 160.0;
/// Height the header, the seek bar and the controls take around the stage, with their gaps.
const CHROME: f32 = 236.0;
/// Below this stage width the Queue and Lyrics pills lose their labels.
const NARROW: f32 = 820.0;
pub struct Ctx<'a> {
pub t: &'static Tokens,
pub player: &'a Player,
pub liked: bool,
pub drawer: Option<Panel>,
pub covers: &'a Covers,
pub lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
}
pub fn view(cx: Ctx<'_>) -> Element<'_, Message> {
let Ctx { t, player, liked, drawer, covers, lyrics } = cx;
let Some(track) = player.track() else { return empty(t, player) };
let stage = responsive(move |area| stage(t, player, track, liked, drawer, covers, lyrics, area));
let mut body = row![stage].height(Fill);
if let Some(panel) = drawer {
body = body
.push(container(space()).width(1).height(Fill).style(theme::divider))
.push(drawer::view(t, panel, player, covers, lyrics));
}
stack![backdrop(track, covers), body].into()
}
#[allow(clippy::too_many_arguments)]
fn stage<'a>(
t: &'static Tokens,
p: &'a Player,
track: &'a Track,
liked: bool,
drawer: Option<Panel>,
covers: &Covers,
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
area: Size,
) -> Element<'a, Message> {
let side = (area.height - CHROME)
.min((area.width - 2.0 * gap::SECTION) * 0.45)
.clamp(COVER_MIN, COVER_MAX);
let cover = container(covers::view(covers, track.cover_url(covers::LARGE), track.hues(), side, radius::HERO))
.style(theme::stage_cover);
let middle = row![cover, info(t, p, track, lyrics)]
.spacing(48)
.align_y(Alignment::Center)
.height(Fill);
column![header(t), middle, seek(t, p), controls(t, p, track, liked, drawer, area.width < NARROW)]
.spacing(gap::L)
.padding(Padding::from([gap::XL, gap::SECTION]))
.width(Fill)
.height(Fill)
.into()
}
fn header<'a>(t: &'static Tokens) -> Element<'a, Message> {
row![
button(icon(Icon::Collapse, t.muted))
.padding(8)
.style(theme::icon_button(None))
.on_press(Message::ShowNowPlaying(false)),
line(tr("Now playing"), theme::MEDIUM, size::SMALL, t.muted),
]
.spacing(6)
.align_y(Alignment::Center)
.into()
}
/// Quality, title, artists, album, the notice when there is one, and the line being sung.
fn info<'a>(
t: &'static Tokens,
p: &'a Player,
track: &'a Track,
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
) -> Element<'a, Message> {
let mut info = column![].spacing(gap::M).width(Fill);
if let Some(stream) = p.stream() {
let label = if stream.preview { tr("Preview").to_owned() } else { stream.label() };
let ink = if stream.lossless() { t.accent } else { t.muted };
info = info.push(container(line(label, theme::MEDIUM, 11.5, ink)).padding([2, 6]).style(theme::badge));
}
info = info
.push(text(track.full_title()).font(theme::DISPLAY).size(size::DISPLAY_M).color(t.fg).line_height(1.2))
.push(line(track.artist_line(), theme::SEMIBOLD, size::SECTION, t.fg));
if let Some(album) = track.album.as_ref().filter(|a| !a.title.is_empty()) {
info = info.push(line(album.title.as_str(), theme::BODY, size::BODY, t.muted));
}
if let Some(notice) = &p.notice
&& matches!(p.status(), Status::Loading | Status::Paused)
{
info = info.push(para(notice.as_str(), size::META, t.like));
}
// Synced lyrics show the line being sung; the drawer has the rest.
if let Some(Loadable::Loaded(Some(l))) = lyrics
&& l.synced
&& let Some(i) = l.current(p.position())
{
let sung = if l.lines[i].text.is_empty() { "♪" } else { l.lines[i].text.as_str() };
let glance = text(sung).font(theme::SEMIBOLD).size(size::SECTION).color(t.accent).line_height(1.35);
info = info.push(container(glance).padding(Padding::default().top(gap::L)));
}
info.clip(true).into()
}
/// The bar and the times under its ends.
fn seek<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
let duration = p.duration().as_secs_f32();
let position = p.position().as_secs_f32().min(duration);
let bar: Element<'a, Message> = if duration > 0.0 {
slider(0.0..=duration, position, |v| Message::Player(Msg::SeekPreview(v)))
.on_release(Message::Player(Msg::SeekCommit))
.step(0.5_f32)
.width(Fill)
.style(theme::stage_seek_bar)
.into()
} else {
container(space())
.width(Fill)
.height(6)
.style(move |_| container::Style {
background: Some(t.raised.into()),
border: iced::Border { radius: 3.0.into(), ..Default::default() },
..Default::default()
})
.into()
};
let times = row![
line(clock(position), theme::BODY, size::SMALL, t.muted),
space().width(Fill),
line(clock(duration), theme::BODY, size::SMALL, t.muted),
];
column![bar, times].spacing(6).into()
}
/// Shuffle, previous, the play disc, next and repeat; then like, the track's menu, the
/// drawer's two panels and the volume.
fn controls<'a>(
t: &'static Tokens,
p: &'a Player,
track: &'a Track,
liked: bool,
drawer: Option<Panel>,
narrow: bool,
) -> Element<'a, Message> {
let send = Message::Player;
let round = |glyph: Icon, tint, on: Option<iced::Color>, msg: Message| {
button(sized(glyph, 20.0, tint)).padding(10).style(theme::icon_button(on)).on_press(msg)
};
let toggle = |glyph: Icon, on: bool, msg: Msg| {
round(glyph, if on { t.accent } else { t.fg }, on.then_some(t.accent), send(msg))
};
let glyph = match p.status() {
Status::Playing | Status::Loading => Icon::Pause,
Status::Paused | Status::Ended => Icon::Play,
};
let ink = if p.status() == Status::Loading { theme::mix(t.accent_ink, t.accent, 0.5) } else { t.accent_ink };
let disc = button(container(sized(glyph, 24.0, ink)).center(56))
.width(56)
.height(56)
.padding(0)
.style(theme::primary)
.on_press(send(Msg::Toggle));
let transport = row![
toggle(Icon::Shuffle, p.shuffle(), Msg::ToggleShuffle),
round(Icon::Previous, t.fg, None, send(Msg::Previous)),
disc,
round(Icon::Next, t.fg, None, send(Msg::Next)),
toggle(
if p.repeat == Repeat::One { Icon::RepeatOne } else { Icon::Repeat },
p.repeat != Repeat::Off,
Msg::CycleRepeat,
),
]
.spacing(10)
.align_y(Alignment::Center);
let heart = button(icon(
if liked { Icon::HeartFilled } else { Icon::Heart },
if liked { t.like } else { t.muted },
))
.padding(8)
.style(theme::icon_button(None))
.on_press(Message::LikeTrack(track.clone(), !liked));
// The anchor takes the click and reports where the button is, so the menu hangs under it.
let target = Target::Track { track: track.clone(), from: Source::PlayerBar };
let more = anchor(button(icon(Icon::More, t.muted)).padding(8).style(theme::icon_button(None)).on_press(Message::CloseMenu))
.on_press(move |bounds| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Below(bounds)))));
let pill = |glyph: Icon, panel: Panel, label: &'static str| -> Element<'a, Message> {
let on = drawer == Some(panel);
if narrow {
return button(icon(glyph, if on { t.accent } else { t.muted }))
.padding(8)
.style(theme::icon_button(on.then_some(t.accent)))
.on_press(Message::ToggleDrawer(panel))
.into();
}
let ink = if on { t.accent_ink } else { t.fg };
button(row![icon(glyph, ink), line(label, theme::MEDIUM, size::BODY, ink)].spacing(8).align_y(Alignment::Center))
.padding([7, 14])
.style(theme::chip(on))
.on_press(Message::ToggleDrawer(panel))
.into()
};
let volume = if p.muted { 0.0 } else { p.volume };
row![
transport,
space().width(Fill),
heart,
more,
pill(Icon::Queue, Panel::Queue, tr("Queue")),
pill(Icon::Lyrics, Panel::Lyrics, tr("Lyrics")),
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
.padding(8)
.style(theme::icon_button(None))
.on_press(send(Msg::ToggleMute)),
slider(0.0..=1.0, volume, |v| Message::Player(Msg::SetVolume(v)))
.step(0.01_f32)
.width(if narrow { 72 } else { 110 })
.style(theme::volume_bar),
]
.spacing(8)
.align_y(Alignment::Center)
.into()
}
/// The cover's blurred copy stretched over the window, washed with the ground. Until the
/// cover has loaded, its placeholder gradient stands in.
fn backdrop<'a>(track: &Track, covers: &Covers) -> Element<'a, Message> {
let art: Element<'a, Message> = match track.cover_url(covers::LARGE).and_then(|url| covers.backdrop(&url)) {
Some(handle) => image(handle)
.width(Fill)
.height(Fill)
.content_fit(ContentFit::Cover)
.filter_method(FilterMethod::Linear)
.into(),
None => {
let (h1, h2) = track.hues();
container(space()).width(Fill).height(Fill).style(theme::cover(h1, h2, 0.0)).into()
}
};
stack![art, container(space()).width(Fill).height(Fill).style(theme::backdrop_wash)].into()
}
/// Nothing to show: a station's first track on its way, or nothing queued at all.
fn empty<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
let (title, sub) = match (&p.notice, p.wave_station()) {
(None, Some(_)) => (tr("Loading…"), ""),
(Some(notice), _) => (tr("Can't play"), notice.as_str()),
(None, None) => (tr("Nothing playing"), tr("Pick a track to start")),
};
let message = column![
line(title, theme::DISPLAY, size::DISPLAY_S, t.fg),
para(sub, size::BODY, t.muted),
]
.spacing(gap::M);
container(column![header(t), container(message).center(Fill)].height(Fill))
.padding(Padding::from([gap::XL, gap::SECTION]))
.width(Fill)
.height(Fill)
.style(theme::app)
.into()
}
+8 -1
View File
@@ -70,7 +70,7 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
_ => (track.artist_line(), t.muted),
};
// A right-click on the cover or the title opens the track's menu.
// A click on the cover or the title opens Now Playing; a right-click, the track's menu.
let target = Target::Track { track: track.clone(), from: Source::PlayerBar };
let about = anchor(
row![
@@ -85,6 +85,7 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
.spacing(12)
.align_y(Alignment::Center),
)
.on_press(|_| Message::ShowNowPlaying(true))
.on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))));
row![
@@ -201,6 +202,12 @@ fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Eleme
let volume = if p.muted { 0.0 } else { p.volume };
items
.push(
button(icon(Icon::Expand, t.muted))
.padding(8)
.style(theme::icon_button(None))
.on_press_maybe(p.track().is_some().then_some(Message::ShowNowPlaying(true))),
)
.push(panel_button(Icon::Lyrics, Panel::Lyrics))
.push(panel_button(Icon::Queue, Panel::Queue))
.push(