| {
+ let mine = *counts.get(self.name.as_ref()?).filter(|n| **n > 0)?;
+ Some(1 + counts.values().filter(|n| **n > mine).count() as u64)
+ };
+ ArtistHighlight {
+ plays: self.total(),
+ rank: rank(&self.by_name),
+ rank_month: rank(&self.this_month),
+ }
+ }
}
/// A time some days back, for tests that place plays relative to now.
@@ -807,6 +875,68 @@ mod tests {
assert_eq!(count.total(), 2);
}
+ #[test]
+ fn an_artist_page_highlights_a_top_rank_or_else_the_plays() {
+ let line = |plays, rank, rank_month| {
+ ArtistHighlight {
+ plays,
+ rank,
+ rank_month,
+ }
+ .line()
+ };
+ assert_eq!(line(0, None, None), None);
+ assert_eq!(
+ line(399, Some(2), Some(2)).as_deref(),
+ Some("Your #2 artist")
+ );
+ assert_eq!(
+ line(399, Some(5), Some(3)).as_deref(),
+ Some("Your #3 artist this month")
+ );
+ assert_eq!(
+ line(80, Some(40), Some(3)).as_deref(),
+ Some("Your #3 artist this month")
+ );
+ assert_eq!(line(80, Some(4), None).as_deref(), Some("Your #4 artist"));
+ assert_eq!(
+ line(80, Some(40), Some(12)).as_deref(),
+ Some("80 total plays by you")
+ );
+ assert_eq!(
+ line(1, Some(40), None).as_deref(),
+ Some("1 total play by you")
+ );
+ }
+
+ #[test]
+ fn an_artist_ranks_against_every_artist_and_this_month_apart() {
+ let n = now();
+ let mut count = ArtistCount {
+ month_start: at_hour(&n, 10, 0),
+ ..ArtistCount::default()
+ };
+ for (song, artist, days) in [
+ ("a", "Top", 40),
+ ("a", "Top", 40),
+ ("a", "Top", 40),
+ ("b", "Mine", 40),
+ ("b", "Mine", 2),
+ ("c", "Fresh", 1),
+ ] {
+ count.add("id-Mine", &play(song, artist, at_hour(&n, days, 12)));
+ }
+ assert_eq!(
+ count.highlight(),
+ ArtistHighlight {
+ plays: 2,
+ rank: Some(2),
+ // This month Mine and Fresh have one play each: a shared first place.
+ rank_month: Some(1),
+ }
+ );
+ }
+
#[test]
fn the_report_says_whether_anything_was_imported() {
let n = now();
diff --git a/crates/refryt/src/lyrics/better_lyrics.rs b/crates/refryt/src/lyrics/better_lyrics.rs
new file mode 100644
index 0000000..0d15941
--- /dev/null
+++ b/crates/refryt/src/lyrics/better_lyrics.rs
@@ -0,0 +1,204 @@
+//! BetterLyrics: Apple Music's timed lyrics, through the API behind the BetterLyrics browser
+//! extension.
+//!
+//! One GET keyed on the title, artist, length and album, answering `{"ttml": …}` with Apple's
+//! TTML: a `` per line, word ``s inside, background vocals in a
+//! ``. Only songs its cache already holds are answered: since late 2026
+//! anything else gets 401 "API key required", which counts as a miss here.
+//!
+//! Lines only for now: the words' own timing is read past, and each line lights up as a whole.
+
+use anyhow::{Context, Result};
+
+use crate::model::{LyricLine, Lyrics, Track};
+
+const ENDPOINT: &str = "https://lyrics-api.boidu.dev/getLyrics";
+
+pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> {
+ let artist = track.artist_line();
+ let mut query: Vec<(&str, String)> = vec![("s", track.title.clone()), ("a", artist)];
+ if let Some(seconds) = track.duration.filter(|d| *d > 0) {
+ query.push(("d", seconds.to_string()));
+ }
+ if let Some(album) = track.album.as_deref().filter(|a| !a.is_empty()) {
+ query.push(("al", album.to_owned()));
+ }
+ let response = http
+ .get(ENDPOINT)
+ .query(&query)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .context("BetterLyrics")?;
+ // Not in its cache (401), or no lyrics at all (404): a miss, not a failure.
+ if matches!(response.status().as_u16(), 401 | 404) {
+ return Ok(None);
+ }
+ let body: serde_json::Value = response
+ .error_for_status()
+ .context("BetterLyrics")?
+ .json()
+ .await
+ .context("BetterLyrics")?;
+ let Some(ttml) = body.get("ttml").and_then(serde_json::Value::as_str) else {
+ return Ok(None);
+ };
+ Ok(parse_ttml(ttml))
+}
+
+/// Apple's TTML as lines. `itunes:timing="None"` (or a line with no `begin`) is plain text.
+pub fn parse_ttml(ttml: &str) -> Option {
+ let doc = roxmltree::Document::parse(ttml).ok()?;
+ let root = doc.root_element();
+ let untimed = root
+ .attributes()
+ .any(|a| a.name() == "timing" && a.value().eq_ignore_ascii_case("none"));
+ let body = root.children().find(|n| n.has_tag_name("body"))?;
+ let romanised = transliterations(&doc);
+ let mut lines = Vec::new();
+ let mut synced = !untimed;
+ for p in body.descendants().filter(|n| n.has_tag_name("p")) {
+ let text = collapse(
+ &p.descendants()
+ .filter(|n| n.is_text())
+ .filter_map(|n| n.text())
+ .collect::(),
+ );
+ let at_ms = p.attribute("begin").and_then(ttml_time_ms);
+ if at_ms.is_none() {
+ synced = false;
+ }
+ // Each line names its key (`itunes:key` or `lrc:key`, "L12"), which is how its
+ // romanised text is filed. A romanisation that only repeats the line (an English line
+ // in a Korean song) is left out.
+ let romanised = p
+ .attributes()
+ .find(|a| a.name() == "key")
+ .and_then(|key| romanised.get(key.value()))
+ .filter(|r| !r.eq_ignore_ascii_case(&text))
+ .cloned();
+ lines.push(LyricLine {
+ at_ms: at_ms.unwrap_or(0),
+ text,
+ romanised,
+ });
+ }
+ if lines.is_empty() {
+ return None;
+ }
+ if synced {
+ lines.sort_by_key(|l| l.at_ms);
+ } else {
+ lines.iter_mut().for_each(|l| l.at_ms = 0);
+ }
+ Some(Lyrics {
+ lines,
+ synced,
+ source: "Apple Music".to_owned(),
+ })
+}
+
+/// Apple's romanised lines, by line key: `` in the head,
+/// with a `` per line (per-word spans inside, read as one line). The first
+/// transliteration in Latin letters, when a song has several.
+fn transliterations(doc: &roxmltree::Document) -> std::collections::HashMap {
+ let latin = |n: &roxmltree::Node| {
+ n.attributes()
+ .find(|a| a.name() == "lang")
+ .is_some_and(|a| a.value().contains("Latn"))
+ };
+ let mut all = doc
+ .descendants()
+ .filter(|n| n.has_tag_name("transliteration"));
+ let Some(chosen) = all.clone().find(latin).or_else(|| all.next()) else {
+ return Default::default();
+ };
+ chosen
+ .children()
+ .filter(|n| n.has_tag_name("text"))
+ .filter_map(|t| {
+ let key = t.attribute("for")?;
+ let text = collapse(
+ &t.descendants()
+ .filter(|n| n.is_text())
+ .filter_map(|n| n.text())
+ .collect::(),
+ );
+ (!text.is_empty()).then(|| (key.to_owned(), text))
+ })
+ .collect()
+}
+
+/// Runs of whitespace, including the line breaks between spans, as one space.
+fn collapse(text: &str) -> String {
+ text.split_whitespace().collect::>().join(" ")
+}
+
+/// A TTML clock value to milliseconds: `ss.fff`, `m:ss.fff`, `h:mm:ss.fff`, or with an `s` or
+/// `ms` unit.
+fn ttml_time_ms(value: &str) -> Option {
+ let value = value.trim();
+ if let Some(ms) = value.strip_suffix("ms") {
+ return ms.trim().parse::().ok().map(|ms| ms.round() as u64);
+ }
+ let value = value.strip_suffix('s').unwrap_or(value);
+ let mut seconds = 0.0;
+ for part in value.split(':') {
+ let n: f64 = part.trim().parse().ok()?;
+ seconds = seconds * 60.0 + n;
+ }
+ (seconds >= 0.0).then(|| (seconds * 1000.0).round() as u64)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const SAMPLE: &str = r#"Second line
calling back (Back again)
"#;
+
+ #[test]
+ fn apple_ttml_reads_as_timed_lines() {
+ let lyrics = parse_ttml(SAMPLE).unwrap();
+ assert!(lyrics.synced);
+ assert_eq!(lyrics.lines.len(), 2);
+ assert_eq!(lyrics.lines[0].at_ms, 140_059, "sorted by start");
+ assert_eq!(lyrics.lines[0].text, "calling back (Back again)");
+ assert_eq!(lyrics.lines[1].text, "Second line");
+ }
+
+ /// Apple's romaji for a Japanese line sits under it; a line whose romanisation only repeats
+ /// it gets none.
+ #[test]
+ fn apple_romanisations_attach_to_their_lines() {
+ let ttml = r#"shizu mu you ni Hello "#;
+ let lyrics = parse_ttml(ttml).unwrap();
+ assert_eq!(lyrics.lines[0].text, "沈むように");
+ assert_eq!(lyrics.lines[0].romanised.as_deref(), Some("shizumu you ni"));
+ assert_eq!(lyrics.lines[1].romanised, None, "only repeats the line");
+ assert_eq!(lyrics.lines[2].romanised, None, "none given");
+ }
+
+ #[test]
+ fn untimed_ttml_is_plain_text() {
+ let ttml = r#" "#;
+ let lyrics = parse_ttml(ttml).unwrap();
+ assert!(!lyrics.synced);
+ assert_eq!(lyrics.lines[1].text, "Two");
+ assert!(lyrics.lines.iter().all(|l| l.at_ms == 0));
+ }
+
+ #[test]
+ fn ttml_clock_values_in_every_form() {
+ assert_eq!(ttml_time_ms("12.5"), Some(12_500));
+ assert_eq!(ttml_time_ms("2:20.059"), Some(140_059));
+ assert_eq!(ttml_time_ms("1:02:03.004"), Some(3_723_004));
+ assert_eq!(ttml_time_ms("1.25s"), Some(1_250));
+ assert_eq!(ttml_time_ms("1250ms"), Some(1_250));
+ assert_eq!(ttml_time_ms("soon"), None);
+ }
+
+ #[test]
+ fn broken_xml_is_none() {
+ assert!(parse_ttml("").is_none());
+ }
+}
diff --git a/crates/refryt/src/lyrics/kugou.rs b/crates/refryt/src/lyrics/kugou.rs
new file mode 100644
index 0000000..b560856
--- /dev/null
+++ b/crates/refryt/src/lyrics/kugou.rs
@@ -0,0 +1,249 @@
+//! KuGou: a large Chinese music service's line-timed lyrics, strong outside the English
+//! catalogue.
+//!
+//! Three steps, as BitChord does it: a song search for the recordings near this length, a
+//! lyrics search by the nearest one's hash (or, failing that, by name and length), and a
+//! download of the first candidate as base64 LRC. KuGou's LRC opens and closes with credit lines
+//! ("作词 : …"), which are cut, and a track with no words gets a "pure music" notice instead,
+//! which counts as no lyrics.
+
+use anyhow::{Context, Result};
+use base64::Engine;
+use serde::Deserialize;
+
+use crate::model::{Lyrics, Track};
+
+const LENGTH_TOLERANCE_SECS: i64 = 8;
+
+#[derive(Deserialize)]
+struct SongSearch {
+ data: Option,
+}
+#[derive(Deserialize)]
+struct SongData {
+ #[serde(default)]
+ info: Vec,
+}
+#[derive(Deserialize)]
+struct SongInfo {
+ hash: String,
+ #[serde(default = "unknown")]
+ duration: i64,
+}
+fn unknown() -> i64 {
+ -1
+}
+#[derive(Deserialize)]
+struct LyricsSearch {
+ #[serde(default)]
+ candidates: Vec,
+}
+#[derive(Deserialize)]
+struct Candidate {
+ id: String,
+ accesskey: String,
+}
+#[derive(Deserialize)]
+struct Download {
+ content: String,
+}
+
+pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> {
+ let keyword = keyword(track);
+ let seconds = track.duration.map_or(-1, |d| d as i64);
+
+ let mut candidate = None;
+ for hash in song_hashes(http, &keyword, seconds).await? {
+ let found = search(http, &[("hash", hash.as_str())]).await?;
+ if let Some(first) = found.into_iter().next() {
+ candidate = Some(first);
+ break;
+ }
+ }
+ if candidate.is_none() {
+ let ms = (seconds > 0).then(|| (seconds * 1000).to_string());
+ let mut query = vec![("keyword", keyword.as_str())];
+ if let Some(ms) = ms.as_deref() {
+ query.push(("duration", ms));
+ }
+ candidate = search(http, &query).await?.into_iter().next();
+ }
+ let Some(candidate) = candidate else {
+ return Ok(None);
+ };
+
+ let download: Download = get(
+ http,
+ "https://lyrics.kugou.com/download",
+ &[
+ ("fmt", "lrc"),
+ ("charset", "utf8"),
+ ("client", "pc"),
+ ("ver", "1"),
+ ("id", candidate.id.as_str()),
+ ("accesskey", candidate.accesskey.as_str()),
+ ],
+ )
+ .await?;
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(download.content.trim())
+ .context("KuGou lyrics")?;
+ let lrc = String::from_utf8_lossy(&bytes);
+ let lines = strip_credits(super::lrclib::parse_lrc(&lrc));
+ if lines.is_empty() || is_instrumental_notice(&lines) {
+ return Ok(None);
+ }
+ Ok(Some(Lyrics {
+ lines,
+ synced: true,
+ source: "KuGou".to_owned(),
+ }))
+}
+
+/// "Title - Artist Album", without bracketed parts, as KuGou's own search wants it.
+fn keyword(track: &Track) -> String {
+ let mut out = format!(
+ "{} - {}",
+ strip_brackets(&track.title),
+ strip_brackets(&track.artist_line())
+ );
+ if let Some(album) = track.album.as_deref().filter(|a| !a.is_empty()) {
+ out.push(' ');
+ out.push_str(album);
+ }
+ out
+}
+
+fn strip_brackets(text: &str) -> String {
+ let mut out = String::new();
+ let mut depth = 0u32;
+ for c in text.chars() {
+ match c {
+ '(' | '(' => depth += 1,
+ ')' | ')' if depth > 0 => depth -= 1,
+ _ if depth == 0 => out.push(c),
+ _ => {}
+ }
+ }
+ let out = out.trim().to_owned();
+ if out.is_empty() {
+ text.trim().to_owned()
+ } else {
+ out
+ }
+}
+
+/// The hashes of the recordings within [`LENGTH_TOLERANCE_SECS`] of this one, nearest first.
+async fn song_hashes(http: &reqwest::Client, keyword: &str, seconds: i64) -> Result> {
+ let found: SongSearch = get(
+ http,
+ "https://mobileservice.kugou.com/api/v3/search/song",
+ &[
+ ("version", "9108"),
+ ("plat", "0"),
+ ("pagesize", "8"),
+ ("showtype", "0"),
+ ("keyword", keyword),
+ ],
+ )
+ .await?;
+ let mut info: Vec = found
+ .data
+ .map(|d| d.info)
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|i| seconds <= 0 || (i.duration - seconds).abs() <= LENGTH_TOLERANCE_SECS)
+ .collect();
+ info.sort_by_key(|i| (i.duration - seconds).abs());
+ Ok(info.into_iter().map(|i| i.hash).collect())
+}
+
+async fn search(http: &reqwest::Client, by: &[(&str, &str)]) -> Result> {
+ let mut query = vec![("ver", "1"), ("man", "yes"), ("client", "pc")];
+ query.extend_from_slice(by);
+ let found: LyricsSearch = get(http, "https://lyrics.kugou.com/search", &query).await?;
+ Ok(found.candidates)
+}
+
+async fn get(
+ http: &reqwest::Client,
+ url: &str,
+ query: &[(&str, &str)],
+) -> Result {
+ http.get(url)
+ .query(query)
+ .header(reqwest::header::USER_AGENT, super::USER_AGENT)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .context("KuGou")?
+ .error_for_status()
+ .context("KuGou")?
+ .json()
+ .await
+ .context("KuGou")
+}
+
+/// Whether a line is a credit: "作词 : 某人", "Composer: Someone".
+fn is_credit(text: &str) -> bool {
+ text.split_once([':', ':']).is_some_and(|(k, v)| {
+ !k.trim().is_empty() && !v.trim().is_empty() && k.chars().count() <= 12
+ })
+}
+
+/// Cut the credit lines KuGou opens and closes its lyrics with: the "Title - Artist" line and
+/// the run of credits after it, and the run of credits at the end. Only runs at the very ends,
+/// so a short song's closing credit can't take its lyrics with it.
+fn strip_credits(mut lines: Vec) -> Vec {
+ let title_line = lines.first().is_some_and(|l| l.text.contains(" - "))
+ && lines.get(1).is_some_and(|l| is_credit(&l.text));
+ let mut head = usize::from(title_line);
+ while lines.get(head).is_some_and(|l| is_credit(&l.text)) {
+ head += 1;
+ }
+ lines.drain(..head);
+ while lines.last().is_some_and(|l| is_credit(&l.text)) {
+ lines.pop();
+ }
+ lines
+}
+
+/// "纯音乐,请欣赏" ("pure music, please enjoy") on every line: an instrumental.
+fn is_instrumental_notice(lines: &[crate::model::LyricLine]) -> bool {
+ let words: Vec<&str> = lines
+ .iter()
+ .map(|l| l.text.trim())
+ .filter(|t| !t.is_empty())
+ .collect();
+ !words.is_empty() && words.iter().all(|t| t.contains("纯音乐"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::lyrics::lrclib::parse_lrc;
+
+ #[test]
+ fn credits_at_both_ends_are_cut() {
+ let lines = parse_lrc(
+ "[00:00.00]夜に駆ける - YOASOBI\n[00:01.00]词:Ayase\n[00:02.00]曲:Ayase\n\
+ [00:10.00]沈むように\n[00:12.00]溶けてゆくように\n[03:00.00]Producer: Someone\n",
+ );
+ let kept: Vec<_> = strip_credits(lines).into_iter().map(|l| l.text).collect();
+ assert_eq!(kept, ["沈むように", "溶けてゆくように"]);
+ }
+
+ #[test]
+ fn a_pure_music_notice_is_no_lyrics() {
+ let lines = parse_lrc("[00:00.00]纯音乐,请欣赏\n");
+ assert!(is_instrumental_notice(&lines));
+ assert!(!is_instrumental_notice(&parse_lrc("[00:00.00]la la\n")));
+ }
+
+ #[test]
+ fn brackets_leave_the_keyword() {
+ assert_eq!(strip_brackets("Glue (Edit)"), "Glue");
+ assert_eq!(strip_brackets("夜に駆ける(Remix)"), "夜に駆ける");
+ assert_eq!(strip_brackets("(Intro)"), "(Intro)");
+ }
+}
diff --git a/crates/refryt/src/lyrics/lrc_red.rs b/crates/refryt/src/lyrics/lrc_red.rs
new file mode 100644
index 0000000..cf20e91
--- /dev/null
+++ b/crates/refryt/src/lyrics/lrc_red.rs
@@ -0,0 +1,152 @@
+//! lrc.red: Apple Music's TTML, filed by recording (ISRC).
+//!
+//! A search (`search.json?q=`) names the recordings it has, each with its ISRC, title, artist
+//! and length. The best match's document is then `s/.ttml`, the same TTML BetterLyrics
+//! serves, but for any song lrc.red indexed rather than only those a cache holds. Matching
+//! follows BitChord's: the same title once brackets are set aside, the same version words
+//! ("live", "remix", …), a shared artist, and a length within 3 seconds.
+
+use anyhow::{Context, Result};
+use serde::Deserialize;
+
+use crate::model::{Lyrics, Track};
+
+const BASE: &str = "https://lrc.red/";
+const LENGTH_TOLERANCE_SECS: f64 = 3.0;
+
+#[derive(Deserialize)]
+struct Response {
+ #[serde(default)]
+ hits: Vec,
+}
+
+#[derive(Clone, Debug, Deserialize, PartialEq)]
+struct Hit {
+ isrc: Option,
+ title: Option,
+ artist: Option,
+ duration: Option,
+}
+
+pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> {
+ let artist = track.artist_line();
+ let query = format!("{} {}", track.title, artist);
+ let response: Response = http
+ .get(format!("{BASE}search.json"))
+ .query(&[("q", query.trim())])
+ .header(reqwest::header::USER_AGENT, super::USER_AGENT)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .context("lrc.red search")?
+ .error_for_status()
+ .context("lrc.red search")?
+ .json()
+ .await
+ .context("lrc.red search")?;
+ let Some(isrc) = best(&response.hits, &track.title, &artist, track.duration)
+ .and_then(|hit| hit.isrc.clone())
+ else {
+ return Ok(None);
+ };
+ let document = http
+ .get(format!("{BASE}s/{isrc}.ttml"))
+ .header(reqwest::header::USER_AGENT, super::USER_AGENT)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .context("lrc.red document")?;
+ if document.status() == reqwest::StatusCode::NOT_FOUND {
+ return Ok(None);
+ }
+ let ttml = document
+ .error_for_status()
+ .context("lrc.red document")?
+ .text()
+ .await
+ .context("lrc.red document")?;
+ Ok(super::better_lyrics::parse_ttml(&ttml))
+}
+
+/// The hit that is this recording, nearest in length when several are.
+fn best<'a>(hits: &'a [Hit], title: &str, artist: &str, seconds: Option) -> Option<&'a Hit> {
+ let core = super::title_core(title);
+ let version = super::version_words(title);
+ let artists = super::artist_names(artist);
+ let distance = |hit: &Hit| match (seconds, hit.duration) {
+ (Some(s), Some(d)) if s > 0 => (d - s as f64).abs(),
+ _ => 0.0,
+ };
+ hits.iter()
+ .filter(|hit| {
+ let Some(name) = hit.title.as_deref() else {
+ return false;
+ };
+ hit.isrc.as_deref().is_some_and(valid_isrc)
+ && super::title_core(name) == core
+ && super::version_words(name) == version
+ && (artists.is_empty()
+ || super::artist_names(hit.artist.as_deref().unwrap_or_default())
+ .iter()
+ .any(|a| artists.contains(a)))
+ && distance(hit) <= LENGTH_TOLERANCE_SECS
+ })
+ .min_by(|a, b| distance(a).total_cmp(&distance(b)))
+}
+
+/// Two letters, three letters or digits, seven digits: the shape of an ISRC, so nothing else
+/// ends up in the document's path.
+fn valid_isrc(isrc: &str) -> bool {
+ let b = isrc.as_bytes();
+ b.len() == 12
+ && b[..2].iter().all(u8::is_ascii_uppercase)
+ && b[2..5]
+ .iter()
+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
+ && b[5..].iter().all(u8::is_ascii_digit)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hit(isrc: &str, title: &str, artist: &str, duration: f64) -> Hit {
+ Hit {
+ isrc: Some(isrc.to_owned()),
+ title: Some(title.to_owned()),
+ artist: Some(artist.to_owned()),
+ duration: Some(duration),
+ }
+ }
+
+ #[test]
+ fn the_same_recording_is_picked_and_other_versions_are_not() {
+ let hits = vec![
+ hit(
+ "USUG11904206",
+ "Blinding Lights (Live)",
+ "The Weeknd",
+ 200.0,
+ ),
+ hit("USUG11904207", "Blinding Lights", "Someone Else", 200.0),
+ hit("USUG11904208", "Blinding Lights", "The Weeknd", 210.0),
+ hit(
+ "USUG11904209",
+ "Blinding Lights",
+ "The Weeknd & Rosalía",
+ 201.0,
+ ),
+ ];
+ let picked = best(&hits, "Blinding Lights", "The Weeknd", Some(200)).unwrap();
+ assert_eq!(picked.isrc.as_deref(), Some("USUG11904209"));
+ assert!(best(&hits, "Blinding Lights", "Nobody", Some(200)).is_none());
+ }
+
+ #[test]
+ fn only_isrc_shaped_codes_are_used() {
+ assert!(valid_isrc("USUG11904206"));
+ assert!(valid_isrc("GBCFB1700229"));
+ assert!(!valid_isrc("../etc/passwd"));
+ assert!(!valid_isrc("usug11904206"));
+ }
+}
diff --git a/crates/refryt/src/lyrics/lrclib.rs b/crates/refryt/src/lyrics/lrclib.rs
new file mode 100644
index 0000000..e13418a
--- /dev/null
+++ b/crates/refryt/src/lyrics/lrclib.rs
@@ -0,0 +1,149 @@
+//! lrclib.net: community lyrics, synced where someone timed them. No auth, one GET.
+
+use crate::model::{LyricLine, Lyrics, Track};
+
+/// LRCLIB's lyrics for a track: synced when it has them, else its plain text. `None` on any
+/// miss.
+pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Option {
+ let artist = track.artist_line();
+ let duration = track.duration.map(|d| d.to_string());
+ let mut query: Vec<(&str, &str)> = vec![
+ ("track_name", track.title.as_str()),
+ ("artist_name", artist.as_str()),
+ ];
+ if let Some(album) = track.album.as_deref() {
+ query.push(("album_name", album));
+ }
+ if let Some(duration) = duration.as_deref() {
+ query.push(("duration", duration));
+ }
+ let response = http
+ .get("https://lrclib.net/api/get")
+ .query(&query)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .ok()?;
+ if !response.status().is_success() {
+ return None;
+ }
+ let body: serde_json::Value = response.json().await.ok()?;
+ if let Some(lrc) = body.get("syncedLyrics").and_then(serde_json::Value::as_str) {
+ let lines = parse_lrc(lrc);
+ if !lines.is_empty() {
+ return Some(Lyrics {
+ lines,
+ synced: true,
+ source: "LRCLIB".to_owned(),
+ });
+ }
+ }
+ let plain = body
+ .get("plainLyrics")
+ .and_then(serde_json::Value::as_str)?;
+ Some(Lyrics {
+ lines: plain_lines(plain),
+ synced: false,
+ source: "LRCLIB".to_owned(),
+ })
+}
+
+/// Plain text as lines, each at zero.
+pub fn plain_lines(text: &str) -> Vec {
+ text.lines()
+ .map(|l| LyricLine {
+ at_ms: 0,
+ text: l.trim_end().to_owned(),
+ romanised: None,
+ })
+ .collect()
+}
+
+/// Parse an LRC body (`[mm:ss.xx] line`) into sorted, timestamped lines. Malformed stamps are
+/// skipped rather than failing the whole set.
+pub fn parse_lrc(text: &str) -> Vec {
+ let mut out = Vec::new();
+ for line in text.lines() {
+ let line = line.trim();
+ if !line.starts_with('[') {
+ continue;
+ }
+ let Some(close) = line.find(']') else {
+ continue;
+ };
+ let Some(at_ms) = lrc_time_ms(&line[1..close]) else {
+ continue;
+ };
+ out.push(LyricLine {
+ at_ms,
+ text: without_word_stamps(&line[close + 1..]),
+ romanised: None,
+ });
+ }
+ out.sort_by_key(|l| l.at_ms);
+ out
+}
+
+/// A line's text with enhanced LRC's word stamps (`<00:01.40>`) taken out, since lines light
+/// up whole.
+fn without_word_stamps(text: &str) -> String {
+ let mut out = String::new();
+ let mut rest = text;
+ while let Some(lt) = rest.find('<') {
+ let Some(gt) = rest[lt..].find('>') else {
+ break;
+ };
+ out.push_str(&rest[..lt]);
+ if lrc_time_ms(&rest[lt + 1..lt + gt]).is_none() {
+ out.push_str(&rest[lt..=lt + gt]);
+ }
+ rest = &rest[lt + gt + 1..];
+ }
+ out.push_str(rest);
+ out.split_whitespace().collect::>().join(" ")
+}
+
+/// `mm:ss.xx` (or `.x`, `.xxx`) to milliseconds. The fraction's digits count as written, so
+/// `.05` is 50 ms, not 500.
+fn lrc_time_ms(stamp: &str) -> Option {
+ let (mm, rest) = stamp.split_once(':')?;
+ let mm: u64 = mm.trim().parse().ok()?;
+ let (ss, frac) = rest.split_once('.').unwrap_or((rest, ""));
+ let ss: u64 = ss.trim().parse().ok()?;
+ let digits: String = frac.trim().chars().take(3).collect();
+ let ms = if digits.is_empty() {
+ 0
+ } else {
+ let value: u64 = digits.parse().ok()?;
+ value * 10u64.pow(3 - digits.len() as u32)
+ };
+ Some(mm * 60_000 + ss * 1000 + ms)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// LRC stamps: the fraction counts as many digits as it has, and a malformed stamp is
+ /// skipped rather than dropping the whole lyric set.
+ #[test]
+ fn lrc_times_parse_in_every_fraction_width() {
+ assert_eq!(lrc_time_ms("00:12.34"), Some(12_340));
+ assert_eq!(lrc_time_ms("01:02.345"), Some(62_345));
+ assert_eq!(lrc_time_ms("02:00"), Some(120_000));
+ assert_eq!(lrc_time_ms("00:01.5"), Some(1_500));
+ // A leading zero used to read as 500 ms.
+ assert_eq!(lrc_time_ms("00:01.05"), Some(1_050));
+ assert_eq!(lrc_time_ms("00:01.005"), Some(1_005));
+ assert_eq!(lrc_time_ms("not a stamp"), None);
+ }
+
+ #[test]
+ fn lrc_lines_are_sorted_and_timed() {
+ let lines = parse_lrc("[00:20.00] second\nnoise\n[00:10.50] first\n");
+ assert_eq!(lines.len(), 2, "the header-less line is skipped");
+ assert_eq!(lines[0].text, "first");
+ assert_eq!(lines[0].at_ms, 10_500);
+ assert_eq!(lines[1].text, "second");
+ }
+}
diff --git a/crates/refryt/src/lyrics/mod.rs b/crates/refryt/src/lyrics/mod.rs
new file mode 100644
index 0000000..7d72b26
--- /dev/null
+++ b/crates/refryt/src/lyrics/mod.rs
@@ -0,0 +1,743 @@
+//! Where lyrics come from: several sources, asked together, the best answer shown.
+//!
+//! Every source the listener has ticked in Settings is asked at the same time, and the answers
+//! are taken in the listener's order: the first source with *synced* lyrics wins, and plain
+//! text is shown only when no source had timing. A source that is ticked off is never
+//! contacted. The lyrics panel lets the listener switch to another source's answer for the
+//! song that is playing.
+//!
+//! The approach follows BitChord's (github.com/kushagrasinghx/BitChord, GPL-3.0 like refryt):
+//! an ordered, tickable list of sources, all asked at once and read in order, with a manual
+//! pick per song.
+
+pub mod better_lyrics;
+pub mod kugou;
+pub mod lrc_red;
+pub mod lrclib;
+pub mod unison;
+pub mod youtube;
+
+use std::collections::HashMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::model::Lyrics;
+
+/// How long one source gets to answer before it counts as having nothing. Long enough for a
+/// slow host, short enough that a source that is down doesn't hold the panel's skeleton for long:
+/// a higher source still pending is waited on before a lower one's answer is shown.
+pub const SOURCE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);
+
+/// What the lyrics hosts are told the client is: the app, never the listener.
+pub const USER_AGENT: &str = concat!(
+ "refryt/",
+ env!("CARGO_PKG_VERSION"),
+ " (https://github.com/gridoe/refryt)"
+);
+
+/// A place lyrics can come from. The order here is the default order they are asked in.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Source {
+ /// Apple Music's timing through the BetterLyrics extension's API. Only songs its cache
+ /// already holds: anything else it now answers with "API key required".
+ BetterLyrics,
+ /// lrc.red: the same Apple Music TTML, filed by recording, for any song it indexed.
+ LrcRed,
+ /// YouTube Music's own timed lyrics (from Musixmatch or LyricFind), as its Android app
+ /// gets them, matched on the exact video.
+ YouTubeSynced,
+ /// lrclib.net's community lyrics, matched on the title, artist, album and length.
+ Lrclib,
+ /// KuGou's line-timed lyrics, strong outside the English catalogue.
+ KuGou,
+ /// Unison: lyrics contributed by listeners, from the BetterLyrics project.
+ Unison,
+ /// YouTube Music's lyrics as the website shows them: plain text, no timing.
+ YouTube,
+}
+
+impl Source {
+ /// Every source, in the default order.
+ pub const ALL: [Source; 7] = [
+ Source::BetterLyrics,
+ Source::LrcRed,
+ Source::YouTubeSynced,
+ Source::Lrclib,
+ Source::KuGou,
+ Source::Unison,
+ Source::YouTube,
+ ];
+
+ /// The name kept in the settings file.
+ pub fn key(self) -> &'static str {
+ match self {
+ Source::BetterLyrics => "better_lyrics",
+ Source::YouTubeSynced => "youtube_synced",
+ Source::Lrclib => "lrclib",
+ Source::KuGou => "kugou",
+ Source::Unison => "unison",
+ Source::YouTube => "youtube",
+ Source::LrcRed => "lrc_red",
+ }
+ }
+
+ pub fn from_key(key: &str) -> Option {
+ Source::ALL.into_iter().find(|s| s.key() == key)
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Source::BetterLyrics => "BetterLyrics",
+ Source::YouTubeSynced => "YouTube Music, synced",
+ Source::Lrclib => "LRCLIB",
+ Source::KuGou => "KuGou",
+ Source::Unison => "Unison",
+ Source::YouTube => "YouTube Music, plain",
+ Source::LrcRed => "lrc.red",
+ }
+ }
+
+ /// The name in the lyrics panel's picker, where there's little room.
+ pub fn short_label(self) -> &'static str {
+ match self {
+ Source::BetterLyrics => "BetterLyrics",
+ Source::YouTubeSynced => "YouTube synced",
+ Source::Lrclib => "LRCLIB",
+ Source::KuGou => "KuGou",
+ Source::Unison => "Unison",
+ Source::YouTube => "YouTube plain",
+ Source::LrcRed => "lrc.red",
+ }
+ }
+
+ /// One line on what it is and what it is sent, for Settings.
+ pub fn detail(self) -> &'static str {
+ match self {
+ Source::BetterLyrics => {
+ "Apple Music's timing, for songs it already has. Gets the title, artist, album \
+ and length."
+ }
+ Source::YouTubeSynced => {
+ "YouTube's own timed lyrics, matched to the exact song. Gets the video id."
+ }
+ Source::Lrclib => {
+ "Community lyrics from lrclib.net. Gets the title, artist, album and length."
+ }
+ Source::YouTube => "YouTube's lyrics without timing. Gets the video id.",
+ Source::LrcRed => {
+ "Apple Music's timing for any song it has indexed, not only cached ones. Gets \
+ the title, artist and length."
+ }
+ Source::KuGou => {
+ "Timed lyrics from a large Chinese music service, good outside English. Gets \
+ the title, artist, album and length."
+ }
+ Source::Unison => {
+ "Lyrics added by listeners, for songs nobody licenses. Gets the title, artist, \
+ album and length."
+ }
+ }
+ }
+}
+
+/// A source and whether it is asked, as the settings file keeps it: by name, so the list can
+/// gain a source, or be reordered in code, without disturbing an order someone chose.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SourceChoice {
+ pub source: String,
+ pub on: bool,
+}
+
+/// The default list: every source, in [`Source::ALL`]'s order, all on.
+pub fn default_choices() -> Vec {
+ to_choices(&Source::ALL.map(|s| (s, true)))
+}
+
+pub fn to_choices(list: &[(Source, bool)]) -> Vec {
+ list.iter()
+ .map(|(s, on)| SourceChoice {
+ source: s.key().to_owned(),
+ on: *on,
+ })
+ .collect()
+}
+
+/// A saved list brought up to date with this build: names this build doesn't know dropped,
+/// repeats dropped, and a source added since the list was saved put in right after the source
+/// it follows in [`Source::ALL`] (at the top if none of those is in the list), switched on. An
+/// empty list is the default one.
+pub fn normalise(saved: &[SourceChoice]) -> Vec<(Source, bool)> {
+ let mut out: Vec<(Source, bool)> = Vec::new();
+ for choice in saved {
+ if let Some(source) = Source::from_key(&choice.source)
+ && !out.iter().any(|(s, _)| *s == source)
+ {
+ out.push((source, choice.on));
+ }
+ }
+ for (index, source) in Source::ALL.into_iter().enumerate() {
+ if out.iter().any(|(s, _)| *s == source) {
+ continue;
+ }
+ let after = Source::ALL[..index]
+ .iter()
+ .rev()
+ .find_map(|prev| out.iter().position(|(s, _)| s == prev));
+ out.insert(after.map_or(0, |i| i + 1), (source, true));
+ }
+ out
+}
+
+/// The sources to ask, in order: the ticked ones.
+pub fn asked(saved: &[SourceChoice]) -> Vec {
+ normalise(saved)
+ .into_iter()
+ .filter_map(|(s, on)| on.then_some(s))
+ .collect()
+}
+
+/// What one source has said about the song so far.
+#[derive(Clone, Debug, PartialEq)]
+pub enum Answer {
+ Pending,
+ Found(Lyrics),
+ /// Nothing for this song, or it could not be reached in time.
+ Missing,
+}
+
+/// Which answer to show, from what the sources have said so far.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Pick {
+ /// A source ahead of every synced answer is still out: its answer may beat them.
+ Wait,
+ Use(Source),
+ /// Every source has answered and none had lyrics.
+ Nothing,
+}
+
+/// The automatic pick. Going down `order`: a source still out means waiting for it; the first
+/// with synced lyrics wins; plain text counts only once every source is in and none had timing,
+/// and then the first plain answer is used.
+///
+/// With `romanise` on, synced lyrics in Japanese, Korean or Chinese that have no romanisation
+/// are only a stand-in: shown at once, but the first source further down that has a
+/// romanisation takes over when it answers.
+pub fn pick(order: &[Source], answers: &HashMap, romanise: bool) -> Pick {
+ let mut plain = None;
+ let mut stand_in = None;
+ for source in order {
+ match answers.get(source) {
+ None | Some(Answer::Pending) => {
+ return stand_in.map_or(Pick::Wait, Pick::Use);
+ }
+ Some(Answer::Found(lyrics)) if lyrics.synced => {
+ let wanting = romanise && needs_romanising(lyrics) && !has_romanised(lyrics);
+ match (wanting, stand_in) {
+ (false, _) if stand_in.is_none() || has_romanised(lyrics) => {
+ return Pick::Use(*source);
+ }
+ (true, None) => stand_in = Some(*source),
+ _ => {}
+ }
+ }
+ Some(Answer::Found(_)) => {
+ plain.get_or_insert(*source);
+ }
+ Some(Answer::Missing) => {}
+ }
+ }
+ stand_in.or(plain).map_or(Pick::Nothing, Pick::Use)
+}
+
+/// Whether a line is in a script romanisation is for: kana, CJK ideographs, Hangul.
+pub fn in_romanisable_script(text: &str) -> bool {
+ text.chars().any(|c| {
+ matches!(c,
+ '\u{3040}'..='\u{30ff}' // hiragana, katakana
+ | '\u{31f0}'..='\u{31ff}' // katakana extensions
+ | '\u{ff66}'..='\u{ff9f}' // half-width katakana
+ | '\u{3400}'..='\u{4dbf}' // CJK extension A
+ | '\u{4e00}'..='\u{9fff}' // CJK ideographs
+ | '\u{f900}'..='\u{faff}' // CJK compatibility
+ | '\u{1100}'..='\u{11ff}' // Hangul jamo
+ | '\u{3130}'..='\u{318f}' // Hangul compatibility jamo
+ | '\u{ac00}'..='\u{d7af}' // Hangul syllables
+ )
+ })
+}
+
+/// Lyrics with lines romanisation is for.
+pub fn needs_romanising(lyrics: &Lyrics) -> bool {
+ lyrics.lines.iter().any(|l| in_romanisable_script(&l.text))
+}
+
+pub fn has_romanised(lyrics: &Lyrics) -> bool {
+ lyrics.lines.iter().any(|l| l.romanised.is_some())
+}
+
+fn has_kana(text: &str) -> bool {
+ text.chars()
+ .any(|c| matches!(c, '\u{3040}'..='\u{30ff}' | '\u{ff66}'..='\u{ff9f}'))
+}
+
+/// The words of Latin text and how many end the way Japanese syllables do, in a vowel or `n`.
+/// Romaji runs well over 70% of them, English nearer 30–50%. Words in brackets are left out:
+/// backing vocals like "(Hey! Hey!)" are the same in either.
+fn japanese_endings(text: &str) -> (usize, usize) {
+ let mut outside = String::new();
+ let mut depth = 0u32;
+ for c in text.chars() {
+ match c {
+ '(' | '[' | '(' => depth += 1,
+ ')' | ']' | ')' if depth > 0 => depth -= 1,
+ _ if depth == 0 => outside.push(c),
+ _ => {}
+ }
+ }
+ let words = outside
+ .split(|c: char| !c.is_alphabetic())
+ .filter(|w| !w.is_empty())
+ .map(str::to_lowercase);
+ let (mut all, mut japanese) = (0, 0);
+ for w in words {
+ all += 1;
+ if w.ends_with([
+ 'a', 'e', 'i', 'o', 'u', 'n', 'ā', 'ē', 'ī', 'ō', 'ū', 'â', 'ô', 'û',
+ ]) {
+ japanese += 1;
+ }
+ }
+ (all, japanese)
+}
+
+/// Romaji a lyrics file carries as lines of its own. Some LRC files hold the song in Japanese
+/// and again in romaji under the same timestamps, so each Japanese line has a twin at the same
+/// moment. Those twins become the line's romanisation, and a line both halves share (an English
+/// line) is kept once.
+///
+/// Judged over the whole file, not line by line: the twins must read as romaji taken together,
+/// so an English translation filed the same way stays as lines, and most Japanese lines must
+/// have one, so a stray repeated stamp changes nothing.
+pub fn pair_romaji(lyrics: &mut Lyrics) {
+ if !lyrics.synced || has_romanised(lyrics) || !lyrics.lines.iter().any(|l| has_kana(&l.text)) {
+ return;
+ }
+ let lines = &lyrics.lines;
+ let japanese = lines
+ .iter()
+ .filter(|l| in_romanisable_script(&l.text))
+ .count();
+ let mut out = Vec::with_capacity(lines.len());
+ let (mut twins, mut words, mut endings) = (0, 0, 0);
+ let mut i = 0;
+ while i < lines.len() {
+ let mut j = i + 1;
+ while j < lines.len() && lines[j].at_ms == lines[i].at_ms {
+ j += 1;
+ }
+ if let [a, b] = &lines[i..j] {
+ let twin = match (
+ in_romanisable_script(&a.text),
+ in_romanisable_script(&b.text),
+ ) {
+ (true, false) => Some((a, b)),
+ (false, true) => Some((b, a)),
+ _ => None,
+ };
+ if let Some((original, roman)) = twin {
+ let (all, japanese_like) = japanese_endings(&roman.text);
+ words += all;
+ endings += japanese_like;
+ twins += 1;
+ out.push(crate::model::LyricLine {
+ at_ms: original.at_ms,
+ text: original.text.clone(),
+ romanised: Some(roman.text.trim().to_owned()).filter(|r| !r.is_empty()),
+ });
+ i = j;
+ continue;
+ }
+ if a.text == b.text {
+ out.push(a.clone());
+ i = j;
+ continue;
+ }
+ }
+ out.extend(lines[i..j].iter().cloned());
+ i = j;
+ }
+ if twins * 2 > japanese && words > 0 && endings * 10 >= words * 7 {
+ lyrics.lines = out;
+ }
+}
+
+/// Ask one source for `track`'s lyrics. `Ok(None)` is a plain miss; an error is a source that
+/// could not be reached or answered something unreadable, which counts as a miss too.
+pub async fn fetch(
+ source: Source,
+ http: &reqwest::Client,
+ api: &crate::api::Api,
+ track: &crate::model::Track,
+) -> anyhow::Result> {
+ let mut found = match source {
+ Source::BetterLyrics => better_lyrics::lyrics(http, track).await,
+ Source::YouTubeSynced => youtube::synced(http, &track.video_id).await,
+ Source::Lrclib => Ok(lrclib::lyrics(http, track).await),
+ Source::YouTube => api.lyrics(&track.video_id).await,
+ Source::LrcRed => lrc_red::lyrics(http, track).await,
+ Source::KuGou => kugou::lyrics(http, track).await,
+ Source::Unison => unison::lyrics(http, track).await,
+ }?;
+ if let Some(lyrics) = found.as_mut() {
+ pair_romaji(lyrics);
+ }
+ Ok(found)
+}
+
+// Matching a search hit to the song, for the sources that search by name.
+
+/// Lowercase, everything but letters and digits as spaces, runs of spaces as one.
+pub(crate) fn normalised(text: &str) -> String {
+ text.to_lowercase()
+ .chars()
+ .map(|c| if c.is_alphanumeric() { c } else { ' ' })
+ .collect::()
+ .split_whitespace()
+ .collect::>()
+ .join(" ")
+}
+
+/// The title with bracketed parts and anything after " - " set aside, as written: "Glue (Edit)"
+/// and "Glue - 2017 Remaster" are both "Glue". The whole title if that leaves nothing.
+pub(crate) fn title_core_display(title: &str) -> String {
+ let mut out = String::new();
+ let mut depth = 0u32;
+ for c in title.chars() {
+ match c {
+ '(' | '[' | '(' => depth += 1,
+ ')' | ']' | ')' if depth > 0 => depth -= 1,
+ _ if depth == 0 => out.push(c),
+ _ => {}
+ }
+ }
+ let out = out
+ .split(" - ")
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .to_owned();
+ if out.is_empty() {
+ title.trim().to_owned()
+ } else {
+ out
+ }
+}
+
+/// [`title_core_display`], normalised for comparing.
+pub(crate) fn title_core(title: &str) -> String {
+ normalised(&title_core_display(title))
+}
+
+/// The words in a title's brackets or after its " - " that make it a different recording:
+/// "live", "remix", "acoustic"… Two titles are the same version when these match.
+pub(crate) fn version_words(title: &str) -> std::collections::BTreeSet {
+ const WORDS: [&str; 21] = [
+ "live",
+ "remix",
+ "remixed",
+ "mix",
+ "acoustic",
+ "unplugged",
+ "instrumental",
+ "karaoke",
+ "cappella",
+ "acapella",
+ "demo",
+ "edit",
+ "version",
+ "cover",
+ "sped",
+ "slowed",
+ "reverb",
+ "nightcore",
+ "lofi",
+ "orchestral",
+ "extended",
+ ];
+ let core = title_core_display(title);
+ let extra = title.replacen(core.as_str(), " ", 1);
+ normalised(&extra)
+ .split(' ')
+ .filter(|w| WORDS.contains(w))
+ .map(str::to_owned)
+ .collect()
+}
+
+/// The artists in an artist line, normalised: "A & B feat. C" is {a, b, c}.
+pub(crate) fn artist_names(artist: &str) -> Vec {
+ let mut line = format!(" {} ", artist.to_lowercase());
+ for joiner in [
+ " and ",
+ " x ",
+ " with ",
+ " feat. ",
+ " feat ",
+ " ft. ",
+ " ft ",
+ " featuring ",
+ ] {
+ line = line.replace(joiner, ",");
+ }
+ line.split([',', '&', ';', '/', '、'])
+ .map(normalised)
+ .filter(|a| !a.is_empty())
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::LyricLine;
+
+ fn lyrics(synced: bool) -> Lyrics {
+ Lyrics {
+ lines: vec![LyricLine {
+ at_ms: 0,
+ text: "la".to_owned(),
+ romanised: None,
+ }],
+ synced,
+ source: String::new(),
+ }
+ }
+
+ fn answers(list: &[(Source, Answer)]) -> HashMap {
+ list.iter().cloned().collect()
+ }
+
+ use Source::*;
+
+ #[test]
+ fn the_first_synced_answer_in_order_wins() {
+ let order = [BetterLyrics, YouTubeSynced, Lrclib];
+ let a = answers(&[
+ (BetterLyrics, Answer::Missing),
+ (YouTubeSynced, Answer::Found(lyrics(true))),
+ (Lrclib, Answer::Found(lyrics(true))),
+ ]);
+ assert_eq!(pick(&order, &a, false), Pick::Use(YouTubeSynced));
+ }
+
+ /// A lower source answering first doesn't jump ahead of one still out above it.
+ #[test]
+ fn a_pending_source_above_is_waited_for() {
+ let order = [BetterLyrics, Lrclib];
+ let a = answers(&[
+ (BetterLyrics, Answer::Pending),
+ (Lrclib, Answer::Found(lyrics(true))),
+ ]);
+ assert_eq!(pick(&order, &a, false), Pick::Wait);
+ }
+
+ #[test]
+ fn plain_text_waits_for_every_source_and_loses_to_timing() {
+ let order = [YouTube, Lrclib];
+ let mut a = answers(&[
+ (YouTube, Answer::Found(lyrics(false))),
+ (Lrclib, Answer::Pending),
+ ]);
+ assert_eq!(pick(&order, &a, false), Pick::Wait);
+ a.insert(Lrclib, Answer::Found(lyrics(true)));
+ assert_eq!(pick(&order, &a, false), Pick::Use(Lrclib));
+ a.insert(Lrclib, Answer::Missing);
+ assert_eq!(pick(&order, &a, false), Pick::Use(YouTube));
+ }
+
+ #[test]
+ fn nothing_anywhere_is_nothing() {
+ let order = [YouTube, Lrclib];
+ let a = answers(&[(YouTube, Answer::Missing), (Lrclib, Answer::Missing)]);
+ assert_eq!(pick(&order, &a, false), Pick::Nothing);
+ assert_eq!(pick(&[], &a, false), Pick::Nothing);
+ }
+
+ fn line(at_ms: u64, text: &str, romanised: Option<&str>) -> LyricLine {
+ LyricLine {
+ at_ms,
+ text: text.to_owned(),
+ romanised: romanised.map(str::to_owned),
+ }
+ }
+
+ fn synced(lines: Vec) -> Lyrics {
+ Lyrics {
+ lines,
+ synced: true,
+ source: String::new(),
+ }
+ }
+
+ /// The song in Japanese, then again in romaji under the same stamps: each line gets its
+ /// romaji, and a line both halves share is kept once.
+ #[test]
+ fn romaji_twins_in_a_file_become_romanisations() {
+ let mut l = synced(crate::lyrics::lrclib::parse_lrc(
+ "[00:00.87]無敵の笑顔で荒らすメディア\n[00:03.78]知りたいその秘密ミステリアス\n\
+ [00:14.76](You're my savior)\n\
+ [00:00.87]Muteki no egao de arasu media\n[00:03.78]Shiritai sono himitsu misuteriasu\n\
+ [00:14.76](You're my savior)\n",
+ ));
+ pair_romaji(&mut l);
+ assert_eq!(l.lines.len(), 3);
+ assert_eq!(l.lines[0].text, "無敵の笑顔で荒らすメディア");
+ assert_eq!(
+ l.lines[0].romanised.as_deref(),
+ Some("Muteki no egao de arasu media")
+ );
+ assert_eq!(l.lines[2].text, "(You're my savior)");
+ assert_eq!(l.lines[2].romanised, None);
+ }
+
+ /// Romaji with English mixed in ("(Hey! Hey!)") still counts, and an empty twin leaves the
+ /// Japanese line on its own.
+ #[test]
+ fn romaji_with_shouts_in_it_still_pairs() {
+ let mut l = synced(crate::lyrics::lrclib::parse_lrc(
+ "[00:46.24]嘘か本当か知り得ない\n[00:49.43]そんな言葉にまた一人堕ちる\n\
+ [01:18.47]はいはいあの子は特別です\n\
+ [00:46.24]Uso ka hontou ka shirienai (Hey! Hey! Hey! Hey!)\n\
+ [00:49.43]Sonna kotoba ni mata hitori ochiru (Hey! Hey! Hey! Hey!)\n\
+ [01:18.47]\n",
+ ));
+ pair_romaji(&mut l);
+ assert_eq!(l.lines.len(), 3);
+ assert!(
+ l.lines[0]
+ .romanised
+ .as_deref()
+ .unwrap()
+ .starts_with("Uso ka")
+ );
+ assert_eq!(l.lines[2].text, "はいはいあの子は特別です");
+ assert_eq!(l.lines[2].romanised, None);
+ }
+
+ /// An English translation under the same stamps isn't romaji, and is left as lines.
+ #[test]
+ fn a_translation_twin_is_not_taken_for_romaji() {
+ let lrc = "[00:01.00]知りたいその秘密\n[00:01.00]I want to know that secret\n\
+ [00:03.00]完璧で嘘つきな君は\n[00:03.00]You, perfect and a liar\n";
+ let mut l = synced(crate::lyrics::lrclib::parse_lrc(lrc));
+ pair_romaji(&mut l);
+ assert_eq!(l.lines.len(), 4);
+ assert!(!has_romanised(&l));
+ }
+
+ /// Romanisation on: Japanese without it stands in at once, and the first source that has
+ /// it takes over when it answers. Lyrics with nothing to romanise win as before.
+ #[test]
+ fn a_romanised_answer_takes_over_from_a_stand_in() {
+ let japanese = synced(vec![line(0, "無敵の笑顔", None)]);
+ let romaji = synced(vec![line(0, "無敵の笑顔", Some("Muteki no egao"))]);
+ let english = synced(vec![line(0, "Couldn't beat her smile", None)]);
+ let order = [YouTubeSynced, Lrclib, LrcRed];
+ let mut a = answers(&[
+ (YouTubeSynced, Answer::Found(japanese.clone())),
+ (Lrclib, Answer::Found(english)),
+ (LrcRed, Answer::Pending),
+ ]);
+ assert_eq!(
+ pick(&order, &a, true),
+ Pick::Use(YouTubeSynced),
+ "shown meanwhile"
+ );
+ assert_eq!(pick(&order, &a, false), Pick::Use(YouTubeSynced));
+ a.insert(LrcRed, Answer::Found(romaji));
+ assert_eq!(pick(&order, &a, true), Pick::Use(LrcRed));
+ assert_eq!(
+ pick(&order, &a, false),
+ Pick::Use(YouTubeSynced),
+ "off: order as ever"
+ );
+ a.insert(LrcRed, Answer::Missing);
+ assert_eq!(
+ pick(&order, &a, true),
+ Pick::Use(YouTubeSynced),
+ "none had it"
+ );
+ }
+
+ #[test]
+ fn an_empty_list_is_the_default_order_all_on() {
+ assert_eq!(normalise(&[]), Source::ALL.map(|s| (s, true)).to_vec(),);
+ assert_eq!(asked(&default_choices()), Source::ALL.to_vec());
+ }
+
+ /// A saved order is kept; unknown names and repeats go; a source it never named lands
+ /// right after its neighbour in the default order, switched on.
+ #[test]
+ fn a_saved_list_keeps_its_order_and_gains_new_sources_in_place() {
+ let saved = vec![
+ SourceChoice {
+ source: "lrclib".into(),
+ on: false,
+ },
+ SourceChoice {
+ source: "something_gone".into(),
+ on: true,
+ },
+ SourceChoice {
+ source: "youtube".into(),
+ on: true,
+ },
+ SourceChoice {
+ source: "lrclib".into(),
+ on: true,
+ },
+ ];
+ // BetterLyrics follows nothing, so it goes on top; each other new one follows its
+ // neighbour in the default order.
+ assert_eq!(
+ normalise(&saved),
+ vec![
+ (BetterLyrics, true),
+ (LrcRed, true),
+ (YouTubeSynced, true),
+ (Lrclib, false),
+ (KuGou, true),
+ (Unison, true),
+ (YouTube, true),
+ ]
+ );
+ assert_eq!(
+ asked(&saved),
+ vec![BetterLyrics, LrcRed, YouTubeSynced, KuGou, Unison, YouTube]
+ );
+ }
+
+ #[test]
+ fn titles_and_artists_match_across_spellings() {
+ assert_eq!(title_core("Glue (Edit)"), "glue");
+ assert_eq!(title_core("Glue - 2017 Remaster"), "glue");
+ assert_eq!(title_core("(Intro)"), "intro");
+ assert!(version_words("Glue").is_empty());
+ assert_eq!(
+ version_words("Blinding Lights (Live) - Acoustic")
+ .into_iter()
+ .collect::>(),
+ ["acoustic", "live"]
+ );
+ assert_eq!(
+ artist_names("The Weeknd & Rosalía feat. Someone"),
+ ["the weeknd", "rosalía", "someone"]
+ );
+ assert_eq!(artist_names("Simon and Garfunkel"), ["simon", "garfunkel"]);
+ }
+
+ #[test]
+ fn keys_round_trip() {
+ for s in Source::ALL {
+ assert_eq!(Source::from_key(s.key()), Some(s));
+ }
+ }
+}
diff --git a/crates/refryt/src/lyrics/unison.rs b/crates/refryt/src/lyrics/unison.rs
new file mode 100644
index 0000000..cd46174
--- /dev/null
+++ b/crates/refryt/src/lyrics/unison.rs
@@ -0,0 +1,121 @@
+//! Unison: lyrics contributed and voted on by listeners, from the BetterLyrics project, so it has
+//! songs nobody licenses.
+//!
+//! One GET by title, artist, album and length answers `{"success":…, "data":{"lyrics",
+//! "format", "syncType"}}`: TTML, LRC (word stamps or not), or plain text. Smaller than the
+//! others, but keyless and quick to say no.
+
+use anyhow::{Context, Result};
+use serde::Deserialize;
+
+use crate::model::{Lyrics, Track};
+
+const ENDPOINT: &str = "https://unison.boidu.dev/lyrics";
+
+#[derive(Deserialize)]
+struct Response {
+ #[serde(default)]
+ success: bool,
+ data: Option,
+}
+
+#[derive(Deserialize)]
+struct Entry {
+ lyrics: Option,
+ format: Option,
+ #[serde(rename = "syncType")]
+ sync_type: Option,
+}
+
+pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> {
+ let mut query: Vec<(&str, String)> = vec![
+ ("song", track.title.clone()),
+ ("artist", track.artist_line()),
+ ];
+ if let Some(album) = track.album.as_deref().filter(|a| !a.is_empty()) {
+ query.push(("album", album.to_owned()));
+ }
+ if let Some(seconds) = track.duration.filter(|d| *d > 0) {
+ query.push(("duration", seconds.to_string()));
+ }
+ let response = http
+ .get(ENDPOINT)
+ .query(&query)
+ .header(reqwest::header::USER_AGENT, super::USER_AGENT)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .context("Unison")?;
+ if response.status() == reqwest::StatusCode::NOT_FOUND {
+ return Ok(None);
+ }
+ let body: Response = response
+ .error_for_status()
+ .context("Unison")?
+ .json()
+ .await
+ .context("Unison")?;
+ Ok(body.success.then_some(body.data).flatten().and_then(read))
+}
+
+fn read(entry: Entry) -> Option {
+ let text = entry.lyrics.filter(|t| !t.trim().is_empty())?;
+ let is = |field: &Option, value: &str| {
+ field
+ .as_deref()
+ .is_some_and(|f| f.eq_ignore_ascii_case(value))
+ };
+ let mut lyrics = if is(&entry.format, "ttml") {
+ super::better_lyrics::parse_ttml(&text)?
+ } else {
+ let timed = super::lrclib::parse_lrc(&text);
+ if !is(&entry.sync_type, "plain") && !timed.is_empty() {
+ Lyrics {
+ lines: timed,
+ synced: true,
+ source: String::new(),
+ }
+ } else {
+ Lyrics {
+ lines: super::lrclib::plain_lines(&text),
+ synced: false,
+ source: String::new(),
+ }
+ }
+ };
+ lyrics.source = "Unison".to_owned();
+ Some(lyrics)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(lyrics: &str, format: &str, sync: &str) -> Entry {
+ Entry {
+ lyrics: Some(lyrics.to_owned()),
+ format: Some(format.to_owned()),
+ sync_type: Some(sync.to_owned()),
+ }
+ }
+
+ #[test]
+ fn lrc_plain_and_word_stamped_lrc_all_read() {
+ let timed = read(entry("[00:01.00]One\n[00:02.50]Two", "lrc", "line")).unwrap();
+ assert!(timed.synced);
+ assert_eq!(timed.lines[1].at_ms, 2_500);
+
+ let words = read(entry(
+ "[00:01.00]<00:01.00>One <00:01.40>more",
+ "lrc",
+ "word",
+ ))
+ .unwrap();
+ assert_eq!(words.lines[0].text, "One more");
+
+ let plain = read(entry("One\nTwo", "lrc", "plain")).unwrap();
+ assert!(!plain.synced);
+ assert_eq!(plain.lines.len(), 2);
+ assert!(read(entry(" ", "lrc", "line")).is_none());
+ }
+}
diff --git a/crates/refryt/src/lyrics/youtube.rs b/crates/refryt/src/lyrics/youtube.rs
new file mode 100644
index 0000000..0a7fc65
--- /dev/null
+++ b/crates/refryt/src/lyrics/youtube.rs
@@ -0,0 +1,182 @@
+//! YouTube Music's own timed lyrics.
+//!
+//! The website only ever gets plain text (`Api::lyrics`), but YouTube Music's Android app gets
+//! the same lyrics with a start time per line, from Musixmatch or LyricFind. Asked as that app,
+//! the `browse` of a song's lyrics id answers `timedLyricsData`: a list of
+//! `{lyricLine, cueRange: {startTimeMilliseconds, endTimeMilliseconds}}`, and a `sourceMessage`
+//! naming the provider. Checked 2026-11-21: 5 of 6 songs came back timed.
+//!
+//! Always sent without the session's cookie: the lyrics are the same signed out, and these
+//! requests then carry nothing about the account.
+
+use anyhow::{Context, Result};
+use serde_json::{Value, json};
+
+use crate::model::{LyricLine, Lyrics};
+
+const ENDPOINT: &str = "https://music.youtube.com/youtubei/v1";
+const CLIENT_NAME: &str = "ANDROID_MUSIC";
+const CLIENT_VERSION: &str = "7.27.52";
+const USER_AGENT: &str =
+ "com.google.android.apps.youtube.music/7.27.52 (Linux; U; Android 14) gzip";
+
+/// The timed lyrics for `video_id`, or `None` when YouTube has none with timing.
+pub async fn synced(http: &reqwest::Client, video_id: &str) -> Result> {
+ let next = post(http, "next", json!({ "videoId": video_id })).await?;
+ let Some(browse_id) = lyrics_browse_id(&next) else {
+ return Ok(None);
+ };
+ let page = post(http, "browse", json!({ "browseId": browse_id })).await?;
+ Ok(parse_timed(&page))
+}
+
+async fn post(http: &reqwest::Client, endpoint: &str, body: Value) -> Result {
+ let mut body = body;
+ body["context"] = json!({
+ "client": {
+ "clientName": CLIENT_NAME,
+ "clientVersion": CLIENT_VERSION,
+ "androidSdkVersion": 34,
+ "osName": "Android",
+ "osVersion": "14",
+ "hl": "en",
+ }
+ });
+ let response = http
+ .post(format!("{ENDPOINT}/{endpoint}?prettyPrint=false"))
+ .header(reqwest::header::USER_AGENT, USER_AGENT)
+ .json(&body)
+ .timeout(super::SOURCE_TIMEOUT)
+ .send()
+ .await
+ .with_context(|| format!("YouTube {endpoint} for lyrics"))?
+ .error_for_status()
+ .with_context(|| format!("YouTube {endpoint} for lyrics"))?;
+ response
+ .json()
+ .await
+ .with_context(|| format!("YouTube {endpoint} for lyrics"))
+}
+
+/// The lyrics tab's browse id (`MPLYt…`) in a `next` answer.
+fn lyrics_browse_id(next: &Value) -> Option {
+ let mut ids = Vec::new();
+ find_all(next, "browseId", &mut ids);
+ ids.into_iter()
+ .filter_map(Value::as_str)
+ .find(|id| id.starts_with("MPLY"))
+ .map(str::to_owned)
+}
+
+/// The lines of a lyrics page's `timedLyricsData`, with the provider its `sourceMessage` names.
+fn parse_timed(page: &Value) -> Option {
+ let mut found = Vec::new();
+ find_all(page, "timedLyricsData", &mut found);
+ let data = found.into_iter().find_map(Value::as_array)?;
+ let mut lines: Vec = data
+ .iter()
+ .filter_map(|line| {
+ let text = line.get("lyricLine")?.as_str()?;
+ let at_ms = line
+ .pointer("/cueRange/startTimeMilliseconds")
+ .and_then(|v| {
+ v.as_str()
+ .and_then(|s| s.parse().ok())
+ .or_else(|| v.as_u64())
+ })?;
+ Some(LyricLine {
+ at_ms,
+ text: text.trim().to_owned(),
+ romanised: None,
+ })
+ })
+ .collect();
+ if lines.is_empty() {
+ return None;
+ }
+ lines.sort_by_key(|l| l.at_ms);
+ let mut messages = Vec::new();
+ find_all(page, "sourceMessage", &mut messages);
+ let source = messages
+ .into_iter()
+ .find_map(|m| {
+ m.as_str().map(str::to_owned).or_else(|| {
+ m.get("runs")?.as_array().map(|runs| {
+ runs.iter()
+ .filter_map(|r| r.get("text")?.as_str())
+ .collect::()
+ })
+ })
+ })
+ .map(|s| s.trim_start_matches("Source:").trim().to_owned())
+ .unwrap_or_default();
+ Some(Lyrics {
+ lines,
+ synced: true,
+ source,
+ })
+}
+
+/// Every value under `key`, anywhere in `value`.
+fn find_all<'a>(value: &'a Value, key: &str, out: &mut Vec<&'a Value>) {
+ match value {
+ Value::Object(map) => {
+ for (k, v) in map {
+ if k == key {
+ out.push(v);
+ }
+ find_all(v, key, out);
+ }
+ }
+ Value::Array(items) => {
+ for v in items {
+ find_all(v, key, out);
+ }
+ }
+ _ => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_lyrics_tab_id_is_found_among_the_others() {
+ let next = json!({"tabs": [
+ {"endpoint": {"browseId": "MPTRt_abc"}},
+ {"endpoint": {"browseId": "MPLYt_xyz"}},
+ ]});
+ assert_eq!(lyrics_browse_id(&next).as_deref(), Some("MPLYt_xyz"));
+ assert_eq!(lyrics_browse_id(&json!({})), None);
+ }
+
+ /// The shape the Android client answers: string milliseconds, lines in order, and the
+ /// provider named after "Source:".
+ #[test]
+ fn timed_lyrics_parse_with_their_source() {
+ let page = json!({"contents": {"elementRenderer": {"newElement": {"type": {
+ "componentType": {"model": {"timedLyricsModel": {"lyricsData": {
+ "timedLyricsData": [
+ {"lyricLine": "second", "cueRange": {"startTimeMilliseconds": "6290", "endTimeMilliseconds": "9000"}},
+ {"lyricLine": "first ", "cueRange": {"startTimeMilliseconds": "2620", "endTimeMilliseconds": "6290"}},
+ {"cueRange": {"startTimeMilliseconds": "9000"}},
+ ],
+ "sourceMessage": "Source: Musixmatch",
+ }}}}
+ }}}}});
+ let lyrics = parse_timed(&page).unwrap();
+ assert!(lyrics.synced);
+ assert_eq!(lyrics.source, "Musixmatch");
+ assert_eq!(lyrics.lines.len(), 2, "a line with no text is skipped");
+ assert_eq!(lyrics.lines[0].text, "first");
+ assert_eq!(lyrics.lines[0].at_ms, 2620);
+ assert_eq!(lyrics.lines[1].at_ms, 6290);
+ }
+
+ #[test]
+ fn a_page_without_timing_is_none() {
+ let page = json!({"contents": {"messageRenderer": {"text": "Lyrics not available"}}});
+ assert!(parse_timed(&page).is_none());
+ }
+}
diff --git a/crates/refryt/src/main.rs b/crates/refryt/src/main.rs
index 1bc0628..6be3e56 100644
--- a/crates/refryt/src/main.rs
+++ b/crates/refryt/src/main.rs
@@ -12,6 +12,20 @@ fn main() -> eframe::Result {
// Before any other thread exists: how glibc treats freed memory (see `memory.rs`).
refryt::memory::tune();
+ // The GTK colour lookup behind the "GTK" theme (`theme::system`): GTK cannot share the
+ // main thread with the app's window either, so it answers from a child of its own. Before
+ // the log and the crash hook: the helper isn't the app, and its failing (the app quit
+ // before it answered, or GTK fell over) must not leave a crash report behind as if the app
+ // had crashed. The app just goes without the GTK theme.
+ #[cfg(target_os = "linux")]
+ if std::env::args().any(|a| a == refryt::theme::system::GTK_ARG) {
+ std::process::exit(if refryt::theme::system::gtk_child() {
+ 0
+ } else {
+ 1
+ });
+ }
+
// The Discord crate's one warning is "Discord isn't running", repeated on every retry while
// Rich Presence is on: a third of a long log, saying nothing.
refryt::init_tracing("warn,refryt=info,discord_rich_presence=error");
diff --git a/crates/refryt/src/model.rs b/crates/refryt/src/model.rs
index 88f11e8..5dfd210 100644
--- a/crates/refryt/src/model.rs
+++ b/crates/refryt/src/model.rs
@@ -948,6 +948,9 @@ pub struct Lyrics {
pub struct LyricLine {
pub at_ms: u64,
pub text: String,
+ /// The line in Latin letters (Japanese romaji, Korean, pinyin), when the source gave one:
+ /// only Apple's lyrics do. Shown with the line while "Prefer romanised lyrics" is on.
+ pub romanised: Option,
}
/// A playlist id without its browse `VL` prefix. Browses want `VL{id}`; the edit endpoint
diff --git a/crates/refryt/src/settings.rs b/crates/refryt/src/settings.rs
index 1a8f106..656bf7e 100644
--- a/crates/refryt/src/settings.rs
+++ b/crates/refryt/src/settings.rs
@@ -420,10 +420,19 @@ pub struct Settings {
/// The networks the cast receiver runs on (see `crate::network`). Turning casting on allows
/// the network the computer is on; anywhere else it stays off until allowed there too.
pub cast_networks: Vec,
- /// Ask LRCLIB for synced lyrics. On by default; off, lyrics come from YouTube alone, as
- /// plain text. LRCLIB gets the song's title, artist, album and length while the lyrics are
- /// shown, so it is a switch: see PRIVACY.md.
- pub lrclib_lyrics: bool,
+ /// The lyrics sources, in the order they are asked, each on or off (see [`crate::lyrics`]).
+ /// Empty is the default list. Read through [`crate::lyrics::normalise`], which drops names
+ /// this build doesn't know and slots in sources added since the list was saved. Each source
+ /// gets the song's details while lyrics are shown, so each is a switch: see PRIVACY.md.
+ pub lyrics_sources: Vec,
+ /// "Prefer romanised lyrics": a source with romanised lines (romaji, Korean in Latin
+ /// letters, pinyin) wins for a song in those scripts, and its lines lead with the
+ /// romanisation, the original under it. Apple's lyrics carry it, and some LRC files do.
+ pub lyrics_romanisation: bool,
+ /// Before there were several sources: whether LRCLIB was asked. Read from an older file,
+ /// folded into [`Self::lyrics_sources`] by [`Settings::migrate_legacy`], never written back.
+ #[serde(default, skip_serializing)]
+ lrclib_lyrics: Option,
/// Folders scanned for local audio files, shown in the Library's Local tab. Absolute paths,
/// same shape as `playlist_order`.
pub local_folders: Vec,
@@ -486,7 +495,9 @@ impl Default for Settings {
discord_rich_presence: false,
cast_receiver: false,
cast_networks: Vec::new(),
- lrclib_lyrics: true,
+ lyrics_sources: Vec::new(),
+ lyrics_romanisation: true,
+ lrclib_lyrics: None,
local_folders: Vec::new(),
playlist_default_sort: crate::app::PlaylistSort::Default,
sidebar_width: None,
@@ -499,6 +510,19 @@ impl Default for Settings {
}
impl Settings {
+ /// The settings of a first start, with no settings file yet: the defaults, on the
+ /// platform's own themes ([`crate::theme::custom::platform_default`]). [`Default`] keeps
+ /// Classic, since it also fills the fields an existing file leaves out, and a file from
+ /// before themes were named was on Classic.
+ pub fn fresh() -> Self {
+ let (dark, light) = crate::theme::custom::platform_default();
+ Self {
+ dark_theme: dark.to_owned(),
+ light_theme: light.to_owned(),
+ ..Self::default()
+ }
+ }
+
/// The theme chosen for this polarity, if it loaded and is of that polarity.
pub fn chosen_theme<'a>(&self, dark: bool, themes: &'a Themes) -> Option<&'a CustomTheme> {
let name = if dark {
@@ -506,6 +530,9 @@ impl Settings {
} else {
&self.light_theme
};
+ if crate::theme::system::is_system(name) {
+ return themes.system_theme(name, dark);
+ }
themes.get(name).filter(|t| t.dark == dark)
}
@@ -538,6 +565,14 @@ impl Settings {
/// and flavour become the theme files they were turned into, and a custom theme picked over
/// them goes to the polarity it declares. Idempotent; the old fields are never saved.
pub fn migrate_legacy(&mut self, themes: &Themes) {
+ // LRCLIB switched off in the one-switch days stays off in the list.
+ if self.lrclib_lyrics.take() == Some(false) && self.lyrics_sources.is_empty() {
+ let list: Vec<_> = crate::lyrics::normalise(&[])
+ .into_iter()
+ .map(|(s, on)| (s, on && s != crate::lyrics::Source::Lrclib))
+ .collect();
+ self.lyrics_sources = crate::lyrics::to_choices(&list);
+ }
if let Some(family) = self.scheme.take()
&& let Some((dark, light)) = legacy_names(&family, self.scheme_variant.as_deref())
{
@@ -614,8 +649,10 @@ pub fn load() -> Settings {
let Ok(path) = path() else {
return Settings::default();
};
- let Ok(bytes) = std::fs::read(&path) else {
- return Settings::default();
+ let bytes = match std::fs::read(&path) {
+ Ok(bytes) => bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Settings::fresh(),
+ Err(_) => return Settings::default(),
};
serde_json::from_slice(&bytes).unwrap_or_else(|e| {
tracing::warn!(error = %e, "settings file could not be parsed; using defaults");
@@ -667,15 +704,94 @@ mod tests {
partial.autoplay,
"an older settings file without the toggle must still autoplay"
);
+ assert_eq!(
+ crate::lyrics::asked(&partial.lyrics_sources),
+ crate::lyrics::Source::ALL.to_vec(),
+ "an older settings file asks every lyrics source"
+ );
+ }
+
+ /// LRCLIB switched off before there were several sources stays off; the others are on.
+ #[test]
+ fn lrclib_switched_off_stays_off_in_the_source_list() {
+ let mut old: Settings = serde_json::from_str(r#"{"lrclib_lyrics":false}"#).unwrap();
+ old.migrate_legacy(&Themes::default());
+ use crate::lyrics::Source::*;
+ assert_eq!(
+ crate::lyrics::asked(&old.lyrics_sources),
+ vec![BetterLyrics, LrcRed, YouTubeSynced, KuGou, Unison, YouTube]
+ );
+ let json = serde_json::to_string(&old).unwrap();
+ assert!(
+ !json.contains("lrclib_lyrics"),
+ "the old switch is not written back"
+ );
+
+ let mut on: Settings = serde_json::from_str(r#"{"lrclib_lyrics":true}"#).unwrap();
+ on.migrate_legacy(&Themes::default());
assert!(
- partial.lrclib_lyrics,
- "an older settings file without the toggle keeps synced lyrics"
+ on.lyrics_sources.is_empty(),
+ "on was the default: nothing to keep"
);
}
/// The literal shape of every file on disk before this milestone: a theme and the tint
/// toggle that no longer exists. It must still parse, and land on today's defaults for the
/// three fields it never mentioned — this is the actual migration every user's file takes.
+ /// The desktop's theme paints whatever the mode, and only when the desktop gave one.
+ #[test]
+ fn a_desktop_theme_paints_in_either_mode() {
+ let qt = crate::theme::custom::parse(
+ crate::theme::system::QT,
+ "--base:#ffffff;--text:#222222;--accent:#3366cc;",
+ )
+ .unwrap();
+ let mut themes = Themes::default();
+ let s = Settings {
+ dark_theme: crate::theme::system::QT.into(),
+ light_theme: crate::theme::system::QT.into(),
+ ..Settings::default()
+ };
+ assert!(
+ s.chosen_theme(true, &themes).is_none(),
+ "not on a KDE desktop"
+ );
+ themes.set_system(crate::theme::system::QT, vec![qt]);
+ assert_eq!(
+ s.chosen_theme(true, &themes).map(|t| t.name.as_str()),
+ Some("Qt"),
+ "a light desktop theme still paints in dark mode"
+ );
+ assert!(s.chosen_theme(false, &themes).is_some());
+ }
+
+ /// A first start gets the platform's themes, and they ship with the app; an existing file
+ /// that never named a theme stays on Classic.
+ #[test]
+ fn a_fresh_install_starts_on_the_platform_theme() {
+ let fresh = Settings::fresh();
+ let shipped = |name: &str| {
+ crate::theme::custom::BUILTIN
+ .iter()
+ .any(|(n, css)| *n == name && crate::theme::custom::parse(n, css).is_ok())
+ };
+ assert!(shipped(&fresh.dark_theme) && shipped(&fresh.light_theme));
+ let parse = |n: &str| {
+ let (_, css) = crate::theme::custom::BUILTIN
+ .iter()
+ .find(|(b, _)| *b == n)
+ .unwrap();
+ crate::theme::custom::parse(n, css).unwrap()
+ };
+ assert!(parse(&fresh.dark_theme).dark && !parse(&fresh.light_theme).dark);
+ if cfg!(target_os = "macos") {
+ assert_eq!(fresh.dark_theme, "macOS Dark");
+ } else if cfg!(target_os = "windows") {
+ assert_eq!(fresh.dark_theme, "Windows Dark");
+ }
+ assert_eq!(Settings::default().dark_theme, "Classic Dark");
+ }
+
#[test]
fn a_settings_file_from_before_schemes_still_loads() {
let migrated: Settings =
@@ -900,7 +1016,7 @@ mod tests {
crate::theme::custom::parse("Night", &css("#101010", "dark")).unwrap(),
crate::theme::custom::parse("Paper", &css("#fafafa", "light")).unwrap(),
],
- errors: Vec::new(),
+ ..Themes::default()
};
let s = Settings {
dark_theme: "Deleted".into(),
diff --git a/crates/refryt/src/theme.rs b/crates/refryt/src/theme.rs
index 631ebd9..beb346b 100644
--- a/crates/refryt/src/theme.rs
+++ b/crates/refryt/src/theme.rs
@@ -14,6 +14,7 @@ use egui::{Color32, CornerRadius, Stroke};
pub mod custom;
mod ramp;
+pub mod system;
// ---------------------------------------------------------------------------------------------
// Metrics
diff --git a/crates/refryt/src/theme/custom.rs b/crates/refryt/src/theme/custom.rs
index 82b54d9..5b1efa3 100644
--- a/crates/refryt/src/theme/custom.rs
+++ b/crates/refryt/src/theme/custom.rs
@@ -58,9 +58,25 @@ pub struct Themes {
pub themes: Vec,
/// `(file name, reason)` for each file that failed to parse.
pub errors: Vec<(String, String)>,
+ /// The desktop's GTK and Qt themes ([`super::system`]), kept apart from the files: they
+ /// are read from the desktop, not the folder, and offered in both modes.
+ pub system: Vec,
}
impl Themes {
+ /// A desktop theme by name: the variant of this polarity if there is one, else the only
+ /// one, since following the desktop means its colours whatever the mode.
+ pub fn system_theme(&self, name: &str, dark: bool) -> Option<&CustomTheme> {
+ let named = || self.system.iter().filter(move |t| t.name == name);
+ named().find(|t| t.dark == dark).or_else(|| named().next())
+ }
+
+ /// Replace the desktop themes called `name` with `fresh`.
+ pub fn set_system(&mut self, name: &str, fresh: Vec) {
+ self.system.retain(|t| t.name != name);
+ self.system.extend(fresh);
+ }
+
pub fn get(&self, name: &str) -> Option<&CustomTheme> {
self.themes.iter().find(|t| t.name == name)
}
@@ -210,12 +226,48 @@ pub const BUILTIN: &[(&str, &str)] = &[
include_str!("../../themes/Tokyo Night Storm.css"),
),
("Spotify", include_str!("../../themes/Spotify.css")),
+ ("macOS Dark", include_str!("../../themes/macOS Dark.css")),
+ ("macOS Light", include_str!("../../themes/macOS Light.css")),
+ (
+ "Windows Dark",
+ include_str!("../../themes/Windows Dark.css"),
+ ),
+ (
+ "Windows Light",
+ include_str!("../../themes/Windows Light.css"),
+ ),
+ ("Breeze Dark", include_str!("../../themes/Breeze Dark.css")),
+ (
+ "Breeze Light",
+ include_str!("../../themes/Breeze Light.css"),
+ ),
];
+/// The themes a fresh install starts on, `(dark, light)`: the system's own colours on macOS and
+/// Windows, Classic elsewhere. Only a fresh install: a settings file that already exists keeps
+/// what it names, so nobody's look changes on an update.
+pub const fn platform_default() -> (&'static str, &'static str) {
+ if cfg!(target_os = "macos") {
+ ("macOS Dark", "macOS Light")
+ } else if cfg!(target_os = "windows") {
+ ("Windows Dark", "Windows Light")
+ } else {
+ ("Classic Dark", "Classic Light")
+ }
+}
+
/// Built-in themes added after the first release that shipped themes. A folder made before the
/// app kept its [`OFFERED`] record was given every other built-in, so these are the ones it still
/// needs offering.
-const ADDED_LATER: &[&str] = &["Spotify"];
+const ADDED_LATER: &[&str] = &[
+ "Spotify",
+ "macOS Dark",
+ "macOS Light",
+ "Windows Dark",
+ "Windows Light",
+ "Breeze Dark",
+ "Breeze Light",
+];
/// The file in the themes folder that names every built-in theme already written there once. A
/// newer release writes only the built-ins missing from it, so a new theme reaches an existing
@@ -400,7 +452,7 @@ pub fn parse(name: &str, src: &str) -> Result {
})
}
-fn hex(c: u32) -> Color32 {
+pub(super) fn hex(c: u32) -> Color32 {
Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}
@@ -464,7 +516,7 @@ fn declarations(src: &str) -> Vec<(usize, String)> {
}
/// `#rgb`, `#rrggbb`, or `rgb(r, g, b)` / `rgb(r g b)`.
-fn parse_colour(value: &str) -> Option {
+pub(super) fn parse_colour(value: &str) -> Option {
let v = value.trim();
if let Some(h) = v.strip_prefix('#') {
let h: String = match h.len() {
@@ -791,7 +843,7 @@ mod tests {
fn a_theme_is_found_however_its_name_is_typed() {
let themes = Themes {
themes: builtins(),
- errors: Vec::new(),
+ ..Themes::default()
};
for q in [
"catppuccin-frappe",
diff --git a/crates/refryt/src/theme/system.rs b/crates/refryt/src/theme/system.rs
new file mode 100644
index 0000000..3ea2c6b
--- /dev/null
+++ b/crates/refryt/src/theme/system.rs
@@ -0,0 +1,445 @@
+//! Following the desktop's own toolkit theme, as Chrome's "GTK" and "Qt" appearance options do.
+//!
+//! Two entries at the top of the Theme list on Linux, each a theme built from the desktop's
+//! colours rather than read from a file:
+//!
+//! - **Qt** reads KDE's colour scheme from `kdeglobals`, which is where Qt apps on Plasma get
+//! their palette. A scheme section missing there comes from the scheme's own `.colors` file.
+//! - **GTK** asks GTK 3 itself: a child of this binary (`--gtk-colours`, like the sign-in
+//! window's child, since GTK cannot share the main thread with the app's window) starts GTK,
+//! looks up the theme's named colours (`theme_bg_color`, `theme_selected_bg_color`, …) once
+//! with the dark variant asked for and once without, prints them and exits.
+//!
+//! Either becomes ordinary theme CSS run through [`super::custom::parse`], so everything a file
+//! leaves out is derived the same way, and low contrast is a warning under the dropdown rather
+//! than a refusal: the colours are the desktop's, not refryt's to fix. Both are read again when
+//! the window is focused, so changing the desktop's theme repaints the app on the way back.
+
+use std::collections::HashMap;
+
+use egui::Color32;
+
+use super::custom::{CustomTheme, parse};
+
+pub const GTK: &str = "GTK";
+pub const QT: &str = "Qt";
+/// Both, in the order the Theme list shows them.
+pub const GTK_AND_QT: [&str; 2] = [GTK, QT];
+
+/// Whether a theme name is one of these, rather than a file.
+pub fn is_system(name: &str) -> bool {
+ name == GTK || name == QT
+}
+
+/// The argument that makes the binary the GTK child.
+pub const GTK_ARG: &str = "--gtk-colours";
+
+/// The GTK colours a theme is built from, by GTK's own names.
+const GTK_NAMES: [&str; 9] = [
+ "theme_bg_color",
+ "theme_base_color",
+ "theme_fg_color",
+ "theme_text_color",
+ "theme_selected_bg_color",
+ "theme_selected_fg_color",
+ "borders",
+ "error_color",
+ "warning_color",
+];
+
+/// The slots one theme fills, by refryt's variable names. `base`, `text` and `accent` are
+/// required; the rest fall back to what the parser derives.
+#[derive(Clone, Debug, Default, PartialEq)]
+struct Slots {
+ window: Option,
+ view: Option,
+ text: Option,
+ accent: Option,
+ on_accent: Option,
+ surface: Option,
+ subtext: Option,
+ outline: Option,
+ danger: Option,
+ warning: Option,
+}
+
+/// The theme these slots make, named `name`. The lighter of the window and view colours is the
+/// cards and the darker the gap behind them, which is how both toolkits' default themes read in
+/// refryt's layout; when they are the same, the gap is derived. Text on the accent is the
+/// toolkit's own when it reads at 3:1, else black or white, whichever reads better.
+fn theme(name: &str, s: &Slots) -> Option {
+ let (window, view) = (s.window, s.view);
+ let (base, gutter) = match (window, view) {
+ (Some(w), Some(v)) if w != v => {
+ if super::ramp::luminance(v) >= super::ramp::luminance(w) {
+ (v, Some(w))
+ } else {
+ (w, Some(v))
+ }
+ }
+ (Some(c), _) | (None, Some(c)) => (c, None),
+ (None, None) => return None,
+ };
+ let text = s.text?;
+ let accent = s.accent?;
+ let on_accent = s
+ .on_accent
+ .filter(|c| super::ramp::contrast(*c, accent) >= 3.0)
+ .unwrap_or_else(|| {
+ if super::ramp::contrast(Color32::BLACK, accent)
+ >= super::ramp::contrast(Color32::WHITE, accent)
+ {
+ Color32::BLACK
+ } else {
+ Color32::WHITE
+ }
+ });
+ let mut css = String::from(":root {\n");
+ let mut put = |var: &str, c: Option| {
+ if let Some(c) = c {
+ css.push_str(&format!(
+ " --{var}: #{:02x}{:02x}{:02x};\n",
+ c.r(),
+ c.g(),
+ c.b()
+ ));
+ }
+ };
+ put("base", Some(base));
+ put("text", Some(text));
+ put("accent", Some(accent));
+ put("on-accent", Some(on_accent));
+ put("gutter", gutter);
+ put("surface", s.surface.filter(|c| *c != base));
+ put("subtext", s.subtext.filter(|c| *c != text));
+ put("outline", s.outline);
+ put("danger", s.danger);
+ put("warning", s.warning);
+ css.push_str("}\n");
+ parse(name, &css).ok()
+}
+
+/// `r,g,b` or `r,g,b,a` as KDE writes a colour.
+fn kde_colour(value: &str) -> Option {
+ let parts: Vec = value
+ .split(',')
+ .map(|p| p.trim().parse().ok())
+ .collect::>()?;
+ match parts[..] {
+ [r, g, b] | [r, g, b, _] => Some(Color32::from_rgb(r, g, b)),
+ _ => None,
+ }
+}
+
+type Ini = HashMap>;
+
+/// An INI file as sections of keys. Later keys win, as KDE reads them.
+fn ini(text: &str) -> Ini {
+ let mut out = Ini::new();
+ let mut section = String::new();
+ for line in text.lines().map(str::trim) {
+ if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
+ section = name.to_owned();
+ } else if let Some((k, v)) = line.split_once('=')
+ && !line.starts_with('#')
+ {
+ out.entry(section.clone())
+ .or_default()
+ .insert(k.trim().to_owned(), v.trim().to_owned());
+ }
+ }
+ out
+}
+
+/// The Qt theme from `kdeglobals`, with `scheme` (the `.colors` file `[General] ColorScheme`
+/// names) filling whatever colour `kdeglobals` itself leaves out.
+fn from_kde(kdeglobals: &str, scheme: Option<&str>) -> Option {
+ let mut colours = scheme.map(ini).unwrap_or_default();
+ for (section, keys) in ini(kdeglobals) {
+ colours.entry(section).or_default().extend(keys);
+ }
+ let get = |section: &str, key: &str| {
+ colours
+ .get(&format!("Colors:{section}"))
+ .and_then(|s| s.get(key))
+ .and_then(|v| kde_colour(v))
+ };
+ theme(
+ QT,
+ &Slots {
+ window: get("Window", "BackgroundNormal"),
+ view: get("View", "BackgroundNormal"),
+ text: get("View", "ForegroundNormal").or(get("Window", "ForegroundNormal")),
+ accent: get("Selection", "BackgroundNormal"),
+ on_accent: get("Selection", "ForegroundNormal"),
+ surface: get("Button", "BackgroundNormal"),
+ subtext: get("View", "ForegroundInactive"),
+ outline: None,
+ danger: get("View", "ForegroundNegative"),
+ warning: get("View", "ForegroundNeutral"),
+ },
+ )
+}
+
+/// The GTK themes from the child's answer: one per variant it reported, the dark one first, and
+/// only one when the theme has no separate dark variant.
+fn from_gtk(answer: &str) -> Vec {
+ let Ok(variants) = serde_json::from_str::>>(answer)
+ else {
+ return Vec::new();
+ };
+ let mut out: Vec = Vec::new();
+ for variant in ["dark", "light"] {
+ let Some(c) = variants.get(variant) else {
+ continue;
+ };
+ let colour = |name: &str| {
+ c.get(name)
+ .and_then(|v| super::custom::parse_colour(v))
+ .map(super::custom::hex)
+ };
+ if let Some(t) = theme(
+ GTK,
+ &Slots {
+ window: colour("theme_bg_color"),
+ view: colour("theme_base_color"),
+ text: colour("theme_text_color").or(colour("theme_fg_color")),
+ accent: colour("theme_selected_bg_color"),
+ on_accent: colour("theme_selected_fg_color"),
+ surface: None,
+ subtext: None,
+ outline: colour("borders"),
+ danger: colour("error_color"),
+ warning: colour("warning_color"),
+ },
+ ) && !out.iter().any(|o| o == &t)
+ {
+ out.push(t);
+ }
+ }
+ out
+}
+
+/// The Qt theme as KDE has it now, if this is a KDE desktop.
+#[cfg(target_os = "linux")]
+pub fn qt() -> Option {
+ let config = directories::BaseDirs::new()?;
+ let kdeglobals = std::fs::read_to_string(config.config_dir().join("kdeglobals")).ok()?;
+ let name = ini(&kdeglobals)
+ .get("General")
+ .and_then(|g| g.get("ColorScheme"))
+ .cloned();
+ let scheme = name.and_then(|name| {
+ let file = format!("{name}.colors");
+ let mut places = vec![config.data_local_dir().join("color-schemes").join(&file)];
+ let data_dirs =
+ std::env::var("XDG_DATA_DIRS").unwrap_or_else(|_| "/usr/local/share:/usr/share".into());
+ places.extend(
+ data_dirs
+ .split(':')
+ .filter(|d| !d.is_empty())
+ .map(|d| std::path::Path::new(d).join("color-schemes").join(&file)),
+ );
+ places
+ .into_iter()
+ .find_map(|p| std::fs::read_to_string(p).ok())
+ });
+ from_kde(&kdeglobals, scheme.as_deref())
+}
+
+#[cfg(not(target_os = "linux"))]
+pub fn qt() -> Option {
+ None
+}
+
+/// Run the GTK child and read its answer: the GTK themes, or none when GTK could not start
+/// (no display, no GTK) within a few seconds.
+#[cfg(target_os = "linux")]
+pub fn gtk() -> Vec {
+ use std::io::Read;
+ use std::process::{Command, Stdio};
+
+ let Ok(exe) = std::env::current_exe() else {
+ return Vec::new();
+ };
+ let Ok(mut child) = Command::new(exe)
+ .arg(GTK_ARG)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ else {
+ return Vec::new();
+ };
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(4);
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => break,
+ Ok(None) if std::time::Instant::now() < deadline => {
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ tracing::warn!("the GTK colour lookup did not answer in time");
+ return Vec::new();
+ }
+ }
+ }
+ let mut answer = String::new();
+ if let Some(mut out) = child.stdout.take() {
+ let _ = out.read_to_string(&mut answer);
+ }
+ from_gtk(&answer)
+}
+
+#[cfg(not(target_os = "linux"))]
+pub fn gtk() -> Vec {
+ Vec::new()
+}
+
+/// The child's half: start GTK, look the colours up with the dark variant asked for and
+/// without, and print them as JSON on one line. `false` when GTK could not start.
+#[cfg(target_os = "linux")]
+pub fn gtk_child() -> bool {
+ use gtk::prelude::*;
+
+ if gtk::init().is_err() {
+ return false;
+ }
+ let Some(settings) = gtk::Settings::default() else {
+ return false;
+ };
+ let mut answer: HashMap<&str, HashMap<&str, String>> = HashMap::new();
+ for (variant, dark) in [("dark", true), ("light", false)] {
+ settings.set_gtk_application_prefer_dark_theme(dark);
+ while gtk::events_pending() {
+ gtk::main_iteration_do(false);
+ }
+ // A fresh widget, so its style is the variant just asked for.
+ let probe = gtk::Window::new(gtk::WindowType::Toplevel);
+ let style = probe.style_context();
+ let mut colours = HashMap::new();
+ for name in GTK_NAMES {
+ if let Some(c) = style.lookup_color(name) {
+ let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ colours.insert(
+ name,
+ format!(
+ "#{:02x}{:02x}{:02x}",
+ byte(c.red()),
+ byte(c.green()),
+ byte(c.blue())
+ ),
+ );
+ }
+ }
+ answer.insert(variant, colours);
+ // SAFETY: the probe was never shown and nothing else holds it.
+ unsafe { probe.destroy() };
+ }
+ // Written, not `println!`: if the app quit while GTK was starting, nobody is reading any
+ // more, and `println!` panics on the closed pipe.
+ use std::io::Write;
+ match serde_json::to_string(&answer) {
+ Ok(line) => writeln!(std::io::stdout(), "{line}").is_ok(),
+ Err(_) => false,
+ }
+}
+
+/// Reads the GTK colours off the UI thread: the child takes a moment, and the app keeps
+/// painting meanwhile. The answer is picked up by [`GtkWatch::take`].
+#[derive(Default)]
+pub struct GtkWatch {
+ slot: std::sync::Arc>>>,
+ running: std::sync::Arc,
+}
+
+impl GtkWatch {
+ /// Ask again, unless an answer is already on its way.
+ pub fn refresh(&self, ctx: &egui::Context) {
+ if !cfg!(target_os = "linux")
+ || self.running.swap(true, std::sync::atomic::Ordering::AcqRel)
+ {
+ return;
+ }
+ let slot = self.slot.clone();
+ let running = self.running.clone();
+ let ctx = ctx.clone();
+ std::thread::spawn(move || {
+ let themes = gtk();
+ if let Ok(mut s) = slot.lock() {
+ *s = Some(themes);
+ }
+ running.store(false, std::sync::atomic::Ordering::Release);
+ ctx.request_repaint();
+ });
+ }
+
+ /// The answer that came in since the last call, if one did.
+ pub fn take(&self) -> Option> {
+ self.slot.lock().ok()?.take()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const BREEZE_DARK: &str = "[Colors:Window]\nBackgroundNormal=32,35,38\nForegroundNormal=252,252,252\n\
+ [Colors:View]\nBackgroundNormal=20,22,24\nForegroundNormal=252,252,252\nForegroundInactive=161,169,177\n\
+ ForegroundNegative=218,68,83\nForegroundNeutral=246,116,0\n\
+ [Colors:Selection]\nBackgroundNormal=61,174,233\nForegroundNormal=252,252,252\n\
+ [Colors:Button]\nBackgroundNormal=41,44,48\n";
+
+ #[test]
+ fn kde_colours_make_a_qt_theme() {
+ let t = from_kde(BREEZE_DARK, None).unwrap();
+ assert_eq!(t.name, QT);
+ assert!(t.dark);
+ let p = t.palette();
+ assert_eq!(
+ p.panel,
+ Color32::from_rgb(32, 35, 38),
+ "the lighter one is the cards"
+ );
+ assert_eq!(
+ p.window,
+ Color32::from_rgb(20, 22, 24),
+ "the darker one the gap"
+ );
+ assert_eq!(p.accent, Color32::from_rgb(61, 174, 233));
+ }
+
+ /// `kdeglobals` that only names its scheme gets the colours from the scheme's file, and
+ /// its own keys win over the file's.
+ #[test]
+ fn a_scheme_file_fills_what_kdeglobals_leaves_out() {
+ let kdeglobals =
+ "[General]\nColorScheme=BreezeDark\n[Colors:Selection]\nBackgroundNormal=200,0,100\n";
+ let t = from_kde(kdeglobals, Some(BREEZE_DARK)).unwrap();
+ assert_eq!(t.palette().accent, Color32::from_rgb(200, 0, 100));
+ assert!(from_kde("[General]\nColorScheme=Gone\n", None).is_none());
+ }
+
+ #[test]
+ fn unreadable_text_on_the_accent_is_replaced() {
+ // KDE's own white on Breeze blue is 2.4:1.
+ let t = from_kde(BREEZE_DARK, None).unwrap();
+ assert!(super::super::ramp::contrast(t.palette().on_accent, t.palette().accent) >= 3.0);
+ }
+
+ #[test]
+ fn gtk_variants_become_themes_and_a_missing_dark_one_is_not_repeated() {
+ let adwaita = r##"{"dark":{"theme_bg_color":"#353535","theme_base_color":"#2d2d2d","theme_fg_color":"#eeeeec","theme_selected_bg_color":"#15539e","theme_selected_fg_color":"#ffffff"},
+ "light":{"theme_bg_color":"#f6f5f4","theme_base_color":"#ffffff","theme_fg_color":"#2e3436","theme_selected_bg_color":"#3584e4","theme_selected_fg_color":"#ffffff"}}"##;
+ let themes = from_gtk(adwaita);
+ assert_eq!(themes.len(), 2);
+ assert!(themes[0].dark && !themes[1].dark);
+
+ let one = r##"{"dark":{"theme_bg_color":"#f6f5f4","theme_base_color":"#ffffff","theme_fg_color":"#2e3436","theme_selected_bg_color":"#3584e4"},
+ "light":{"theme_bg_color":"#f6f5f4","theme_base_color":"#ffffff","theme_fg_color":"#2e3436","theme_selected_bg_color":"#3584e4"}}"##;
+ assert_eq!(from_gtk(one).len(), 1);
+ assert!(from_gtk("not json").is_empty());
+ }
+}
diff --git a/crates/refryt/src/ui/artist.rs b/crates/refryt/src/ui/artist.rs
index 9d25e2c..fcc94c0 100644
--- a/crates/refryt/src/ui/artist.rs
+++ b/crates/refryt/src/ui/artist.rs
@@ -63,22 +63,25 @@ pub fn page(app: &mut App, ui: &mut egui::Ui) {
});
}
-/// The hero when the page carries wide channel art, the circle header otherwise, then the
-/// controls on their own row below either.
-/// How many times you've played the artist on the page, once there's anything to say.
+/// Your listening to the artist on the page — a top rank, or else your plays — once there's
+/// anything to say.
fn your_plays(app: &App) -> Option {
- let (id, plays) = app.artist_plays.as_ref()?;
- (*plays > 0 && app.artist_for.as_deref() == Some(id.as_str()))
- .then(|| crate::listening_stats::plays_label(*plays))
+ let (id, highlight) = app.artist_plays.as_ref()?;
+ if app.artist_for.as_deref() != Some(id.as_str()) {
+ return None;
+ }
+ highlight.line()
}
fn with_your_plays(audience: String, yours: Option) -> String {
match yours {
- Some(plays) => format!("{audience} • {plays} by you"),
+ Some(yours) => format!("{audience} • {yours}"),
None => audience,
}
}
+/// The hero when the page carries wide channel art, the circle header otherwise, then the
+/// controls on their own row below either.
fn header(app: &mut App, ui: &mut egui::Ui) {
let has_hero = app.artist.as_ref().is_some_and(|a| a.hero.is_some());
if has_hero {
@@ -457,7 +460,7 @@ fn hero_header(app: &mut App, ui: &mut egui::Ui) {
// with every other page's header. White, because the scrim is dark whatever the theme is.
let (name_y, meta_y, name_size) = hero_text_lines(rect, width);
let name_font = crate::theme::bold(name_size);
- let meta_font = crate::theme::medium(14.0);
+ let meta_font = crate::theme::medium(15.0);
let text_w = (width - inset_x - 24.0).max(0.0);
crate::emoji::paint_line(
ui,
@@ -622,6 +625,9 @@ fn action_row(app: &mut App, ui: &mut egui::Ui) {
let mut play_clicked = false;
let mut play_target = None;
let mut subscribe_to = None;
+ // Played here before: their stats page is a button away.
+ let has_plays = your_plays(app).is_some();
+ let mut open_stats = None;
let (menu_action, menu_description) = {
let crate::app::App {
palette,
@@ -661,6 +667,13 @@ fn action_row(app: &mut App, ui: &mut egui::Ui) {
{
play_target = Some(target.clone());
}
+ if has_plays
+ && widgets::icon_button(ui, &p, crate::icons::Icon::ChartColumn, 18.0, false)
+ .hint("Your stats")
+ .clicked()
+ {
+ open_stats = Some(a.name.to_lowercase());
+ }
ui.add_space(6.0);
// Your own channel has no subscription to toggle — YouTube refuses the write with a
// 400 either way, and its own page still marks the channel "Subscribed". The button
@@ -764,6 +777,9 @@ fn action_row(app: &mut App, ui: &mut egui::Ui) {
if let Some((subscribe, params)) = subscribe_to {
app.toggle_subscribed(&id, subscribe, params);
}
+ if let Some(name) = open_stats {
+ app.navigate(crate::app::Route::StatsArtist(name));
+ }
match menu_action {
Some(crate::ui::RowAction::PageInfo) => app.page_info = menu_description,
Some(other) => app.row_action(other),
diff --git a/crates/refryt/src/ui/entity_stats.rs b/crates/refryt/src/ui/entity_stats.rs
new file mode 100644
index 0000000..ead3b0e
--- /dev/null
+++ b/crates/refryt/src/ui/entity_stats.rs
@@ -0,0 +1,283 @@
+//! An artist's or a song's stats page: everything the play log says about them, opened from
+//! Stats' top lists or a song's "Your stats".
+
+use chrono::{Datelike, Local, NaiveDate, TimeZone};
+use egui::{pos2, vec2};
+
+use crate::app::{App, Route};
+use crate::entity_stats::{EntityKey, EntityReport, Rank};
+use crate::listening_stats::{listening_time, plays_label};
+use crate::model::Track;
+use crate::ui::listening::{Tile, bar_chart, quiet_line, tiles};
+use crate::ui::{centered, failed, page_title, section};
+use crate::widgets;
+
+pub fn page(app: &mut App, ui: &mut egui::Ui) {
+ let key = match app.current_route() {
+ Route::StatsArtist(name) => EntityKey::Artist(name),
+ Route::StatsSong(id) => EntityKey::Song(id),
+ _ => return,
+ };
+ if let Some(error) = app.entity_error.clone() {
+ page_title(ui, &app.palette, "Stats");
+ failed(app, ui, error, App::retry_route);
+ return;
+ }
+ let Some(report) = app.entity_report.clone().filter(|r| r.key == key) else {
+ widgets::skeleton_shelf(ui, &app.palette, widgets::SkeletonShelfShape::Rows, 8);
+ return;
+ };
+ if report.plays == 0 {
+ page_title(ui, &app.palette, "Stats");
+ centered(
+ app,
+ ui,
+ match key {
+ EntityKey::Artist(_) => "No plays of this artist yet.",
+ EntityKey::Song(_) => "No plays of this song yet.",
+ },
+ );
+ return;
+ }
+ crate::ui::page_scroll(app, "entity-stats").show(ui, |ui| {
+ header(app, ui, &report);
+ totals(app, ui, &report);
+ if let Some((track, at)) = &report.first_song {
+ quiet_line(
+ app,
+ ui,
+ &format!(
+ "Your first song by {} was “{}”, on {}.",
+ report.name,
+ track.title,
+ date(*at)
+ ),
+ );
+ }
+ if !report.top_songs.is_empty() {
+ section(ui, &app.palette, "Your top songs");
+ ui.push_id("entity-top-songs", |ui| {
+ crate::ui::ranked_stats_rows(app, ui, &report.top_songs);
+ });
+ }
+ if report.bars.len() > 1 {
+ // Bars are years once the history is too long for months.
+ let by_year = report.bars.iter().all(|b| b.label.len() == 4);
+ section(
+ ui,
+ &app.palette,
+ if by_year {
+ "Plays by year"
+ } else {
+ "Plays by month"
+ },
+ );
+ bar_chart(ui, &app.palette, &report.bars);
+ }
+ ui.add_space(24.0);
+ });
+}
+
+/// The tracks the header's Play plays: the song, or the artist's top songs.
+fn tracks(report: &EntityReport) -> Vec {
+ match &report.track {
+ Some(track) => vec![track.clone()],
+ None => report
+ .top_songs
+ .iter()
+ .filter_map(|e| match e {
+ crate::model::Entry::Song(t) | crate::model::Entry::Video(t) => {
+ let mut t = t.clone();
+ t.plays = None;
+ Some(t)
+ }
+ _ => None,
+ })
+ .collect(),
+ }
+}
+
+fn header(app: &mut App, ui: &mut egui::Ui, report: &EntityReport) {
+ let p = app.palette;
+ let artist = matches!(report.key, EntityKey::Artist(_));
+ let queue = tracks(report);
+ let playing = app.is_playing_any(&queue);
+ let meta = format!(
+ "{} · {}",
+ plays_label(report.plays),
+ time_text(report.seconds, report.seconds_estimated)
+ );
+ let second = report.rank.map(|r| {
+ format!(
+ "Your #{} {}",
+ r.place,
+ if artist { "artist" } else { "song" }
+ )
+ });
+ let no_artists = [];
+ let artists = report
+ .track
+ .as_ref()
+ .map_or(&no_artists[..], |t| &t.artists[..]);
+ let art_top = ui.cursor().top();
+ let out = {
+ let App {
+ images, backend, ..
+ } = &mut *app;
+ crate::ui::page_header(
+ ui,
+ &p,
+ images,
+ backend,
+ crate::ui::PageHeader {
+ art_url: report.art.as_ref(),
+ art_size: crate::ui::PAGE_ART_SIZE,
+ circle: artist,
+ kind_label: if artist { "Artist stats" } else { "Song stats" },
+ title: &report.name,
+ description: None,
+ artists,
+ second_plain: if artist { second.as_deref() } else { None },
+ meta: Some(&meta),
+ owner: None,
+ credit_air: 5.6,
+ credit_pt: 15.0,
+ play_size: (!queue.is_empty()).then_some(crate::ui::DETAIL_PLAY_PT),
+ playing,
+ save_in_library: None,
+ dots: false,
+ salt: "entity-stats-artist",
+ },
+ )
+ };
+ // Beside Play: the way to the artist's own page, or from a song to its artist's stats.
+ let link = if artist {
+ Some(("Artist page", None))
+ } else {
+ report
+ .track
+ .as_ref()
+ .and_then(|t| t.artists.first())
+ .map(|a| ("Artist stats", Some(a.name.to_lowercase())))
+ };
+ let mut link_clicked = false;
+ if let (Some((label, _)), Some(end)) = (&link, out.controls_end) {
+ // `controls_end` already holds the header's gap after Play and the spacing after that;
+ // 12 pt from Play, as the artist page's own buttons sit.
+ let rect = egui::Rect::from_min_size(pos2(end.x - 8.0, end.y - 18.0), vec2(200.0, 36.0));
+ let mut cell = ui.new_child(
+ egui::UiBuilder::new()
+ .max_rect(rect)
+ .layout(egui::Layout::left_to_right(egui::Align::Center)),
+ );
+ link_clicked = widgets::outline_button(&mut cell, &p, label).clicked();
+ }
+ ui.add_space(out.art_bottom - art_top + 16.0);
+
+ if out.play {
+ if app.queue_matches(&queue) {
+ app.toggle_playback();
+ } else {
+ app.start_from(queue, 0);
+ }
+ }
+ if let Some(route) = out.link {
+ app.navigate(route);
+ }
+ if link_clicked {
+ match link {
+ Some((_, Some(name))) => app.navigate(Route::StatsArtist(name)),
+ Some((_, None)) => match &report.artist_id {
+ Some(id) => app.navigate(Route::Artist(id.clone())),
+ // Known only from an import: no id, so their name is searched instead.
+ None => app.search_again(report.name.clone()),
+ },
+ None => {}
+ }
+ }
+}
+
+fn totals(app: &App, ui: &mut egui::Ui, report: &EntityReport) {
+ let p = app.palette;
+ let rank =
+ |r: Option| r.map_or("–".to_owned(), |r| format!("#{} of {}", r.place, r.of));
+ tiles(
+ ui,
+ &p,
+ &[
+ Tile {
+ label: "Plays",
+ value: report.plays.to_string(),
+ delta: None,
+ },
+ Tile {
+ label: "Listening time",
+ value: time_text(report.seconds, report.seconds_estimated),
+ delta: None,
+ },
+ Tile {
+ label: "First played",
+ value: report.first.map_or("–".to_owned(), date),
+ delta: None,
+ },
+ Tile {
+ label: "Last played",
+ value: report.last.map_or("–".to_owned(), date),
+ delta: None,
+ },
+ ],
+ );
+ let mut second = vec![
+ Tile {
+ label: "Rank, all time",
+ value: rank(report.rank),
+ delta: None,
+ },
+ Tile {
+ label: "Rank, 6 months",
+ value: rank(report.rank_recent),
+ delta: None,
+ },
+ ];
+ if matches!(report.key, EntityKey::Artist(_)) {
+ second.push(Tile {
+ label: "Songs played",
+ value: report.songs.to_string(),
+ delta: None,
+ });
+ }
+ second.push(Tile {
+ label: "Most in a day",
+ value: report.best_day.map_or("–".to_owned(), |(day, plays)| {
+ format!("{plays} on {}", short_date(day))
+ }),
+ delta: None,
+ });
+ tiles(ui, &p, &second);
+}
+
+/// "5 h 12 min", with a "~" once part of it is an estimate.
+fn time_text(seconds: u64, estimated: bool) -> String {
+ if estimated {
+ format!("~{}", listening_time(seconds))
+ } else {
+ listening_time(seconds)
+ }
+}
+
+/// "Mar 3, 2026", in local time.
+fn date(at: i64) -> String {
+ Local
+ .timestamp_opt(at, 0)
+ .earliest()
+ .map_or_else(String::new, |at| at.format("%b %-d, %Y").to_string())
+}
+
+/// "Mar 3" this year, "Mar 3, 2025" before it.
+fn short_date(day: NaiveDate) -> String {
+ if day.year() == Local::now().year() {
+ day.format("%b %-d").to_string()
+ } else {
+ day.format("%b %-d, %Y").to_string()
+ }
+}
diff --git a/crates/refryt/src/ui/fullscreen.rs b/crates/refryt/src/ui/fullscreen.rs
index 0da9202..f914a15 100644
--- a/crates/refryt/src/ui/fullscreen.rs
+++ b/crates/refryt/src/ui/fullscreen.rs
@@ -1487,14 +1487,30 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
}
let font = theme::semibold(m.lyrics);
+ // With romanisation on, a romanised line leads, big, and the original sits under it in the
+ // small type: the one most people read is the one that lights up.
+ let romanise = app.settings.lyrics_romanisation;
+ let lead = |line: &crate::model::LyricLine| -> String {
+ match line.romanised.as_ref().filter(|_| romanise) {
+ Some(roman) => roman.clone(),
+ None => line.text.clone(),
+ }
+ };
+ let under = |line: &crate::model::LyricLine| -> Option {
+ line.romanised
+ .as_ref()
+ .filter(|_| romanise)
+ .map(|_| line.text.clone())
+ };
let galleys: Vec<_> = lyrics
.lines
.iter()
.map(|line| {
- let text = if line.text.is_empty() {
+ let lead = lead(line);
+ let text = if lead.is_empty() {
"♪"
} else {
- line.text.as_str()
+ lead.as_str()
};
ui.painter().layout(
text.to_owned(),
@@ -1504,11 +1520,26 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
)
})
.collect();
+ // The second, smaller line: the original under its romanisation.
+ let roman_font = theme::medium(m.lyrics * 0.55);
+ let roman_gap = m.line_gap * 0.12;
+ let romans: Vec<_> = lyrics
+ .lines
+ .iter()
+ .map(|line| {
+ under(line).map(|r| {
+ ui.painter()
+ .layout(r, roman_font.clone(), Color32::PLACEHOLDER, rect.width())
+ })
+ })
+ .collect();
+ let height_of =
+ |i: usize| galleys[i].size().y + romans[i].as_ref().map_or(0.0, |r| roman_gap + r.size().y);
let mut tops = Vec::with_capacity(galleys.len());
let mut y = 0.0;
- for galley in &galleys {
+ for i in 0..galleys.len() {
tops.push(y);
- y += galley.size().y + m.line_gap;
+ y += height_of(i) + m.line_gap;
}
// A test aid for debug builds: `REFRYT_PLAIN_LYRICS=1` shows timed lyrics as plain text, the
@@ -1527,20 +1558,35 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
let mut child = ui.new_child(UiBuilder::new().max_rect(rect));
let from = painted_so_far(&child);
let plain_font = theme::semibold(m.lyrics * 0.75);
+ let plain_roman = theme::medium(m.lyrics * 0.45);
let gap = m.line_gap * 0.55;
let total: f32 = lyrics
.lines
.iter()
- .map(|line| {
- let text = if line.text.is_empty() {
+ .enumerate()
+ .map(|(i, line)| {
+ let lead = lead(line);
+ let text = if lead.is_empty() {
"♪".to_owned()
} else {
- line.text.clone()
+ lead
};
+ let roman = romans[i].as_ref().map_or(0.0, |_| {
+ ui.painter()
+ .layout(
+ under(line).unwrap_or_default(),
+ plain_roman.clone(),
+ Color32::PLACEHOLDER,
+ rect.width(),
+ )
+ .size()
+ .y
+ });
ui.painter()
.layout(text, plain_font.clone(), Color32::PLACEHOLDER, rect.width())
.size()
.y
+ + roman
+ gap
})
.sum();
@@ -1550,17 +1596,27 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
.show(&mut child, |ui| {
// Words that all fit sit in the middle of their column.
ui.add_space(((rect.height() - total) / 2.0).max(0.0));
- for line in &lyrics.lines {
- let text = if line.text.is_empty() {
+ for (i, line) in lyrics.lines.iter().enumerate() {
+ let lead = lead(line);
+ let text = if lead.is_empty() {
"♪"
} else {
- &line.text
+ lead.as_str()
};
ui.label(
egui::RichText::new(text)
.font(plain_font.clone())
.color(p.text.gamma_multiply(0.85)),
);
+ if romans[i].is_some()
+ && let Some(roman) = under(line)
+ {
+ ui.label(
+ egui::RichText::new(roman)
+ .font(plain_roman.clone())
+ .color(p.text.gamma_multiply(0.6)),
+ );
+ }
ui.add_space(gap);
}
});
@@ -1634,7 +1690,7 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
let mut clicked = None;
for (i, galley) in galleys.iter().enumerate() {
let top_y = anchor + tops[i] - view;
- let height = galley.size().y;
+ let height = height_of(i);
if top_y + height < rect.top() - 40.0 || top_y > rect.bottom() + 40.0 {
continue;
}
@@ -1650,6 +1706,13 @@ fn lyrics_column(app: &mut App, ui: &mut egui::Ui, m: &Metrics, rect: Rect, vide
}
let shown = ctx.animate_value_with_time(Id::new(("fs-lyric-a", i)), want, 0.28);
painter.galley(line_rect.min, galley.clone(), p.text.gamma_multiply(shown));
+ if let Some(roman) = &romans[i] {
+ painter.galley(
+ line_rect.min + vec2(0.0, galley.size().y + roman_gap),
+ roman.clone(),
+ p.text.gamma_multiply(shown * 0.7),
+ );
+ }
if response.clicked() {
clicked = Some(lyrics.lines[i].at_ms);
}
diff --git a/crates/refryt/src/ui/listening.rs b/crates/refryt/src/ui/listening.rs
index 2e687ee..8445357 100644
--- a/crates/refryt/src/ui/listening.rs
+++ b/crates/refryt/src/ui/listening.rs
@@ -150,7 +150,7 @@ fn ago(elapsed: std::time::Duration) -> String {
}
}
-fn quiet_line(app: &App, ui: &mut egui::Ui, text: &str) {
+pub(crate) fn quiet_line(app: &App, ui: &mut egui::Ui, text: &str) {
ui.label(
egui::RichText::new(text)
.font(theme::regular(13.0))
@@ -271,10 +271,10 @@ pub(crate) fn history_gap_note(app: &mut App, ui: &mut egui::Ui) {
}
}
-struct Tile {
- label: &'static str,
- value: String,
- delta: Option,
+pub(crate) struct Tile {
+ pub label: &'static str,
+ pub value: String,
+ pub delta: Option,
}
fn totals(app: &App, ui: &mut egui::Ui, report: &Report) {
@@ -338,7 +338,7 @@ fn streaks(app: &App, ui: &mut egui::Ui, report: &Report) {
}
/// A row of tiles, wrapping two by two where four would be cramped.
-fn tiles(ui: &mut egui::Ui, p: &theme::Palette, tiles: &[Tile]) {
+pub(crate) fn tiles(ui: &mut egui::Ui, p: &theme::Palette, tiles: &[Tile]) {
let width = ui.available_width();
let columns = if width < FOUR_TILES_WIDTH {
tiles.len().min(2)
@@ -471,7 +471,7 @@ fn top_list(app: &mut App, ui: &mut egui::Ui, list: TopList, items: &[crate::mod
.inner;
ui.add_space(8.0);
ui.push_id(title, |ui| {
- crate::ui::ranked_entry_rows(app, ui, &items[..items.len().min(TOP_SHOWN)]);
+ crate::ui::ranked_stats_rows(app, ui, &items[..items.len().min(TOP_SHOWN)]);
});
if show_all {
app.navigate(Route::StatsTop(list));
@@ -502,14 +502,14 @@ pub fn top_page(app: &mut App, ui: &mut egui::Ui, list: TopList) {
if items.is_empty() {
quiet_line(app, ui, "Nothing played in this range.");
} else {
- crate::ui::ranked_entry_rows(app, ui, items);
+ crate::ui::ranked_stats_rows(app, ui, items);
}
ui.add_space(24.0);
});
}
/// Plays over time. A bar's date and count show on hovering it; the ends are labelled below.
-fn bar_chart(ui: &mut egui::Ui, p: &theme::Palette, bars: &[Bar]) {
+pub(crate) fn bar_chart(ui: &mut egui::Ui, p: &theme::Palette, bars: &[Bar]) {
let width = ui.available_width();
let label_height = 20.0;
let (rect, response) =
diff --git a/crates/refryt/src/ui/lyrics.rs b/crates/refryt/src/ui/lyrics.rs
index 111426a..dd60362 100644
--- a/crates/refryt/src/ui/lyrics.rs
+++ b/crates/refryt/src/ui/lyrics.rs
@@ -4,11 +4,13 @@
//! width and insets the queue uses.
use crate::app::App;
+use crate::lyrics::{Answer, Source};
use crate::theme;
use crate::widgets;
pub fn panel(app: &mut App, ui: &mut egui::Ui) {
let p = app.palette;
+ let picker = picker(app);
// The card's own rect, before the header and list consume the ui: the corner repaint at
// the end needs its rounded edges.
let card = widgets::card_rect(ui.available_rect_before_wrap(), theme::CARD_INSET);
@@ -20,7 +22,9 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
// of the way: without this the card's fill stopped short of its right edge. The loaded
// lyrics fill it through their scroll area.
ui.set_min_width(ui.available_width());
- title(ui, &p);
+ if let Some(source) = title(ui, &p, picker.as_ref()) {
+ app.choose_lyrics_source(source);
+ }
ui.horizontal(|ui| {
ui.add_space(2.0);
ui.vertical(|ui| widgets::skeleton_lines(ui, &p, 8));
@@ -28,7 +32,10 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
return;
}
let Some(lyrics) = app.lyrics.as_ref() else {
- title(ui, &p);
+ if let Some(source) = title(ui, &p, picker.as_ref()) {
+ app.choose_lyrics_source(source);
+ return;
+ }
let message = app
.lyrics_error
.clone()
@@ -64,11 +71,12 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
app.lyrics_active = active;
let synced = lyrics.synced;
+ let romanise = app.settings.lyrics_romanisation;
let from = widgets::painted_so_far(ui);
let output = area.show(ui, |ui| {
// Inside the scroll: the title scrolls away with the lyrics rather than staying
// pinned.
- title(ui, &p);
+ let chosen = title(ui, &p, picker.as_ref());
let mut clicked = None;
for (i, line) in lyrics.lines.iter().enumerate() {
// The gap goes before each line but the first, not after each: after the last
@@ -83,11 +91,13 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
} else {
theme::regular(14.0)
};
- let text = if line.text.is_empty() {
- "♪"
- } else {
- &line.text
+ // With romanisation on, the romanised line leads and the original sits under it,
+ // smaller: the one most people read is the one that lights up.
+ let (lead, under) = match line.romanised.as_ref().filter(|_| romanise) {
+ Some(roman) => (roman.as_str(), Some(line.text.as_str())),
+ None => (line.text.as_str(), None),
};
+ let text = if lead.is_empty() { "♪" } else { lead };
// Laid out before the colour is known: a synced line lights up under the
// pointer, which needs the row's rect first. The whole row is the target, so a
// short line is as easy to hit as a long one.
@@ -97,13 +107,25 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
egui::Color32::PLACEHOLDER,
ui.available_width(),
);
+ // The line in Latin letters, under it, when Apple gave one and it's wanted.
+ let roman = under.map(|r| {
+ ui.painter().layout(
+ r.to_owned(),
+ theme::regular(12.0),
+ egui::Color32::PLACEHOLDER,
+ ui.available_width(),
+ )
+ });
+ let roman_height = roman.as_ref().map_or(0.0, |r| r.size().y + 1.0);
let sense = if synced {
egui::Sense::click()
} else {
egui::Sense::hover()
};
- let (rect, response) =
- ui.allocate_exact_size(egui::vec2(ui.available_width(), galley.size().y), sense);
+ let (rect, response) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), galley.size().y + roman_height),
+ sense,
+ );
let hovered = synced && response.hovered();
if hovered {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
@@ -115,7 +137,15 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
} else {
p.secondary
};
+ let line_height = galley.size().y;
ui.painter().galley(rect.min, galley, color);
+ if let Some(roman) = roman {
+ ui.painter().galley(
+ rect.min + egui::vec2(0.0, line_height + 1.0),
+ roman,
+ color.gamma_multiply(0.6),
+ );
+ }
if synced && response.clicked() {
clicked = Some(line.at_ms);
}
@@ -126,11 +156,14 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
);
}
}
- clicked
+ (clicked, chosen)
});
// The title scrolls with the words, so at the top of the lyrics nothing fades there.
widgets::fade_scroll_edges(ui, from, &output, widgets::scroll_fade(&app.settings));
- let clicked = output.inner;
+ let (clicked, chosen) = output.inner;
+ if let Some(source) = chosen {
+ app.choose_lyrics_source(source);
+ }
// A click on a synced line plays from where it starts.
if let Some(at_ms) = clicked {
app.seek_to(at_ms as f64 / 1000.0);
@@ -140,9 +173,54 @@ pub fn panel(app: &mut App, ui: &mut egui::Ui) {
widgets::paint_corner_notches(ui, card, theme::CARD_INSET_X, &p);
}
+/// The source picker beside the title: which source is shown, and the others that found
+/// lyrics for this song. Worked out before the lyrics are borrowed for drawing, so the pick
+/// can be applied to the app after.
+pub(crate) struct Picker {
+ current: String,
+ options: Vec<(Source, String)>,
+ busy: bool,
+}
+
+/// The picker for the song on screen, when more than one source was asked.
+pub(crate) fn picker(app: &App) -> Option {
+ if app.lyrics_order.len() < 2 {
+ return None;
+ }
+ let current = match app.lyrics_shown {
+ Some(source) => source.short_label().to_owned(),
+ None if app.lyrics_loading => "Looking".to_owned(),
+ None => "Sources".to_owned(),
+ };
+ // Only sources that found lyrics: one with none, or still looking, isn't a choice. The
+ // spinner says some are still out.
+ let romanise = app.settings.lyrics_romanisation;
+ let options = app
+ .lyrics_order
+ .iter()
+ .filter_map(|source| match app.lyrics_answers.get(source) {
+ Some(Answer::Found(l)) if l.synced && romanise && crate::lyrics::has_romanised(l) => {
+ Some((*source, format!("{} · romanised", source.short_label())))
+ }
+ Some(Answer::Found(l)) if l.synced => Some((*source, source.short_label().to_owned())),
+ Some(Answer::Found(_)) => {
+ Some((*source, format!("{} · no timing", source.short_label())))
+ }
+ _ => None,
+ })
+ .collect();
+ let busy = app.lyrics_answers.values().any(|a| *a == Answer::Pending);
+ Some(Picker {
+ current,
+ options,
+ busy,
+ })
+}
+
/// The panel's own title, a hair right of the lyrics below it by eye — the same nudge the
-/// queue's own header takes.
-fn title(ui: &mut egui::Ui, p: &theme::Palette) {
+/// queue's own header takes — and the source picker at the right. Returns a source picked.
+fn title(ui: &mut egui::Ui, p: &theme::Palette, picker: Option<&Picker>) -> Option {
+ let mut chosen = None;
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.add_space(2.0);
@@ -151,6 +229,25 @@ fn title(ui: &mut egui::Ui, p: &theme::Palette) {
.font(theme::semibold(14.0))
.color(p.text),
);
+ if let Some(picker) = picker {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ // The same quiet "label ▾" as the queue's radio filter.
+ ui.add_space(2.0);
+ let labels: Vec<&str> = picker.options.iter().map(|o| o.1.as_str()).collect();
+ if let Some(i) = widgets::text_dropdown(
+ ui,
+ p,
+ egui::Id::new("lyrics-source"),
+ &picker.current,
+ &labels,
+ picker.busy,
+ ) && let Some((source, _)) = picker.options.get(i)
+ {
+ chosen = Some(*source);
+ }
+ });
+ }
});
ui.add_space(8.0);
+ chosen
}
diff --git a/crates/refryt/src/ui/lyrics_sources.rs b/crates/refryt/src/ui/lyrics_sources.rs
new file mode 100644
index 0000000..5daf247
--- /dev/null
+++ b/crates/refryt/src/ui/lyrics_sources.rs
@@ -0,0 +1,282 @@
+//! The "Lyrics sources" window: where lyrics are looked for, in the order they're tried, each
+//! with a switch. Opened from Settings; every change is saved at once, and the song on screen
+//! is looked up again with it.
+//!
+//! The same card and drag-to-reorder as the "Order of homepage" window (`home_order`), with a
+//! switch at each row's right. Priority and whether a source is asked are separate questions:
+//! dragging moves a row whether it is on or off.
+
+use crate::app::App;
+use crate::lyrics::{self, Source};
+use crate::theme;
+use crate::widgets;
+
+const ROW: f32 = 64.0;
+const WIDTH: f32 = 480.0;
+/// The Done / Reset row: a chip's height.
+const BUTTONS: f32 = 32.0;
+const TITLE: &str = "Lyrics sources";
+const INTRO: &str = "All the sources that are on are asked at once. The first one in this list \
+ with timed lyrics is shown. Drag a source to move it. A source that's off \
+ is never contacted.";
+
+/// The list after dragging row `from` onto row `to`, as `home_order::moved` does it.
+fn moved(list: &[(Source, bool)], from: usize, to: usize) -> Vec<(Source, bool)> {
+ let mut out = list.to_vec();
+ if from < out.len() && to < out.len() && from != to {
+ let item = out.remove(from);
+ out.insert(to, item);
+ }
+ out
+}
+
+pub(crate) fn modal(app: &mut App, ui: &mut egui::Ui) {
+ if !app.lyrics_sources_open {
+ return;
+ }
+ let Some(screen) = ui.ctx().input(|i| i.raw.screen_rect) else {
+ return;
+ };
+ let p = app.palette;
+ let list = lyrics::normalise(&app.settings.lyrics_sources);
+ let width = WIDTH.min(screen.width() - 40.0);
+ // The title and the line under it, measured at the card's width, so the card fits its
+ // words; then padding, gaps and the buttons. The rows scroll when the window is too short
+ // for all of them.
+ let words = |text: &str, font: egui::FontId| {
+ ui.painter()
+ .layout(text.to_owned(), font, p.text, width - 32.0)
+ .size()
+ .y
+ };
+ let chrome = 16.0
+ + words(TITLE, theme::semibold(15.0))
+ + 6.0
+ + words(INTRO, theme::regular(12.0))
+ + 12.0
+ + 12.0
+ + BUTTONS
+ + 16.0;
+ let height = (chrome + ROW * list.len() as f32).min(screen.height() - 40.0);
+ let rows_height = (height - chrome).max(ROW);
+
+ let mut close = false;
+ let mut dismissed = false;
+ let mut reorder: Option<(usize, usize)> = None;
+ let mut flipped: Option = None;
+ let mut reset = false;
+ egui::Area::new(egui::Id::new("ytm-lyrics-sources-modal"))
+ .order(egui::Order::Middle)
+ .fixed_pos(screen.min)
+ .movable(false)
+ .interactable(true)
+ .show(ui.ctx(), |ui| {
+ let (full, backdrop) = ui.allocate_exact_size(screen.size(), egui::Sense::click());
+ ui.painter()
+ .rect_filled(full, 0.0, egui::Color32::from_black_alpha(150));
+ let card = egui::Rect::from_center_size(
+ full.center() - egui::vec2(0.0, 12.0),
+ egui::vec2(width, height),
+ );
+ if backdrop.clicked()
+ && backdrop
+ .interact_pointer_pos()
+ .is_some_and(|pos| !card.contains(pos))
+ {
+ dismissed = true;
+ }
+ let painter = ui.painter();
+ for (grow, alpha) in [(14.0, 24), (7.0, 40), (2.0, 60)] {
+ painter.rect_filled(
+ card.expand(grow),
+ egui::CornerRadius::same(theme::radii().popup + grow as u8),
+ egui::Color32::from_black_alpha(alpha),
+ );
+ }
+ painter.rect_filled(
+ card,
+ egui::CornerRadius::same(theme::radii().popup),
+ p.overlay,
+ );
+
+ let mut body = ui.new_child(
+ egui::UiBuilder::new()
+ .max_rect(card.shrink(16.0))
+ .layout(egui::Layout::top_down(egui::Align::LEFT)),
+ );
+ body.spacing_mut().item_spacing.y = 0.0;
+ body.label(
+ egui::RichText::new(TITLE)
+ .font(theme::semibold(15.0))
+ .color(p.text),
+ );
+ body.add_space(6.0);
+ body.label(
+ egui::RichText::new(INTRO)
+ .font(theme::regular(12.0))
+ .color(p.secondary),
+ );
+ body.add_space(12.0);
+
+ egui::ScrollArea::vertical()
+ .id_salt("lyrics-sources-rows")
+ .max_height(rows_height)
+ .auto_shrink([false, true])
+ .show(&mut body, |body| {
+ for (i, (source, on)) in list.iter().enumerate() {
+ let (rect, response) = body.allocate_exact_size(
+ egui::vec2(body.available_width(), ROW),
+ egui::Sense::click_and_drag(),
+ );
+ if response.drag_started() {
+ egui::DragAndDrop::set_payload(body.ctx(), i);
+ }
+ let dragging_this = egui::DragAndDrop::payload::(body.ctx())
+ .is_some_and(|from| *from == i);
+ if response.hovered() || dragging_this {
+ body.painter().rect_filled(
+ rect,
+ egui::CornerRadius::same(theme::radii().control),
+ if dragging_this {
+ p.surface_active
+ } else {
+ p.surface_hover
+ },
+ );
+ body.ctx().set_cursor_icon(if dragging_this {
+ egui::CursorIcon::Grabbing
+ } else {
+ egui::CursorIcon::Grab
+ });
+ }
+ paint_grip(body, rect, p.dim);
+ let text = if *on { p.text } else { p.dim };
+ let x = rect.left() + 38.0;
+ body.painter().text(
+ egui::pos2(x, rect.center().y - 15.0),
+ egui::Align2::LEFT_CENTER,
+ source.label(),
+ theme::medium(13.0),
+ text,
+ );
+ // The detail, two lines at most, left of the switch.
+ let detail = body.painter().layout(
+ source.detail().to_owned(),
+ theme::regular(11.0),
+ p.dim,
+ rect.width() - 38.0 - 60.0,
+ );
+ let detail_rect = egui::Rect::from_min_size(
+ egui::pos2(x, rect.center().y - 5.0),
+ egui::vec2(rect.width() - 38.0 - 60.0, 30.0),
+ );
+ body.painter().with_clip_rect(detail_rect).galley(
+ detail_rect.min,
+ detail,
+ p.dim,
+ );
+
+ let switch = egui::Rect::from_center_size(
+ egui::pos2(rect.right() - 28.0, rect.center().y),
+ egui::vec2(40.0, 22.0),
+ );
+ let mut value = *on;
+ // A child of its own, not `scope_builder`: in this top-down list a scope
+ // moves the cursor to below the switch, mid-row, and every row after
+ // it started 21pt inside the one before.
+ let mut cell = body.new_child(egui::UiBuilder::new().max_rect(switch));
+ widgets::toggle(
+ &mut cell,
+ &p,
+ egui::Id::new(("lyrics-source", i)),
+ &mut value,
+ );
+ if value != *on {
+ flipped = Some(i);
+ }
+
+ if egui::DragAndDrop::has_payload_of_type::(body.ctx())
+ && response.contains_pointer()
+ {
+ if body.ctx().input(|inp| inp.pointer.any_released()) {
+ if let Some(from) =
+ egui::DragAndDrop::take_payload::(body.ctx())
+ {
+ reorder = Some((*from, i));
+ }
+ } else {
+ let from = egui::DragAndDrop::payload::(body.ctx());
+ let up = from.is_some_and(|from| i < *from);
+ let y = if up { rect.top() } else { rect.bottom() };
+ body.painter().hline(
+ egui::Rangef::new(rect.left() + 8.0, rect.right() - 8.0),
+ y,
+ egui::Stroke::new(2.0, p.accent),
+ );
+ }
+ }
+ }
+ });
+
+ body.add_space(12.0);
+ body.allocate_ui(egui::vec2(body.available_width(), BUTTONS), |ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if widgets::chip(ui, &p, "Done", true).clicked() {
+ close = true;
+ }
+ if widgets::chip(ui, &p, "Reset to default", false).clicked() {
+ reset = true;
+ }
+ });
+ });
+ if body.input(|i| i.key_pressed(egui::Key::Escape)) {
+ close = true;
+ }
+ });
+
+ let ctx = ui.ctx().clone();
+ let mut next = list.clone();
+ if let Some((from, to)) = reorder {
+ next = moved(&next, from, to);
+ }
+ if let Some(i) = flipped {
+ next[i].1 = !next[i].1;
+ }
+ if reset {
+ next = lyrics::normalise(&[]);
+ }
+ if next != list {
+ app.update_settings(&ctx, |s| s.lyrics_sources = lyrics::to_choices(&next));
+ }
+ if close || dismissed {
+ app.lyrics_sources_open = false;
+ }
+}
+
+/// Six dots in two columns at the row's left: the usual "this can be dragged".
+fn paint_grip(ui: &egui::Ui, row: egui::Rect, colour: egui::Color32) {
+ let x = row.left() + 16.0;
+ let y = row.center().y;
+ for dx in [-3.0, 3.0] {
+ for dy in [-6.0, 0.0, 6.0] {
+ ui.painter()
+ .circle_filled(egui::pos2(x + dx, y + dy), 1.4, colour);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use Source::*;
+
+ #[test]
+ fn dragging_moves_a_source_and_keeps_its_switch() {
+ let list = vec![(BetterLyrics, true), (Lrclib, false), (YouTube, true)];
+ assert_eq!(
+ moved(&list, 1, 0),
+ vec![(Lrclib, false), (BetterLyrics, true), (YouTube, true)]
+ );
+ assert_eq!(moved(&list, 0, 9), list, "off the list changes nothing");
+ }
+}
diff --git a/crates/refryt/src/ui/mod.rs b/crates/refryt/src/ui/mod.rs
index 0042b77..18e8e16 100644
--- a/crates/refryt/src/ui/mod.rs
+++ b/crates/refryt/src/ui/mod.rs
@@ -6,6 +6,7 @@ pub mod artist;
pub mod artist_liked;
pub mod charts;
pub mod crash;
+pub mod entity_stats;
pub mod explore;
pub mod fullscreen;
pub mod help;
@@ -15,6 +16,7 @@ pub mod home_order;
pub mod library;
pub mod listening;
pub mod lyrics;
+pub mod lyrics_sources;
pub mod mood;
pub mod moods;
pub mod paste_cookies;
@@ -425,6 +427,8 @@ pub(crate) enum RowAction {
AddToQueue(Track),
GoToAlbum(String),
GoToArtist(String),
+ /// Open a song's listening stats page.
+ SongStats(String),
/// Copy a song's link.
CopyLink(String),
Rate {
@@ -2193,6 +2197,8 @@ const DESCRIPTION_AIR: f32 = 6.0;
// ~9.4pt of lead, so 19pt of centres reads as ~10pt of space between the ink: one block,
// not two paragraphs.
const LINE_GAP: f32 = 19.0;
+/// The artist page's audience line, and the stats page's rank: a point over the other credits.
+const SECOND_PLAIN_PT: f32 = 14.0;
/// One header for the album, playlist and artist pages: wash, art, type line, title, artist
/// line, meta, and — for the releases — the Play / Save / ••• row on its own baseline.
@@ -2395,8 +2401,8 @@ pub(crate) fn page_header(
ui.painter().text(
egui::pos2(tx, y),
egui::Align2::LEFT_CENTER,
- widgets::truncate_to(ui, plain, theme::regular(13.0), text_w),
- theme::regular(13.0),
+ widgets::truncate_to(ui, plain, theme::regular(SECOND_PLAIN_PT), text_w),
+ theme::regular(SECOND_PLAIN_PT),
palette.secondary,
);
last_line = y;
@@ -3004,13 +3010,14 @@ pub(crate) fn entry_row_spec<'a>(
/// shelves want this even for a shelf that is entirely songs, unlike Home/Explore's shelves,
/// which render every kind as cards.
pub(crate) fn entry_rows(app: &mut crate::app::App, ui: &mut egui::Ui, items: &[Entry]) {
- entry_rows_with(app, ui, items, &[]);
+ entry_rows_with(app, ui, items, &[], false);
}
-/// [`entry_rows`] with each row's place in the list where its number would go.
-pub(crate) fn ranked_entry_rows(app: &mut crate::app::App, ui: &mut egui::Ui, items: &[Entry]) {
+/// [`entry_rows`] for Stats' lists, each row's place where its number would go. A row opens
+/// that song's or artist's stats page, where Play and their own page are a click away.
+pub(crate) fn ranked_stats_rows(app: &mut crate::app::App, ui: &mut egui::Ui, items: &[Entry]) {
let ranks: Vec = (1..=items.len()).map(|n| n.to_string()).collect();
- entry_rows_with(app, ui, items, &ranks);
+ entry_rows_with(app, ui, items, &ranks, true);
}
fn entry_rows_with(
@@ -3018,6 +3025,7 @@ fn entry_rows_with(
ui: &mut egui::Ui,
items: &[Entry],
ranks: &[String],
+ to_stats: bool,
) {
let signed_in = app.signed_in();
let clicked = {
@@ -3057,6 +3065,13 @@ fn entry_rows_with(
app.row_action(action);
}
match clicked.click {
+ Some(ListClick::Row(i)) if to_stats => match &items[i] {
+ Entry::Song(t) | Entry::Video(t) => {
+ app.navigate(Route::StatsSong(t.video_id.clone()));
+ }
+ Entry::Artist(a) => app.navigate(Route::StatsArtist(a.name.to_lowercase())),
+ _ => {}
+ },
Some(ListClick::Row(i)) => match &items[i] {
Entry::Song(_) | Entry::Video(_) => {
if let Some(index) = playable_index(items, i) {
diff --git a/crates/refryt/src/ui/settings.rs b/crates/refryt/src/ui/settings.rs
index a703527..beacbb4 100644
--- a/crates/refryt/src/ui/settings.rs
+++ b/crates/refryt/src/ui/settings.rs
@@ -293,11 +293,13 @@ fn appearance(app: &mut App, ui: &mut egui::Ui) {
let dark = app.palette.dark;
let mut dark_choice = app.settings.dark_theme.clone();
let mut light_choice = app.settings.light_theme.clone();
- let offered: Vec<&crate::theme::custom::CustomTheme> = app
- .custom_themes
- .themes
+ // The desktop's GTK and Qt themes first, in both modes: following the desktop means its
+ // colours whatever the mode. Then the files of this mode.
+ let system = crate::theme::system::GTK_AND_QT
.iter()
- .filter(|t| t.dark == dark)
+ .filter_map(|name| app.custom_themes.system_theme(name, dark));
+ let offered: Vec<&crate::theme::custom::CustomTheme> = system
+ .chain(app.custom_themes.themes.iter().filter(|t| t.dark == dark))
.collect();
let options: Vec<(egui::Color32, &str)> = offered
.iter()
@@ -333,7 +335,11 @@ fn appearance(app: &mut App, ui: &mut egui::Ui) {
&options,
) {
let name = offered[i].name.clone();
- if dark {
+ if crate::theme::system::is_system(&name) {
+ // The desktop's theme stands for both modes.
+ dark_choice = name.clone();
+ light_choice = name;
+ } else if dark {
dark_choice = name;
} else {
light_choice = name;
@@ -955,7 +961,21 @@ fn system(app: &mut App, ui: &mut egui::Ui) {
// Discord Rich Presence. Nothing to configure: the app connects as its own Discord
// application (the id is fixed in `crate::discord`), so the toggle is the whole setting.
let mut discord = app.settings.discord_rich_presence;
- let mut lrclib = app.settings.lrclib_lyrics;
+ let mut romanisation = app.settings.lyrics_romanisation;
+ // The sources asked, in order, as a line under the row that opens the list.
+ let lyrics_summary = {
+ let asked = crate::lyrics::asked(&app.settings.lyrics_sources);
+ if asked.is_empty() {
+ "All off: no lyrics are looked up.".to_owned()
+ } else {
+ asked
+ .iter()
+ .map(|s| s.label())
+ .collect::>()
+ .join(", then ")
+ }
+ };
+ let mut open_lyrics_sources = false;
// The switch is casting on the network the computer is on: on, it is allowed here; off,
// it is not, and any other network allowed stays so.
let on_here = app.settings.cast_receiver && app.cast_allowed_here();
@@ -1002,14 +1022,19 @@ fn system(app: &mut App, ui: &mut egui::Ui) {
"Shows what you're playing on Discord.",
&mut discord,
);
+ g.row(ui, "Lyrics sources", &lyrics_summary, |ui| {
+ open_lyrics_sources = widgets::outline_button(ui, &p, "Change…").clicked();
+ });
toggle_row(
g,
ui,
&p,
- "setting-lrclib",
- "Synced lyrics from LRCLIB",
- "Asks lrclib.net for lyrics with timing. Off, lyrics come from YouTube without it.",
- &mut lrclib,
+ "setting-lyrics-romanisation",
+ "Prefer romanised lyrics",
+ "For Japanese, Korean and Chinese songs: lyrics in Latin letters, with the original \
+ under each line, from a source that has them (Apple Music's lyrics, or a lyrics \
+ file with romaji in it).",
+ &mut romanisation,
);
});
@@ -1021,11 +1046,14 @@ fn system(app: &mut App, ui: &mut egui::Ui) {
}
s.hide_tray_on_close = hide_tray;
s.discord_rich_presence = discord;
- s.lrclib_lyrics = lrclib;
+ s.lyrics_romanisation = romanisation;
});
if cast != on_here {
app.set_cast_here(&ctx, cast);
}
+ if open_lyrics_sources {
+ app.lyrics_sources_open = true;
+ }
if let Some(id) = forget {
app.forget_cast_network(&ctx, &id);
}
diff --git a/crates/refryt/src/widgets.rs b/crates/refryt/src/widgets.rs
index 3578db2..c4886ea 100644
--- a/crates/refryt/src/widgets.rs
+++ b/crates/refryt/src/widgets.rs
@@ -2788,38 +2788,32 @@ pub fn track_row<'a>(ui: &mut Ui, palette: &Palette, row: TrackRow<'a>) -> RowCl
);
}
} else if !narrow && let Some(n) = number {
+ // The numbers are right-aligned to this edge. What takes a number's place is
+ // centred on a one-digit number, the usual case: centred in the whole column it sat
+ // right of every number, and ending at this edge put it left of most of them.
+ let number_right = rect.left() + left_inset + num_w - theme::ROW_NUMBER_GAP;
+ let glyph = 14.0;
+ let digit = text_width(ui, "0", &theme::regular(12.0));
+ let in_place = Rect::from_center_size(
+ egui::pos2(number_right - digit / 2.0, rect.center().y),
+ vec2(glyph, glyph),
+ );
if loading && hide_art {
- paint_spinner(ui, number_rect.center(), 7.0, 2.0, palette.accent);
+ paint_spinner(ui, in_place.center(), 7.0, 2.0, palette.accent);
} else if number_play && over {
// The cover's own hover play button went with the cover, so the affordance
// moves into the number's slot — the pointer turns the number into a play
// (or pause, on the row that is already going) glyph. Painted in the accent
// the cover's button used, so the two read as the same control.
- let glyph = 14.0;
let icon = if playing {
Icon::PauseFilled
} else {
Icon::PlayFilled
};
- // The play triangle's visual centre sits left of its bounding box; Pause is
- // symmetric and needs no nudge.
- let nudge = if playing { 0.0 } else { glyph * 0.06 };
- icon.image(palette.accent, glyph).paint_at(
- ui,
- Rect::from_center_size(
- egui::pos2(
- rect.left() + left_inset + num_w / 2.0 + nudge,
- rect.center().y,
- ),
- vec2(glyph, glyph),
- ),
- );
+ icon.image(palette.accent, glyph).paint_at(ui, in_place);
} else {
ui.painter().text(
- egui::pos2(
- rect.left() + left_inset + num_w - theme::ROW_NUMBER_GAP,
- rect.center().y,
- ),
+ egui::pos2(number_right, rect.center().y),
egui::Align2::RIGHT_CENTER,
n.to_string(),
theme::regular(12.0),
@@ -3220,10 +3214,8 @@ pub(crate) fn row_menu(
mui.close();
}
- // Block three: where it came from, and sending it on.
- if t.album_id.is_some() || t.primary_artist_id().is_some() || t.local_path.is_none() {
- menu_divider(mui, palette);
- }
+ // Block three: where it came from, your stats, and sending it on.
+ menu_divider(mui, palette);
if let Some(id) = &t.album_id
&& menu_item(mui, palette, Icon::Disc3, "Go to album", None).clicked()
{
@@ -3236,6 +3228,10 @@ pub(crate) fn row_menu(
choice = Some(RowAction::GoToArtist(id.to_owned()));
mui.close();
}
+ if menu_item(mui, palette, Icon::ChartColumn, "Your stats", None).clicked() {
+ choice = Some(RowAction::SongStats(t.video_id.clone()));
+ mui.close();
+ }
// There is no real YouTube URL for a local track to copy.
if t.local_path.is_none()
&& menu_item(mui, palette, Icon::Link, "Copy link", None).clicked()
@@ -4900,6 +4896,8 @@ pub fn tab_strip(
/// The height of a [`Group`] row that holds one line of control.
const ROW_H: f32 = 58.0;
+/// The least space under a settings row's words, once a long detail has grown the row.
+const ROW_MIN_BOTTOM: f32 = 10.0;
/// Settings rows inside one card: each a title and a line under it on the left, its control on
/// the right, with a hairline between rows. Build one with [`setting_group`].
@@ -4953,9 +4951,17 @@ impl Group<'_> {
ui.add_space(8.0);
ui.vertical(|ui| {
// Centred by measure: a `vertical` starts at the top of the row's rect.
+ let top = ui.max_rect().top();
let lines = if detail.is_empty() { 1.0 } else { 2.0 };
ui.add_space(((ROW_H - lines * 15.5) / 2.0 - 1.0).max(8.0));
self.text(ui, title, detail);
+ // A detail that wraps to more lines grows the row past `ROW_H`, and its
+ // last line sat on the row's bottom edge: keep a margin under it. A row
+ // whose words fit already has more than that, and is left as it was.
+ let room = ROW_H - (ui.min_rect().bottom() - top);
+ if room < ROW_MIN_BOTTOM {
+ ui.add_space(ROW_MIN_BOTTOM - room.max(0.0));
+ }
});
},
);
@@ -6684,10 +6690,14 @@ mod tests {
for entry in layer.all_entries() {
if let egui::Shape::Text(text) = &entry.shape {
let rect = egui::Rect::from_min_size(text.pos, text.galley.size());
- if rect.right()
- <= hit.response.rect.left()
- + crate::theme::ROW_LEFT_INSET
- + crate::theme::ROW_NUMBER_W
+ // The number itself, not any text there: with no image
+ // loader in a test the play glyph paints as egui's "⚠"
+ // in the same column.
+ if text.galley.text() == "7"
+ && rect.right()
+ <= hit.response.rect.left()
+ + crate::theme::ROW_LEFT_INSET
+ + crate::theme::ROW_NUMBER_W
{
found += 1;
}
diff --git a/crates/refryt/themes/Breeze Dark.css b/crates/refryt/themes/Breeze Dark.css
new file mode 100644
index 0000000..9f572b1
--- /dev/null
+++ b/crates/refryt/themes/Breeze Dark.css
@@ -0,0 +1,26 @@
+/* Breeze Dark
+ KDE Plasma's Breeze Dark colours (BreezeDark.colors): charcoal windows over darker views,
+ with Breeze blue for selection and focus.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: dark;
+
+ --base: #202326; /* the cards */
+ --text: #fcfcfc; /* body text */
+ --accent: #3daee9; /* play buttons, selection, links */
+ --on-accent: #141618; /* text and icons on the accent */
+
+ --gutter: #141618; /* the gap behind the cards */
+ --popup: #292c30; /* menus and popups */
+ --surface: #292c30; /* chips, inputs */
+ --surface-hover: #31363b;
+ --surface-active: #3b4045;
+ --outline: #3a3e43; /* hairlines */
+ --subtext: #a1a9b1; /* second-rank text */
+ --muted: #7a828a; /* third-rank text */
+ --danger: #da4453;
+ --warning: #f67400;
+}
diff --git a/crates/refryt/themes/Breeze Light.css b/crates/refryt/themes/Breeze Light.css
new file mode 100644
index 0000000..6189197
--- /dev/null
+++ b/crates/refryt/themes/Breeze Light.css
@@ -0,0 +1,26 @@
+/* Breeze Light
+ KDE Plasma's Breeze Light colours (BreezeLight.colors): white views on light grey
+ windows, with Breeze blue for selection and focus.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: light;
+
+ --base: #ffffff; /* the cards */
+ --text: #232629; /* body text */
+ --accent: #3daee9; /* play buttons, selection, links */
+ --on-accent: #232629; /* text and icons on the accent */
+
+ --gutter: #eff0f1; /* the gap behind the cards */
+ --popup: #f7f7f7; /* menus and popups */
+ --surface: #eff0f1; /* chips, inputs */
+ --surface-hover: #e3e5e7;
+ --surface-active: #dee0e2;
+ --outline: #d5d8dc; /* hairlines */
+ --subtext: #707d8a; /* second-rank text */
+ --muted: #8c96a0; /* third-rank text */
+ --danger: #da4453;
+ --warning: #f67400;
+}
diff --git a/crates/refryt/themes/Windows Dark.css b/crates/refryt/themes/Windows Dark.css
new file mode 100644
index 0000000..eb2eeab
--- /dev/null
+++ b/crates/refryt/themes/Windows Dark.css
@@ -0,0 +1,26 @@
+/* Windows Dark
+ Windows 11's Fluent dark colours: a charcoal canvas with slightly raised surfaces, and
+ the Windows 11 sky-blue accent.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: dark;
+
+ --base: #202020; /* the cards */
+ --text: #ffffff; /* body text */
+ --accent: #60cdff; /* play buttons, selection, links */
+ --on-accent: #000000; /* text and icons on the accent */
+
+ --gutter: #1c1c1c; /* the gap behind the cards */
+ --popup: #2c2c2c; /* menus and popups */
+ --surface: #2d2d2d; /* chips, inputs */
+ --surface-hover: #383838;
+ --surface-active: #424242;
+ --outline: #3a3a3a; /* hairlines */
+ --subtext: #d0d0d0; /* second-rank text */
+ --muted: #9a9a9a; /* third-rank text */
+ --danger: #ff99a4;
+ --warning: #fce100;
+}
diff --git a/crates/refryt/themes/Windows Light.css b/crates/refryt/themes/Windows Light.css
new file mode 100644
index 0000000..5beb411
--- /dev/null
+++ b/crates/refryt/themes/Windows Light.css
@@ -0,0 +1,26 @@
+/* Windows Light
+ Windows 11's Fluent light colours: a soft grey canvas with crisp white cards, and the
+ Windows 11 system blue.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: light;
+
+ --base: #f3f3f3; /* the cards */
+ --text: #1b1b1b; /* body text */
+ --accent: #0067c0; /* play buttons, selection, links */
+ --on-accent: #ffffff; /* text and icons on the accent */
+
+ --gutter: #e8e8e8; /* the gap behind the cards */
+ --popup: #ffffff; /* menus and popups */
+ --surface: #ffffff; /* chips, inputs */
+ --surface-hover: #eaeaea;
+ --surface-active: #dcdcdc;
+ --outline: #d6d6d6; /* hairlines */
+ --subtext: #5c5c5c; /* second-rank text */
+ --muted: #727272; /* third-rank text */
+ --danger: #c42b1c;
+ --warning: #9d5d00;
+}
diff --git a/crates/refryt/themes/macOS Dark.css b/crates/refryt/themes/macOS Dark.css
new file mode 100644
index 0000000..7aea112
--- /dev/null
+++ b/crates/refryt/themes/macOS Dark.css
@@ -0,0 +1,26 @@
+/* macOS Dark
+ The Mac's own system colours, as Safari and Finder use them: near-black pages in
+ charcoal, with system blue for buttons and links.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: dark;
+
+ --base: #1e1e1e; /* the cards */
+ --text: #f5f5f7; /* body text */
+ --accent: #0a84ff; /* play buttons, selection, links */
+ --on-accent: #ffffff; /* text and icons on the accent */
+
+ --gutter: #141414; /* the gap behind the cards */
+ --popup: #282828; /* menus and popups */
+ --surface: #3a3a3c; /* chips, inputs */
+ --surface-hover: #444446;
+ --surface-active: #545456;
+ --outline: #3d3d3f; /* hairlines */
+ --subtext: #aeaeb2; /* second-rank text */
+ --muted: #8e8e93; /* third-rank text */
+ --danger: #ff453a;
+ --warning: #ff9f0a;
+}
diff --git a/crates/refryt/themes/macOS Light.css b/crates/refryt/themes/macOS Light.css
new file mode 100644
index 0000000..b1ffde0
--- /dev/null
+++ b/crates/refryt/themes/macOS Light.css
@@ -0,0 +1,26 @@
+/* macOS Light
+ The Mac's own system colours, as Safari and Finder use them: white pages in light
+ grey, with system blue for buttons and links.
+
+ A refryt theme. Edit and save to repaint the app; see docs/THEMES.md for every
+ variable. What a file leaves out is derived from --base, --text and --accent. */
+
+:root {
+ color-scheme: light;
+
+ --base: #ffffff; /* the cards */
+ --text: #1d1d1f; /* body text */
+ --accent: #007aff; /* play buttons, selection, links */
+ --on-accent: #ffffff; /* text and icons on the accent */
+
+ --gutter: #ececec; /* the gap behind the cards */
+ --popup: #f5f5f7; /* menus and popups */
+ --surface: #ebebef; /* chips, inputs */
+ --surface-hover: #e0e0e5;
+ --surface-active: #d1d1d6;
+ --outline: #d1d1d6; /* hairlines */
+ --subtext: #6e6e73; /* second-rank text */
+ --muted: #8e8e93; /* third-rank text */
+ --danger: #e0352b;
+ --warning: #b25000;
+}
diff --git a/docs/THEMES.md b/docs/THEMES.md
index ea2e7f6..d289aed 100644
--- a/docs/THEMES.md
+++ b/docs/THEMES.md
@@ -1,9 +1,10 @@
# Themes
Every colour theme in refryt is a `.css` file in the themes folder, including the ones the app
-ships with. The first time refryt starts, it writes its 23 themes there (Classic, Catppuccin,
-Nord, Gruvbox, Tokyo Night, Dracula, Rosé Pine, Everforest and Solarized, each light and dark
-flavour as its own file, and Spotify). From then on the folder is all there is:
+ships with. The first time refryt starts, it writes its 29 themes there (Classic, Catppuccin,
+Nord, Gruvbox, Tokyo Night, Dracula, Rosé Pine, Everforest, Solarized, macOS, Windows and Breeze, each
+light and dark flavour as its own file, and Spotify). A fresh install starts on macOS Dark on a
+Mac, Windows Dark on Windows, and Classic Dark elsewhere. From then on the folder is all there is:
- **Delete a file** and that theme is gone. Nothing puts it back.
- **A theme added in a newer release** is written into the folder once. A hidden `.offered` file
@@ -25,6 +26,14 @@ dark themes while the app is in dark mode and the light ones in light mode, and
pick for each; **Mode** (System / Dark / Light) chooses between them. If the folder has no
theme of the mode on screen, a built-in Classic paints until you add one.
+## Following the desktop
+
+On Linux the Theme list also starts with **GTK** and **Qt**, as Chrome's appearance settings
+do. They aren't files: refryt takes their colours from the desktop. Qt is the KDE colour
+scheme in `~/.config/kdeglobals`, so it's offered on a KDE desktop. GTK is whatever GTK 3
+theme is set, asked of GTK itself. Picking either sets it for dark and light mode alike.
+Change the desktop's theme and refryt repaints when you come back to its window.
+
## The file
```css