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
+2
View File
@@ -23,6 +23,8 @@ Some servers refuse token logins (Subsonic error 41), Nextcloud Music among them
Covers are cached in `~/.cache/remus/covers`.
Preferences live apart from the login, in `~/.config/remus/settings.toml`, so logging in again keeps them. Change them under Settings in the sidebar. "Colours from album art" tints the interface with the cover of the playing track and fades to the next one when the track changes. It is off by default.
## Install on SteamOS
Build the bundle on any Linux machine with Flatpak:
+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 {
+62 -6
View File
@@ -1,7 +1,7 @@
use std::fs;
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use directories::ProjectDirs;
@@ -76,12 +76,53 @@ pub fn load() -> Result<Option<Config>> {
pub fn save(cfg: &Config) -> Result<()> {
let path = config_path().context("no config directory")?;
write_atomic(&path, &toml::to_string(cfg)?)?;
log::info!("saved login to {}", path.display());
Ok(())
}
/// Preferences. Kept apart from the login, so logging out does not reset them.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// Tint the UI with the colours of the playing track's cover.
pub album_art_colours: bool,
}
fn settings_path() -> Option<PathBuf> {
dirs().map(|d| d.config_dir().join("settings.toml"))
}
/// The saved settings, or the defaults when there are none or they cannot be read.
pub fn load_settings() -> Settings {
let Some(path) = settings_path() else {
return Settings::default();
};
match fs::read_to_string(&path) {
Ok(text) => toml::from_str(&text).unwrap_or_else(|e| {
log::warn!("ignoring {}: {e}", path.display());
Settings::default()
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Settings::default(),
Err(e) => {
log::warn!("reading {}: {e}", path.display());
Settings::default()
}
}
}
pub fn save_settings(s: &Settings) -> Result<()> {
let path = settings_path().context("no config directory")?;
write_atomic(&path, &toml::to_string(s)?)
}
/// Writes aside, syncs, then renames over the old file, so a power cut
/// mid-save leaves either the old file or the new one, never a torn one.
/// Owner-only, since the login file holds a token.
fn write_atomic(path: &Path, text: &str) -> Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let text = toml::to_string(cfg)?;
// Write aside, sync, then rename over the old file, so a power cut
// mid-save leaves either the old login or the new one, never a torn file.
let tmp = path.with_extension("toml.tmp");
let mut f = fs::OpenOptions::new()
.write(true)
@@ -92,13 +133,12 @@ pub fn save(cfg: &Config) -> Result<()> {
.with_context(|| format!("writing {}", tmp.display()))?;
f.write_all(text.as_bytes())?;
f.sync_all()?;
fs::rename(&tmp, &path).with_context(|| format!("replacing {}", path.display()))?;
fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))?;
if let Some(dir) = path.parent()
&& let Ok(d) = fs::File::open(dir)
{
let _ = d.sync_all();
}
log::info!("saved login to {}", path.display());
Ok(())
}
@@ -139,4 +179,20 @@ mod tests {
let text = toml::to_string(&cfg).unwrap();
assert!(!text.contains("salt") && !text.contains("token"), "{text}");
}
#[test]
fn settings_default_when_fields_are_missing() {
let s: Settings = toml::from_str("").unwrap();
assert_eq!(s, Settings::default());
assert!(!s.album_art_colours);
}
#[test]
fn settings_round_trip() {
let s = Settings {
album_art_colours: true,
};
let back: Settings = toml::from_str(&toml::to_string(&s).unwrap()).unwrap();
assert_eq!(back, s);
}
}
+1
View File
@@ -4,6 +4,7 @@ mod app;
mod config;
mod devscript;
mod input;
mod palette;
mod player;
mod subsonic;
+452
View File
@@ -0,0 +1,452 @@
//! The UI's colours, either the brand palette or one derived from album art.
//!
//! A cover only contributes a hue and how colourful it is. Each role keeps the
//! lightness it has in the brand palette, so text stays readable whatever the
//! cover looks like. Colours are mixed in OKLab, where equal steps look equal.
/// A colour in OKLab: lightness, then the green-red and blue-yellow axes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Lab {
pub l: f32,
pub a: f32,
pub b: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
Bg,
Panel,
Raised,
Line,
Text,
Muted,
Faint,
Accent,
OnAccent,
Highlight,
Focus,
Glow,
LoginGlow,
}
impl Role {
pub const ALL: [Role; 13] = [
Role::Bg,
Role::Panel,
Role::Raised,
Role::Line,
Role::Text,
Role::Muted,
Role::Faint,
Role::Accent,
Role::OnAccent,
Role::Highlight,
Role::Focus,
Role::Glow,
Role::LoginGlow,
];
/// The brand colour for this role. Must match the defaults of `Theme` in
/// ui/app.slint, which is what the UI shows before any palette is applied.
fn brand(self) -> u32 {
match self {
Role::Bg => 0x140b0c,
Role::Panel => 0x1d1012,
Role::Raised => 0x2b181b,
Role::Line => 0x42272b,
Role::Text | Role::OnAccent | Role::Focus => 0xfaebda,
Role::Muted => 0xbea999,
Role::Faint => 0x80685f,
Role::Accent => 0xa51d2d,
Role::Highlight => 0xe8757b,
Role::Glow => 0x2a0b11,
Role::LoginGlow => 0x3a0b13,
}
}
/// Cream text and focus rings stay cream on every palette.
fn follows_cover(self) -> bool {
!matches!(self, Role::Text | Role::OnAccent | Role::Focus)
}
}
/// What a cover contributes: its dominant hue in radians and its chroma.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tone {
pub hue: f32,
pub chroma: f32,
}
/// The minimum contrast for text, WCAG AA for normal text.
const MIN_CONTRAST: f32 = 4.5;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Palette([Lab; Role::ALL.len()]);
impl Palette {
pub fn brand() -> Palette {
Palette(Role::ALL.map(|r| Lab::from_rgb(r.brand())))
}
/// The palette for a cover with this tone.
pub fn from_tone(tone: Tone) -> Palette {
let brand = Palette::brand();
// A dull cover gives a dull palette, a vivid one the brand's own vividness.
let vividness = (tone.chroma / 0.12).clamp(0.5, 1.0);
let mut roles = brand.0;
for (i, role) in Role::ALL.into_iter().enumerate() {
if !role.follows_cover() {
continue;
}
let b = brand.0[i];
// Hue replaced outright: mixing towards the brand in OKLab would pass
// through grey for a cover on the far side of the wheel from maroon.
roles[i] = Lab::from_lch(b.l, b.chroma() * vividness, tone.hue).into_gamut();
}
let mut p = Palette(roles);
p.ensure_contrast();
p
}
pub fn get(&self, role: Role) -> Lab {
self.0[role as usize]
}
/// The palette `t` of the way from `self` to `other`.
pub fn mix(&self, other: &Palette, t: f32) -> Palette {
// Exact at the ends, so a finished fade lands on the target itself.
if t <= 0.0 {
return *self;
}
if t >= 1.0 {
return *other;
}
let mut out = self.0;
for (o, (a, b)) in out.iter_mut().zip(self.0.iter().zip(other.0.iter())) {
*o = a.mix(*b, t);
}
Palette(out)
}
/// Darkens the accent fill and lightens the highlight until cream text on
/// the fill and the highlight on the background are both readable.
fn ensure_contrast(&mut self) {
let text = self.get(Role::OnAccent);
let bg = self.get(Role::Bg);
let accent = &mut self.0[Role::Accent as usize];
while contrast(*accent, text) < MIN_CONTRAST && accent.l > 0.2 {
*accent = accent.with_lightness(accent.l - 0.01).into_gamut();
}
let hl = &mut self.0[Role::Highlight as usize];
while contrast(*hl, bg) < MIN_CONTRAST && hl.l < 0.95 {
*hl = hl.with_lightness(hl.l + 0.01).into_gamut();
}
}
}
/// The dominant tone of an RGB image (3 bytes a pixel), or None when it has
/// too little colour to base a palette on: greyscale, black and white, sepia
/// that is nearly grey.
pub fn tone(rgb: &[u8]) -> Option<Tone> {
const BINS: usize = 24;
// Below this a pixel's hue is mostly compression noise.
const CHROMATIC: f32 = 0.04;
let mut weight = [0f32; BINS];
let mut sum_a = [0f32; BINS];
let mut sum_b = [0f32; BINS];
let mut sum_c2 = [0f32; BINS];
let (mut pixels, mut chromatic) = (0usize, 0usize);
for px in rgb.as_chunks::<3>().0 {
pixels += 1;
let lab = Lab::from_rgb(u32::from_be_bytes([0, px[0], px[1], px[2]]));
let c = lab.chroma();
// Near black and near white carry no usable hue either.
if c < CHROMATIC || lab.l < 0.12 || lab.l > 0.97 {
continue;
}
chromatic += 1;
let hue = lab.b.atan2(lab.a).rem_euclid(std::f32::consts::TAU);
let bin = ((hue / std::f32::consts::TAU) * BINS as f32) as usize % BINS;
// Weighted by chroma, so a small vivid logo beats a large grey field.
weight[bin] += c;
sum_a[bin] += lab.a;
sum_b[bin] += lab.b;
sum_c2[bin] += c * c;
}
if pixels == 0 || chromatic * 50 < pixels {
return None;
}
let around = |i: usize| [(i + BINS - 1) % BINS, i, (i + 1) % BINS];
let best = (0..BINS)
.max_by(|&x, &y| {
let wx: f32 = around(x).iter().map(|&j| weight[j]).sum();
let wy: f32 = around(y).iter().map(|&j| weight[j]).sum();
wx.total_cmp(&wy)
})
.unwrap_or(0);
let (mut a, mut b, mut w, mut c2) = (0f32, 0f32, 0f32, 0f32);
for j in around(best) {
a += sum_a[j];
b += sum_b[j];
w += weight[j];
c2 += sum_c2[j];
}
Some(Tone {
hue: b.atan2(a),
chroma: c2 / w,
})
}
/// WCAG contrast ratio between two colours.
pub fn contrast(x: Lab, y: Lab) -> f32 {
let (lx, ly) = (x.luminance(), y.luminance());
(lx.max(ly) + 0.05) / (lx.min(ly) + 0.05)
}
impl Lab {
pub fn from_rgb(rgb: u32) -> Lab {
let [_, r, g, b] = rgb.to_be_bytes();
let (r, g, b) = (to_linear(r), to_linear(g), to_linear(b));
let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
Lab {
l: 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
a: 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
b: 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
}
}
fn from_lch(l: f32, c: f32, hue: f32) -> Lab {
Lab {
l,
a: c * hue.cos(),
b: c * hue.sin(),
}
}
fn linear(self) -> [f32; 3] {
let l = (self.l + 0.396_337_78 * self.a + 0.215_803_76 * self.b).powi(3);
let m = (self.l - 0.105_561_346 * self.a - 0.063_854_17 * self.b).powi(3);
let s = (self.l - 0.089_484_18 * self.a - 1.291_485_5 * self.b).powi(3);
[
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
]
}
/// The sRGB colour as 8-bit channels, clipped to the displayable range.
pub fn to_rgb(self) -> [u8; 3] {
self.linear().map(from_linear)
}
pub fn chroma(self) -> f32 {
self.a.hypot(self.b)
}
fn luminance(self) -> f32 {
let [r, g, b] = self.to_rgb().map(to_linear);
0.2126 * r + 0.7152 * g + 0.0722 * b
}
fn mix(self, other: Lab, t: f32) -> Lab {
Lab {
l: self.l + (other.l - self.l) * t,
a: self.a + (other.a - self.a) * t,
b: self.b + (other.b - self.b) * t,
}
}
fn with_lightness(self, l: f32) -> Lab {
Lab { l, ..self }
}
fn in_gamut(self) -> bool {
self.linear().iter().all(|&c| (-0.0005..=1.0005).contains(&c))
}
/// Lowers the chroma, keeping lightness and hue, until sRGB can show it.
fn into_gamut(self) -> Lab {
if self.in_gamut() {
return self;
}
let (mut lo, mut hi) = (0f32, 1f32);
for _ in 0..20 {
let mid = (lo + hi) / 2.0;
let c = Lab {
a: self.a * mid,
b: self.b * mid,
..self
};
if c.in_gamut() {
lo = mid;
} else {
hi = mid;
}
}
Lab {
a: self.a * lo,
b: self.b * lo,
..self
}
}
}
fn to_linear(c: u8) -> f32 {
let c = c as f32 / 255.0;
if c <= 0.040_45 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
fn from_linear(c: f32) -> u8 {
let c = c.clamp(0.0, 1.0);
let s = if c <= 0.003_130_8 {
c * 12.92
} else {
1.055 * c.powf(1.0 / 2.4) - 0.055
};
(s * 255.0).round() as u8
}
#[cfg(test)]
mod tests {
use super::*;
use std::f32::consts::TAU;
fn hex(rgb: [u8; 3]) -> u32 {
u32::from_be_bytes([0, rgb[0], rgb[1], rgb[2]])
}
/// A 24x24 image filled by `f(x, y)`.
fn image(f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
(0..24 * 24).flat_map(|i| f(i % 24, i / 24)).collect()
}
fn hue_distance(a: f32, b: f32) -> f32 {
let d = (a - b).rem_euclid(TAU);
d.min(TAU - d)
}
#[test]
fn brand_palette_round_trips_exactly() {
let p = Palette::brand();
for role in Role::ALL {
assert_eq!(hex(p.get(role).to_rgb()), role.brand(), "{role:?}");
}
}
#[test]
fn contrast_holds_for_every_hue_and_chroma() {
for step in 0..72 {
for chroma in [0.02, 0.06, 0.12, 0.25, 0.4] {
let tone = Tone {
hue: step as f32 * TAU / 72.0,
chroma,
};
let p = Palette::from_tone(tone);
let cases = [
(Role::Text, Role::Bg),
(Role::Text, Role::Panel),
(Role::Text, Role::Raised),
(Role::OnAccent, Role::Accent),
(Role::Highlight, Role::Bg),
(Role::Muted, Role::Bg),
];
for (fg, bg) in cases {
let c = contrast(p.get(fg), p.get(bg));
assert!(c >= MIN_CONTRAST, "{fg:?} on {bg:?} is {c:.2} for {tone:?}");
}
}
}
}
#[test]
fn cover_palette_keeps_cream_text() {
let p = Palette::from_tone(Tone { hue: 4.0, chroma: 0.2 });
for role in [Role::Text, Role::OnAccent, Role::Focus] {
assert_eq!(p.get(role), Palette::brand().get(role));
}
}
#[test]
fn cover_palette_takes_the_cover_hue() {
let blue = Lab::from_rgb(0x2050d0);
let tone = Tone {
hue: blue.b.atan2(blue.a),
chroma: blue.chroma(),
};
let accent = Palette::from_tone(tone).get(Role::Accent);
let brand = Palette::brand().get(Role::Accent);
let hue = |l: Lab| l.b.atan2(l.a);
assert!(hue_distance(hue(accent), tone.hue) < hue_distance(hue(brand), tone.hue));
assert!(hue_distance(hue(accent), tone.hue) < 0.6);
}
#[test]
fn cover_opposite_the_brand_hue_stays_colourful() {
let cyan = Lab::from_rgb(0x30b8d8);
let tone = Tone {
hue: cyan.b.atan2(cyan.a),
chroma: cyan.chroma(),
};
let accent = Palette::from_tone(tone).get(Role::Accent);
assert!(accent.chroma() > 0.08, "accent went grey: {accent:?}");
}
#[test]
fn saturated_cover_gives_its_hue() {
let t = tone(&image(|_, _| [200, 30, 40])).expect("red has a tone");
let red = Lab::from_rgb(0xc81e28);
assert!(hue_distance(t.hue, red.b.atan2(red.a)) < 0.15);
assert!(t.chroma > 0.15);
}
#[test]
fn dark_and_light_covers_still_give_a_tone() {
assert!(tone(&image(|_, _| [40, 20, 70])).is_some());
assert!(tone(&image(|_, _| [240, 220, 160])).is_some());
}
#[test]
fn greyscale_cover_has_no_tone() {
let grey = image(|x, y| {
let v = ((x * 7 + y * 3) % 256) as u8;
[v, v, v]
});
assert_eq!(tone(&grey), None);
assert_eq!(tone(&image(|x, _| if x < 12 { [0; 3] } else { [255; 3] })), None);
assert_eq!(tone(&[]), None);
}
#[test]
fn small_vivid_area_beats_a_grey_field() {
let img = image(|x, y| if x < 5 && y < 5 { [220, 40, 40] } else { [128, 128, 128] });
let t = tone(&img).expect("the red patch is enough");
let red = Lab::from_rgb(0xdc2828);
assert!(hue_distance(t.hue, red.b.atan2(red.a)) < 0.15);
}
#[test]
fn dominant_hue_wins_over_a_minority() {
let img = image(|x, _| if x < 18 { [30, 60, 200] } else { [220, 40, 40] });
let t = tone(&img).unwrap();
let blue = Lab::from_rgb(0x1e3cc8);
assert!(hue_distance(t.hue, blue.b.atan2(blue.a)) < 0.15);
}
#[test]
fn mixing_palettes_hits_both_ends() {
let a = Palette::brand();
let b = Palette::from_tone(Tone { hue: 2.5, chroma: 0.15 });
assert_eq!(a.mix(&b, 0.0), a);
assert_eq!(a.mix(&b, 1.0), b);
let mid = a.mix(&b, 0.5).get(Role::Accent);
let (x, y) = (a.get(Role::Accent), b.get(Role::Accent));
assert!((mid.l - (x.l + y.l) / 2.0).abs() < 1e-6);
}
}
+20 -15
View File
@@ -46,21 +46,27 @@ export struct Hint { key: string, label: string }
export global Theme {
in-out property <float> s: 1.0;
// Warm darks and cream text, from the logo's maroon (#5a0712) and cream.
out property <color> bg: #140b0c;
out property <color> panel: #1d1012;
out property <color> raised: #2b181b;
out property <color> line: #42272b;
out property <color> text: #faebda;
out property <color> muted: #bea999;
out property <color> faint: #80685f;
// The brand palette: warm darks and cream text, from the logo's maroon
// (#5a0712) and cream. The app replaces these with colours from the album
// art when that setting is on; src/palette.rs must keep the same defaults.
in-out property <color> bg: #140b0c;
in-out property <color> panel: #1d1012;
in-out property <color> raised: #2b181b;
in-out property <color> line: #42272b;
in-out property <color> text: #faebda;
in-out property <color> muted: #bea999;
in-out property <color> faint: #80685f;
// Filled surfaces: the current section, buttons, the playing badge.
out property <color> accent: #a51d2d;
out property <color> on-accent: #faebda;
in-out property <color> accent: #a51d2d;
in-out property <color> on-accent: #faebda;
// Accent for text and thin lines, where the fill colour is too dark to read.
out property <color> highlight: #e8757b;
in-out property <color> highlight: #e8757b;
// Ring around whatever has focus.
out property <color> focus: #faebda;
in-out property <color> focus: #faebda;
// Tops of the sidebar and login backgrounds.
in-out property <color> glow: #2a0b11;
in-out property <color> login-glow: #3a0b13;
// Not part of the palette: errors stay red whatever the album art.
out property <color> error: #f0605d;
out property <string> serif: "Noto Serif";
}
@@ -382,8 +388,7 @@ component Sidebar inherits Rectangle {
in property <string> footer;
callback clicked(int);
// A hint of the logo's maroon at the top, fading into the panel.
background: @linear-gradient(180deg, #2a0b11 0%, Theme.panel 55%);
background: @linear-gradient(180deg, Theme.glow 0%, Theme.panel 55%);
VerticalLayout {
padding: 26px * Theme.s;
@@ -653,7 +658,7 @@ component LoginView inherits Rectangle {
}
}
background: @radial-gradient(circle, #3a0b13 0%, Theme.bg 70%);
background: @radial-gradient(circle, Theme.login-glow 0%, Theme.bg 70%);
Rectangle {
width: min(560px * Theme.s, parent.width - 40px * Theme.s);