feat: add an option to colour the UI from the playing track's cover

A new Settings section in the sidebar turns it on and off. It is saved
in settings.toml, apart from the login, so logging out keeps it.

Each theme colour keeps the lightness it has in the brand palette and
only takes the cover's dominant hue, so text stays readable on any
cover. Covers with too little colour, and nothing playing, use the
brand palette. Slint cannot animate a global, so a timer in Rust fades
the Theme colours to the new palette over 800 ms.
This commit is contained in:
Ansho Rei
2026-11-04 03:45:17 +01:00
parent a04b7ee37f
commit 3cb810bbd5
6 changed files with 730 additions and 36 deletions
+193 -15
View File
@@ -8,7 +8,7 @@ use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use anyhow::Result;
use lru::LruCache;
@@ -16,7 +16,8 @@ use slint::{Color, ComponentHandle, Image, ModelRc, Rgb8Pixel, SharedPixelBuffer
use tokio::runtime::Handle;
use tokio::sync::Semaphore;
use crate::config::{self, Config};
use crate::config::{self, Config, Settings};
use crate::palette::{Lab, Palette, Role, Tone};
use crate::player::{Player, PlayerEvent};
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
@@ -70,15 +71,17 @@ enum Section {
Artists,
Playlists,
Search,
Settings,
}
const SECTIONS: [Section; 6] = [
const SECTIONS: [Section; 7] = [
Section::Recent,
Section::Random,
Section::Albums,
Section::Artists,
Section::Playlists,
Section::Search,
Section::Settings,
];
impl Section {
@@ -90,6 +93,7 @@ impl Section {
Section::Artists => "Artists",
Section::Playlists => "Playlists",
Section::Search => "Search",
Section::Settings => "Settings",
}
}
}
@@ -101,6 +105,24 @@ enum Target {
Playlist(String),
/// Index into the page's `songs`.
Song(usize),
Setting(Setting),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Setting {
AlbumArtColours,
}
/// How long the UI takes to change from one palette to the next.
const FADE: Duration = Duration::from_millis(800);
/// The palette on screen and the one it is fading towards.
struct Fade {
from: Palette,
to: Palette,
shown: Palette,
started: Instant,
timer: Timer,
}
#[derive(Clone, Debug)]
@@ -161,6 +183,9 @@ type CoverKey = (String, u32);
struct Covers {
images: LruCache<CoverKey, Image>,
/// Per cover id, whatever size it was decoded at. None for a cover with
/// too little colour to base a palette on.
tones: LruCache<String, Option<Tone>>,
pending: HashSet<CoverKey>,
failed: HashSet<CoverKey>,
limit: Arc<Semaphore>,
@@ -191,6 +216,8 @@ pub struct App {
scrobbled: bool,
login_focus: i32,
toast_timer: Timer,
settings: Settings,
fade: Fade,
}
impl App {
@@ -221,6 +248,7 @@ impl App {
queue_range: (0, 0),
covers: Covers {
images: LruCache::new(NonZeroUsize::new(400).unwrap()),
tones: LruCache::new(NonZeroUsize::new(400).unwrap()),
pending: HashSet::new(),
failed: HashSet::new(),
limit: Arc::new(Semaphore::new(6)),
@@ -235,6 +263,14 @@ impl App {
scrobbled: false,
login_focus: 0,
toast_timer: Timer::default(),
settings: config::load_settings(),
fade: Fade {
from: Palette::brand(),
to: Palette::brand(),
shown: Palette::brand(),
started: Instant::now(),
timer: Timer::default(),
},
}
}
@@ -354,6 +390,7 @@ impl App {
.set_server_label(format!("{} on {}", client.user(), host).into());
self.client = Some(client);
self.covers.images.clear();
self.covers.tones.clear();
self.covers.pending.clear();
self.covers.failed.clear();
for stack in &mut self.stacks {
@@ -571,7 +608,7 @@ impl App {
self.ui.set_section(index as i32);
if self.stacks[index].is_empty() {
let section = SECTIONS[index];
let list = matches!(section, Section::Artists | Section::Search);
let list = matches!(section, Section::Artists | Section::Search | Section::Settings);
let mut page = self.new_page(Source::Section(section), section.label().to_string(), list, None);
if section == Section::Search {
page.loading = false;
@@ -739,6 +776,106 @@ impl App {
let songs = page.songs.clone();
self.play_songs(songs, index);
}
Target::Setting(s) => self.toggle_setting(s),
}
}
// ---------------------------------------------------------------- settings
fn toggle_setting(&mut self, setting: Setting) {
match setting {
Setting::AlbumArtColours => self.settings.album_art_colours = !self.settings.album_art_colours,
}
if let Err(e) = config::save_settings(&self.settings) {
self.toast(format!("Could not save settings: {e:#}"));
}
let entries = settings_data(&self.settings).entries;
let index = SECTIONS.iter().position(|s| *s == Section::Settings).unwrap_or(0);
if let Some(page) = self.stacks[index].first_mut() {
page.entries = entries;
if self.section == index {
self.sync_items(true);
}
}
self.update_theme();
}
// ---------------------------------------------------------------- theme
/// The palette the UI should show: from the playing track's cover when
/// that setting is on, else the brand palette. None while the cover is
/// still loading, to keep the current palette rather than flash the brand.
fn wanted_palette(&mut self) -> Option<Palette> {
if !self.settings.album_art_colours {
return Some(Palette::brand());
}
let Some(id) = self
.current
.and_then(|i| self.queue.get(i))
.and_then(|s| s.cover_art.clone())
else {
return Some(Palette::brand());
};
match self.covers.tones.get(&id) {
Some(Some(tone)) => Some(Palette::from_tone(*tone)),
Some(None) => Some(Palette::brand()),
None if self.covers.failed.iter().any(|(f, _)| *f == id) => Some(Palette::brand()),
None => None,
}
}
fn update_theme(&mut self) {
let Some(target) = self.wanted_palette() else { return };
if target == self.fade.to {
return;
}
log::debug!(
"fading to a new palette, accent {:?}",
target.get(Role::Accent).to_rgb()
);
// From whatever is on screen, so a fade cut short by a skip carries on
// from where it got to instead of jumping.
self.fade.from = self.fade.shown;
self.fade.to = target;
self.fade.started = Instant::now();
if !self.fade.timer.running() {
self.fade
.timer
.start(slint::TimerMode::Repeated, Duration::from_millis(16), || {
with_app(|app| app.fade_step())
});
}
}
fn fade_step(&mut self) {
let t = (self.fade.started.elapsed().as_secs_f32() / FADE.as_secs_f32()).min(1.0);
let eased = t * t * (3.0 - 2.0 * t);
self.fade.shown = self.fade.from.mix(&self.fade.to, eased);
self.apply_palette();
if t >= 1.0 {
self.fade.timer.stop();
}
}
fn apply_palette(&self) {
let theme = self.ui.global::<Theme>();
for role in Role::ALL {
let c = color(self.fade.shown.get(role));
match role {
Role::Bg => theme.set_bg(c),
Role::Panel => theme.set_panel(c),
Role::Raised => theme.set_raised(c),
Role::Line => theme.set_line(c),
Role::Text => theme.set_text(c),
Role::Muted => theme.set_muted(c),
Role::Faint => theme.set_faint(c),
Role::Accent => theme.set_accent(c),
Role::OnAccent => theme.set_on_accent(c),
Role::Highlight => theme.set_highlight(c),
Role::Focus => theme.set_focus(c),
Role::Glow => theme.set_glow(c),
Role::LoginGlow => theme.set_login_glow(c),
}
}
}
@@ -778,6 +915,11 @@ impl App {
// ---------------------------------------------------------------- loading
fn load(&mut self, page_id: u64, source: Source) {
if matches!(source, Source::Section(Section::Settings)) {
let data = settings_data(&self.settings);
self.page_loaded(page_id, Ok(data), true);
return;
}
let Some(client) = self.client.clone() else { return };
match source {
Source::Section(Section::Recent) => self.spawn(
@@ -815,7 +957,7 @@ impl App {
async move { Ok(playlists_data(client.playlists().await?)) },
move |app, r| app.page_loaded(page_id, r, true),
),
Source::Section(Section::Search) => {}
Source::Section(Section::Search | Section::Settings) => {}
Source::Search(q) => self.spawn(
async move { Ok(search_data(client.search(&q).await?)) },
move |app, r| app.page_loaded(page_id, r, true),
@@ -1111,6 +1253,7 @@ impl App {
.map(|e| &e.target);
match target {
Some(Target::Song(_)) => hints.push(h("A", "Play")),
Some(Target::Setting(_)) => hints.push(h("A", "Change")),
Some(_) => hints.push(h("A", "Open")),
None if self.current_page().is_some_and(|p| p.error.is_some()) => {
hints.push(h("A", "Try again"))
@@ -1199,23 +1342,31 @@ impl App {
b
}
};
let buf = tokio::task::spawn_blocking(move || decode_cover(&bytes, px)).await??;
Ok(buf)
let decoded = tokio::task::spawn_blocking(move || decode_cover(&bytes, px)).await??;
Ok(decoded)
},
move |app, r| app.cover_loaded(key, r),
);
None
}
fn cover_loaded(&mut self, key: CoverKey, result: Result<SharedPixelBuffer<Rgb8Pixel>>) {
fn cover_loaded(&mut self, key: CoverKey, result: Result<(SharedPixelBuffer<Rgb8Pixel>, Option<Tone>)>) {
self.covers.pending.remove(&key);
match result {
Ok(buf) => {
Ok((buf, tone)) => {
self.covers.images.put(key.clone(), Image::from_rgb8(buf));
// The first size decoded decides: other sizes give a tone that
// differs in the last digits, which would restart the fade.
if !self.covers.tones.contains(&key.0) {
log::debug!("cover {} tone {tone:?}", key.0);
self.covers.tones.put(key.0.clone(), tone);
}
}
Err(e) => {
log::debug!("cover {} failed: {e:#}", key.0);
self.covers.failed.insert(key);
// The playing track's cover failing means the brand palette.
self.update_theme();
return;
}
}
@@ -1348,6 +1499,7 @@ impl App {
)
}
Target::Artist(_) => self.toast("Open the artist to queue one of their albums".into()),
Target::Setting(_) => {}
}
}
@@ -1453,6 +1605,7 @@ impl App {
}
}
self.render_progress();
self.update_theme();
}
// ---------------------------------------------------------------- now playing
@@ -1635,6 +1788,23 @@ fn song_entry(s: &Song, index: usize) -> Entry {
}
}
fn settings_data(s: &Settings) -> PageData {
let on_off = |on: bool| if on { "On" } else { "Off" }.to_string();
PageData {
entries: vec![Entry {
title: "Colours from album art".to_string(),
subtitle: "Tint the interface with the cover of the playing track".to_string(),
detail: on_off(s.album_art_colours),
number: String::new(),
cover: None,
round: false,
show_art: false,
target: Target::Setting(Setting::AlbumArtColours),
}],
..Default::default()
}
}
fn search_data(r: SearchResult) -> PageData {
let mut entries: Vec<Entry> = r.artist.into_iter().map(artist_entry).collect();
entries.extend(r.album.into_iter().map(|a| Entry {
@@ -1673,19 +1843,27 @@ fn bucket(px: f32) -> u32 {
SIZES.into_iter().find(|&s| px <= s as f32).unwrap_or(1536)
}
fn decode_cover(bytes: &[u8], px: u32) -> Result<SharedPixelBuffer<Rgb8Pixel>> {
/// Decodes a cover at `px` and works out its tone for the album art palette.
fn decode_cover(bytes: &[u8], px: u32) -> Result<(SharedPixelBuffer<Rgb8Pixel>, Option<Tone>)> {
let img = image::load_from_memory(bytes)?;
let img = if img.width() > px || img.height() > px {
img.resize(px, px, image::imageops::FilterType::Triangle)
} else {
img
};
// A small copy is plenty to find the dominant hue.
let small = img
.resize_exact(24, 24, image::imageops::FilterType::Triangle)
.to_rgb8();
let tone = crate::palette::tone(small.as_raw());
let rgb = img.to_rgb8();
Ok(SharedPixelBuffer::clone_from_slice(
rgb.as_raw(),
rgb.width(),
rgb.height(),
))
let buf = SharedPixelBuffer::clone_from_slice(rgb.as_raw(), rgb.width(), rgb.height());
Ok((buf, tone))
}
fn color(lab: Lab) -> Color {
let [r, g, b] = lab.to_rgb();
Color::from_rgb_u8(r, g, b)
}
fn sanitize(id: &str) -> String {