From 4f502967e661e7411dd34a780f64d2b10bcff9cd Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 17:54:22 +0200 Subject: [PATCH 01/12] feat: lyrics from eight sources, picked automatically and switchable Every source that's on is asked at once. The first one in your order with timed lyrics is shown, and plain text only when none had timing. A source that's off is never contacted. Sources: BetterLyrics, lrc.red, YouTube Music synced, LRCLIB, KuGou, Unison, YouTube Music plain and Genius. Settings > Integrations has a "Lyrics sources" window to reorder them and switch each on or off. The lyrics header has a small picker listing the sources that found lyrics for the song, and a pick holds for that song this session. The old LRCLIB switch carries over: off stays off. LRC fractions are now read by their digit count, so [00:01.05] is 1.05 s, not 1.5 s. The approach follows BitChord's (github.com/kushagrasinghx/BitChord). --- Cargo.lock | 2 + PRIVACY.md | 16 +- README.md | 5 +- crates/refryt/Cargo.toml | 5 + crates/refryt/src/app.rs | 137 +++++- crates/refryt/src/backend.rs | 203 ++------- crates/refryt/src/lib.rs | 1 + crates/refryt/src/lyrics/better_lyrics.rs | 150 +++++++ crates/refryt/src/lyrics/genius.rs | 277 ++++++++++++ crates/refryt/src/lyrics/kugou.rs | 249 +++++++++++ crates/refryt/src/lyrics/lrc_red.rs | 152 +++++++ crates/refryt/src/lyrics/lrclib.rs | 147 +++++++ crates/refryt/src/lyrics/mod.rs | 514 ++++++++++++++++++++++ crates/refryt/src/lyrics/unison.rs | 121 +++++ crates/refryt/src/lyrics/youtube.rs | 181 ++++++++ crates/refryt/src/settings.rs | 61 ++- crates/refryt/src/ui/lyrics.rs | 84 +++- crates/refryt/src/ui/lyrics_sources.rs | 259 +++++++++++ crates/refryt/src/ui/mod.rs | 1 + crates/refryt/src/ui/settings.rs | 31 +- 20 files changed, 2387 insertions(+), 209 deletions(-) create mode 100644 crates/refryt/src/lyrics/better_lyrics.rs create mode 100644 crates/refryt/src/lyrics/genius.rs create mode 100644 crates/refryt/src/lyrics/kugou.rs create mode 100644 crates/refryt/src/lyrics/lrc_red.rs create mode 100644 crates/refryt/src/lyrics/lrclib.rs create mode 100644 crates/refryt/src/lyrics/mod.rs create mode 100644 crates/refryt/src/lyrics/unison.rs create mode 100644 crates/refryt/src/lyrics/youtube.rs create mode 100644 crates/refryt/src/ui/lyrics_sources.rs diff --git a/Cargo.lock b/Cargo.lock index 6d1d856..522cb7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4882,6 +4882,7 @@ name = "refryt" version = "0.3.2" dependencies = [ "anyhow", + "base64 0.22.1", "bytes", "chrono", "directories", @@ -4909,6 +4910,7 @@ dependencies = [ "refryt-resolve", "reqwest", "rfd", + "roxmltree", "serde", "serde_json", "sha2", diff --git a/PRIVACY.md b/PRIVACY.md index 6cb51b0..6b16ebd 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -22,9 +22,19 @@ session, and plays are added to your YouTube history unless "Save listening hist in Settings. The bundled yt-dlp contacts YouTube the same way when it is used for playback. Google's privacy policy applies: . -**LRCLIB** (lrclib.net), for synced lyrics. While the lyrics panel is open, each song's title, -artist, album and length are sent to look its lyrics up. Turn it off with "Synced lyrics from -LRCLIB" in Settings, Integrations; lyrics then come from YouTube alone. +**Lyrics sources**, while lyrics are shown. Each source that's on is asked for each song: +- **BetterLyrics** (lyrics-api.boidu.dev) gets the song's title, artist, album and length. +- **lrc.red** gets the title, artist and length. +- **LRCLIB** (lrclib.net) gets the title, artist, album and length. +- **KuGou** (mobileservice.kugou.com, lyrics.kugou.com) gets the title, artist, album and + length. +- **Unison** (unison.boidu.dev) gets the title, artist, album and length. +- **Genius** (genius.com) gets the title and artist. +- **YouTube Music**, for its synced and plain lyrics, gets the video id. These requests are sent + without your Google session. + +Turn any of them off, or change the order they're tried in, under "Lyrics sources" in Settings, +Integrations. A source that's off is never contacted. **GitHub** (api.github.com, github.com), to check for a new release when refryt starts and to download one when you choose to update. The check sends no information about you or what you diff --git a/README.md b/README.md index 672120d..12947ba 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ Sign in from the app's own window, or use Import from browser on Home or in Sett Settings, themes, the session and the log live in `~/.config/refryt` on Linux, `~/Library/Application Support/refryt` on macOS and `~/.var/app/io.github.gridoe.refryt/config/refryt` in the Flatpak. The session is stored with owner-only permissions. -There is no telemetry. refryt connects to YouTube, [LRCLIB](https://lrclib.net) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. LRCLIB and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. +There is no telemetry. refryt connects to YouTube and a few lyrics sites (BetterLyrics, lrc.red, LRCLIB, KuGou, Unison and Genius) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. Each lyrics source and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. ## Status @@ -229,7 +229,8 @@ Built with Rust and [egui](https://github.com/emilk/egui), [mpv](https://mpv.io/ runs out. - **Spotify's desktop app**: the shortcuts, select-then-play clicks, and the shape of the album, playlist and artist pages. -- **[LRCLIB](https://lrclib.net)**: the synced lyrics. +- **[BetterLyrics](https://github.com/better-lyrics/better-lyrics)**, **[lrc.red](https://lrc.red)**, **[LRCLIB](https://lrclib.net)**, **[KuGou](https://www.kugou.com)**, **Unison** and **[Genius](https://genius.com)**: lyrics. +- **[BitChord](https://github.com/kushagrasinghx/BitChord)**: lyrics from several sources, tried in an order you set. - **Theme palettes**: [Catppuccin](https://github.com/catppuccin/palette), [Nord](https://www.nordtheme.com/docs/colors-and-palettes), [Gruvbox](https://github.com/morhetz/gruvbox), diff --git a/crates/refryt/Cargo.toml b/crates/refryt/Cargo.toml index 86ff1d7..3a5d2aa 100644 --- a/crates/refryt/Cargo.toml +++ b/crates/refryt/Cargo.toml @@ -21,6 +21,11 @@ skrifa = "0.44" # No `charset`: YouTube's InnerTube responses are UTF-8 JSON and the code never calls # `text_with_charset`, so `encoding_rs` (1.6 MB) + `mime` would add size for no use. reqwest = { version = "0.13", default-features = false, features = ["rustls", "gzip", "cookies", "http2"] } +# Reading BetterLyrics' TTML (`lyrics::better_lyrics`). Already compiled for another dependency, +# at this version, so it adds an edge rather than a crate. +roxmltree = "0.20" +# KuGou sends its LRC as base64. Already in the build through reqwest's stack. +base64 = "0.22" serde.workspace = true serde_json.workspace = true tokio.workspace = true diff --git a/crates/refryt/src/app.rs b/crates/refryt/src/app.rs index 066edc9..86b63a0 100644 --- a/crates/refryt/src/app.rs +++ b/crates/refryt/src/app.rs @@ -1773,6 +1773,17 @@ pub struct App { /// Which video the current lyrics (or in-flight request) belong to, so a reply for a track /// already left behind is dropped. lyrics_for: Option, + /// What each source asked has said about [`Self::lyrics_for`] so far, and the order they + /// were asked in: the automatic pick reads them in that order. + pub(crate) lyrics_answers: + std::collections::HashMap, + pub(crate) lyrics_order: Vec, + /// The source whose lyrics are in [`Self::lyrics`]. + pub(crate) lyrics_shown: Option, + /// Songs whose source the listener picked in the lyrics panel, this session. + lyrics_choice: std::collections::HashMap, + /// The "Lyrics sources" window, opened from Settings. + pub(crate) lyrics_sources_open: bool, /// The playlist rename editor, when open. pub(crate) playlist_edit: Option, /// A playlist awaiting delete confirmation: its id and title. @@ -2309,6 +2320,11 @@ impl App { lyrics_loading: false, lyrics_error: None, lyrics_for: None, + lyrics_answers: std::collections::HashMap::new(), + lyrics_order: Vec::new(), + lyrics_shown: None, + lyrics_choice: std::collections::HashMap::new(), + lyrics_sources_open: false, playlist_edit: None, playlist_delete: None, playlist_duplicate: None, @@ -2663,6 +2679,14 @@ impl App { let shelves: &mut Vec = Arc::make_mut(home); crate::model::order_home(shelves, &order); } + // A changed source list asks again for the song on screen, so turning a source on (or + // off) shows at once rather than from the next song. + if self.settings.lyrics_sources != before.lyrics_sources + && self.lyrics_wanted() + && let Some(track) = self.now.track.clone() + { + self.fetch_lyrics(track); + } if self.settings.cache_songs != before.cache_songs { self.backend .set_song_cache(self.settings.cache_songs, self.settings.cache_size.bytes()); @@ -6405,22 +6429,25 @@ impl App { } } } - Event::LyricsLoaded { video_id, lyrics } - if self.lyrics_for.as_deref() == Some(video_id.as_str()) => - { - self.lyrics_loading = false; - self.lyrics_error = None; - self.lyrics = Some(lyrics); - } - Event::LyricsFailed { video_id, error } - if self.lyrics_for.as_deref() == Some(video_id.as_str()) => - { - tracing::debug!(%video_id, %error, "no lyrics"); - self.lyrics_loading = false; - self.lyrics = None; - self.lyrics_error = Some(error); + Event::LyricsSource { + video_id, + source, + found, + } if self.lyrics_for.as_deref() == Some(video_id.as_str()) => { + let answer = match found { + Ok(Some(lyrics)) if !lyrics.lines.is_empty() => { + crate::lyrics::Answer::Found(lyrics) + } + Ok(_) => crate::lyrics::Answer::Missing, + Err(error) => { + tracing::debug!(%video_id, source = source.label(), %error, "lyrics source failed"); + crate::lyrics::Answer::Missing + } + }; + self.lyrics_answers.insert(source, answer); + self.show_lyrics(); } - Event::LyricsLoaded { .. } | Event::LyricsFailed { .. } => {} + Event::LyricsSource { .. } => {} Event::MixMore { token, queue } => { self.radio_loading = false; // A newer river may have opened while this was in flight — appending @@ -7193,16 +7220,85 @@ impl App { } } - /// Start a lyrics request for `track`, replacing whatever is shown. The `lyrics_for` guard - /// drops the reply if the track changes before it lands. + /// Start a lyrics request for `track`, replacing whatever is shown: every ticked source is + /// asked at once. The `lyrics_for` guard drops answers for a track already left behind. fn fetch_lyrics(&mut self, track: Track) { self.lyrics_for = Some(track.video_id.clone()); self.lyrics = None; + self.lyrics_shown = None; self.lyrics_error = None; - self.lyrics_loading = true; self.lyrics_scroll_reset = true; - self.backend - .fetch_lyrics(track, self.settings.lrclib_lyrics); + self.lyrics_order = crate::lyrics::asked(&self.settings.lyrics_sources); + self.lyrics_answers = self + .lyrics_order + .iter() + .map(|s| (*s, crate::lyrics::Answer::Pending)) + .collect(); + if self.lyrics_order.is_empty() { + self.lyrics_loading = false; + self.lyrics_error = + Some("Every lyrics source is off. Turn one on in Settings.".to_owned()); + return; + } + self.lyrics_loading = true; + self.backend.fetch_lyrics(track, self.lyrics_order.clone()); + } + + /// Show what the answers so far call for: the source picked for this song in the panel, if + /// it found lyrics, else the automatic pick (see [`crate::lyrics::pick`]). + fn show_lyrics(&mut self) { + let chosen = self + .lyrics_for + .as_ref() + .and_then(|id| self.lyrics_choice.get(id)) + .copied() + .filter(|s| { + matches!( + self.lyrics_answers.get(s), + Some(crate::lyrics::Answer::Found(_)) + ) + }); + let pick = match chosen { + Some(source) => crate::lyrics::Pick::Use(source), + None => crate::lyrics::pick(&self.lyrics_order, &self.lyrics_answers), + }; + match pick { + crate::lyrics::Pick::Wait => {} + crate::lyrics::Pick::Use(source) => { + if self.lyrics_shown != Some(source) + && let Some(crate::lyrics::Answer::Found(lyrics)) = + self.lyrics_answers.get(&source) + { + tracing::debug!( + video_id = self.lyrics_for.as_deref().unwrap_or_default(), + source = source.label(), + synced = lyrics.synced, + lines = lyrics.lines.len(), + "lyrics shown" + ); + self.lyrics = Some(lyrics.clone()); + self.lyrics_shown = Some(source); + self.lyrics_scroll_reset = true; + } + self.lyrics_loading = false; + self.lyrics_error = None; + } + crate::lyrics::Pick::Nothing => { + self.lyrics = None; + self.lyrics_shown = None; + self.lyrics_loading = false; + self.lyrics_error = Some("No lyrics found".to_owned()); + } + } + } + + /// The listener picked `source` in the lyrics panel: show its lyrics for this song, and + /// keep to it if the song comes back this session. + pub(crate) fn choose_lyrics_source(&mut self, source: crate::lyrics::Source) { + if let Some(id) = self.lyrics_for.clone() { + self.lyrics_choice.insert(id, source); + self.show_lyrics(); + } } /// Put `track` straight after the playing one, in the list and in a shuffle's order. @@ -9167,6 +9263,7 @@ impl eframe::App for App { ui::playlist::modals(self, ui); ui::help::modal(self, ui); ui::home_order::modal(self, ui); + ui::lyrics_sources::modal(self, ui); ui::paste_cookies::modal(self, ui); ui::crash::modal(self, ui); ui::update::modal(self, ui); diff --git a/crates/refryt/src/backend.rs b/crates/refryt/src/backend.rs index 6ba474f..e07c7a1 100644 --- a/crates/refryt/src/backend.rs +++ b/crates/refryt/src/backend.rs @@ -373,15 +373,13 @@ pub enum Event { playlist_id: String, error: String, }, - /// Lyrics for the now-playing track: synced from LRCLIB when it had them, else plain text - /// from InnerTube. - LyricsLoaded { + /// One lyrics source's answer for a song: `Ok(Some)` its lyrics, `Ok(None)` none there, + /// `Err` the source could not be reached or read. One arrives per source asked; the app + /// picks among them (see [`crate::lyrics::pick`]). + LyricsSource { video_id: String, - lyrics: crate::model::Lyrics, - }, - LyricsFailed { - video_id: String, - error: String, + source: crate::lyrics::Source, + found: Result, String>, }, /// A rating write was refused. The app updates optimistically, so this carries what to /// revert: the state is never left claiming something YouTube refused. @@ -581,14 +579,14 @@ impl Event { | Event::HomeShelfFailed { .. } | Event::MoodPlaylistsLoaded { .. } | Event::MoodPlaylistsFailed { .. } - | Event::LyricsLoaded { .. } - | Event::LyricsFailed { .. } + | Event::LyricsSource { .. } ) } /// The error a failure carries, for the one question asked of all of them at once: does /// this read as having no connection? See [`crate::api::looks_offline`]. A local folder scan - /// failing is left out — the disk has nothing to say about the network. + /// failing is left out — the disk has nothing to say about the network — and so is a lyrics + /// source failing: one lyrics host being down says nothing about the connection. pub fn error(&self) -> Option<&str> { match self { Event::SearchFailed { error, .. } @@ -618,7 +616,6 @@ impl Event { | Event::MixMoreFailed { error, .. } | Event::MixSeedFailed { error, .. } | Event::RadioFilterFailed { error, .. } - | Event::LyricsFailed { error, .. } | Event::RatingFailed { error, .. } | Event::LibraryToggleFailed { error, .. } | Event::PageLibraryFailed { error, .. } @@ -655,51 +652,6 @@ async fn fetch_bytes(http: &reqwest::Client, url: &str) -> anyhow::Result 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) - .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(crate::model::Lyrics { - lines, - synced: true, - source: "LRCLIB".to_owned(), - }); - } - } - let plain = body - .get("plainLyrics") - .and_then(serde_json::Value::as_str)?; - Some(crate::model::Lyrics { - lines: plain_lines(plain), - synced: false, - source: "LRCLIB".to_owned(), - }) -} - /// A single/album track's `wide: true` id points at a music-video upload, with no separate /// audio-only id anywhere in the album metadata itself — the typed and raw album parsers both /// read exactly one id per row (see `map_album`/`track_states`), so the only way to find the @@ -726,60 +678,6 @@ async fn audio_alternative(api: &Api, track: &Track) -> Option { }) } -/// Split plain text into lines, trimming the ends. -fn plain_lines(text: &str) -> Vec { - text.lines() - .map(|l| crate::model::LyricLine { - at_ms: 0, - text: l.trim_end().to_owned(), - }) - .collect() -} - -/// Parse an LRC body (`[mm:ss.xx] line`) into sorted, timestamped lines. Malformed stamps are -/// skipped rather than failing the whole set. -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(crate::model::LyricLine { - at_ms, - text: line[close + 1..].trim().to_owned(), - }); - } - out.sort_by_key(|l| l.at_ms); - out -} - -/// `mm:ss.xx` (or `.xxx`) to milliseconds. A two-digit fraction is hundredths. -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 frac: u64 = frac - .chars() - .take(3) - .collect::() - .parse() - .unwrap_or(0); - let ms = match frac.to_string().len() { - 1 => frac * 100, - 2 => frac * 10, - _ => frac, - }; - Some(mm * 60_000 + ss * 1000 + ms) -} - /// The `yt-dlp` binary to run. /// /// yt-dlp is not optional (it is the only resolver that actually produces a playable URL; see @@ -2808,35 +2706,41 @@ impl Backend { // is `None` with no session — and the settings toggle is read per track, so flipping it // takes effect on the next song, not mid-song. - /// Fetch lyrics for `track`: LRCLIB's synced text first, InnerTube's plain text as fallback. - /// With `lrclib` off (the Settings switch), InnerTube's alone. - pub fn fetch_lyrics(&self, track: Track, lrclib: bool) { - let (tx, ctx, http, api) = ( - self.tx.clone(), - self.ctx.clone(), - self.http.clone(), - Arc::clone(&self.api), - ); - self.rt.spawn(async move { - let video_id = track.video_id.clone(); - let synced = if lrclib { - self::lrclib(&http, &track).await - } else { - None - }; - let lyrics = match synced { - Some(lyrics) => Some(lyrics), - None => api.lyrics(&track.video_id).await.unwrap_or(None), - }; - let event = match lyrics { - Some(lyrics) => Event::LyricsLoaded { video_id, lyrics }, - None => Event::LyricsFailed { - video_id, - error: "No lyrics found".to_owned(), - }, - }; - Self::emit(&tx, &ctx, event); - }); + /// Ask each of `sources` for `track`'s lyrics, all at once. Each answers with its own + /// [`Event::LyricsSource`] as it lands, within [`crate::lyrics::SOURCE_TIMEOUT`]. + pub fn fetch_lyrics(&self, track: Track, sources: Vec) { + for source in sources { + let (tx, ctx, http, api, track) = ( + self.tx.clone(), + self.ctx.clone(), + self.http.clone(), + Arc::clone(&self.api), + track.clone(), + ); + self.rt.spawn(async move { + let found = tokio::time::timeout( + crate::lyrics::SOURCE_TIMEOUT, + crate::lyrics::fetch(source, &http, &api, &track), + ) + .await + .unwrap_or_else(|_| { + Err(anyhow::anyhow!("{} did not answer in time", source.label())) + }) + .map_err(|e| format!("{e:#}")); + if let Err(error) = &found { + debug!(source = source.label(), %error, "lyrics source failed"); + } + Self::emit( + &tx, + &ctx, + Event::LyricsSource { + video_id: track.video_id.clone(), + source, + found, + }, + ); + }); + } } /// Fetch and decode a cover. @@ -3117,25 +3021,6 @@ mod tests { ); } - /// LRC stamps: two-digit fractions are hundredths, three are milliseconds, and a malformed - /// stamp is skipped rather than dropping the whole lyric set. - #[test] - fn lrc_times_parse_in_both_fraction_widths() { - 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("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"); - } - /// The tick fields land on the base, the session the base carries is untouched, and a base /// without a query still gets one. #[test] diff --git a/crates/refryt/src/lib.rs b/crates/refryt/src/lib.rs index 098eef8..27e74e9 100644 --- a/crates/refryt/src/lib.rs +++ b/crates/refryt/src/lib.rs @@ -42,6 +42,7 @@ pub mod liked; pub mod listening_stats; pub mod local; pub mod local_playlists; +pub mod lyrics; pub mod media; pub mod memory; /// The project's home on GitHub. diff --git a/crates/refryt/src/lyrics/better_lyrics.rs b/crates/refryt/src/lyrics/better_lyrics.rs new file mode 100644 index 0000000..7877c02 --- /dev/null +++ b/crates/refryt/src/lyrics/better_lyrics.rs @@ -0,0 +1,150 @@ +//! 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 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; + } + lines.push(LyricLine { + at_ms: at_ms.unwrap_or(0), + text, + }); + } + 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(), + }) +} + +/// 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"); + } + + #[test] + fn untimed_ttml_is_plain_text() { + let ttml = r#"

One

Two

"#; + 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/genius.rs b/crates/refryt/src/lyrics/genius.rs new file mode 100644 index 0000000..e8c0c53 --- /dev/null +++ b/crates/refryt/src/lyrics/genius.rs @@ -0,0 +1,277 @@ +//! Genius: plain text, no timing, but the largest catalogue there is. Last in the default +//! order, and only shown when no source had timed lyrics. +//! +//! Its site search (`api/search/multi`) finds the song page; the lyrics are the page's +//! `data-lyrics-container` blocks, with `
` as line breaks. The page is read without an HTML +//! library: only those blocks are taken, and inside them only text and line breaks are kept. +//! Section headers ("[Chorus]") are dropped, since no other source has them. + +use anyhow::{Context, Result}; + +use crate::model::{Lyrics, Track}; + +pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> { + let title = super::title_core_display(&track.title); + let artist = track.artist_line(); + let found: serde_json::Value = http + .get("https://genius.com/api/search/multi") + .query(&[("q", format!("{artist} {title}").trim())]) + .header(reqwest::header::USER_AGENT, super::USER_AGENT) + .timeout(super::SOURCE_TIMEOUT) + .send() + .await + .context("Genius search")? + .error_for_status() + .context("Genius search")? + .json() + .await + .context("Genius search")?; + let Some(url) = best_url(&found, &title, &artist) else { + return Ok(None); + }; + let page = http + .get(url) + .header(reqwest::header::USER_AGENT, super::USER_AGENT) + .timeout(super::SOURCE_TIMEOUT) + .send() + .await + .context("Genius page")? + .error_for_status() + .context("Genius page")? + .text() + .await + .context("Genius page")?; + let lines = lyric_lines(&page); + if lines.is_empty() { + return Ok(None); + } + Ok(Some(Lyrics { + lines: lines + .into_iter() + .map(|text| crate::model::LyricLine { at_ms: 0, text }) + .collect(), + synced: false, + source: "Genius".to_owned(), + })) +} + +/// The song hit whose title and artist both match; a translation or romanisation page loses +/// to the original. Only genius.com song pages are followed. +fn best_url(found: &serde_json::Value, title: &str, artist: &str) -> Option { + let want_title = super::normalised(title); + let want_artists = super::artist_names(artist); + let sections = found.pointer("/response/sections")?.as_array()?; + let hits = sections + .iter() + .find(|s| s.get("type").and_then(|t| t.as_str()) == Some("song"))? + .get("hits")? + .as_array()?; + hits.iter() + .filter_map(|h| h.get("result")) + .filter_map(|r| { + let url = r.get("url")?.as_str()?; + if !url.starts_with("https://genius.com/") { + return None; + } + let name = super::normalised(&super::title_core_display(r.get("title")?.as_str()?)); + let by = r + .get("artist_names") + .and_then(|a| a.as_str()) + .unwrap_or_default(); + let artist_ok = want_artists.is_empty() + || super::artist_names(by) + .iter() + .any(|a| want_artists.contains(a)); + if name != want_title || !artist_ok { + return None; + } + let path = url.to_ascii_lowercase(); + let side_page = ["translation", "romanized", "annotated", "tracklist"] + .iter() + .any(|w| path.contains(w)); + Some((side_page, url.to_owned())) + }) + .min_by_key(|(side_page, _)| *side_page) + .map(|(_, url)| url) +} + +/// The text of every `data-lyrics-container="true"` block, one entry per line, with headers, +/// blank runs and Genius's own furniture taken out. +fn lyric_lines(html: &str) -> Vec { + let mut text = String::new(); + let mut rest = html; + while let Some(at) = rest.find("data-lyrics-container=\"true\"") { + let Some(open_end) = rest[at..].find('>') else { + break; + }; + let body = &rest[at + open_end + 1..]; + let (inner, after) = until_close(body); + text.push_str(&block_text(inner)); + text.push('\n'); + rest = after; + } + let mut lines: Vec = Vec::new(); + for line in text.lines() { + let line = line.trim(); + let header = line.starts_with('[') && line.ends_with(']'); + if header { + continue; + } + if line.is_empty() { + if lines.last().is_some_and(|l| !l.is_empty()) { + lines.push(String::new()); + } + continue; + } + lines.push(line.to_owned()); + } + while lines.last().is_some_and(String::is_empty) { + lines.pop(); + } + lines +} + +/// Split at the `` that closes the block `body` starts inside. +fn until_close(body: &str) -> (&str, &str) { + until_close_of(body, "div") +} + +/// Split at the close tag of the `name` element `body` starts inside: only `(body: &'a str, name: &str) -> (&'a str, &'a str) { + let open = format!("<{name}"); + let close = format!("' || c == '/' || c.is_whitespace()) + && !tag.split('>').next().unwrap_or_default().ends_with('/') + { + depth += 1; + } + i += lt + 1; + } + (body, "") +} + +/// A block's text: `
` as a line break, any element marked +/// `data-exclude-from-selection="true"` (Genius's "N Contributors" header and the like) +/// skipped whole, other tags removed, entities decoded. +fn block_text(block: &str) -> String { + let mut out = String::new(); + let mut rest = block; + while let Some(lt) = rest.find('<') { + out.push_str(&decode(&rest[..lt])); + let Some(gt) = rest[lt..].find('>') else { + rest = ""; + break; + }; + let tag = &rest[lt + 1..lt + gt]; + rest = &rest[lt + gt + 1..]; + let name: String = tag + .chars() + .take_while(|c| c.is_ascii_alphanumeric()) + .collect::() + .to_ascii_lowercase(); + if name == "br" { + out.push('\n'); + } else if !name.is_empty() + && !tag.ends_with('/') + && tag.contains("data-exclude-from-selection=\"true\"") + { + let (_, after) = until_close_of(rest, &name); + rest = after.split_once('>').map_or("", |(_, r)| r); + } + } + out.push_str(&decode(rest)); + out +} + +/// The entities Genius pages use: the named five, ` `, and numeric ones. +fn decode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(amp) = rest.find('&') { + out.push_str(&rest[..amp]); + let after = &rest[amp..]; + let Some(semi) = after.find(';').filter(|s| *s <= 10) else { + out.push('&'); + rest = &after[1..]; + continue; + }; + let entity = &after[1..semi]; + let c = match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some(' '), + _ => entity + .strip_prefix("#x") + .or_else(|| entity.strip_prefix("#X")) + .and_then(|h| u32::from_str_radix(h, 16).ok()) + .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok())) + .and_then(char::from_u32), + }; + match c { + Some(c) => { + out.push(c); + rest = &after[semi + 1..]; + } + None => { + out.push('&'); + rest = &after[1..]; + } + } + } + out.push_str(rest); + out.replace(['\u{200B}', '\u{FEFF}'], "") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lyrics_come_out_of_the_containers_without_headers_or_furniture() { + let html = r#"

Not lyrics
+
12 Contributors
Blinding Lights Lyrics
[Intro]
Yeah

[Verse 1]
I've been tryna call
I've been on my own & long enough
+
between
+
Maybe you can show me how to love, maybe
"#; + assert_eq!( + lyric_lines(html), + [ + "Yeah", + "", + "I've been tryna call", + "I've been on my own & long enough", + "Maybe you can show me how to love, maybe", + ] + ); + } + + #[test] + fn the_original_page_wins_over_a_translation() { + let found = serde_json::json!({"response": {"sections": [ + {"type": "top_hit", "hits": []}, + {"type": "song", "hits": [ + {"result": {"title": "Glue (Traducción al Español)", "artist_names": "Genius Traducciones al Español", "url": "https://genius.com/x-translation"}}, + {"result": {"title": "Glue", "artist_names": "Bicep", "url": "https://genius.com/Bicep-glue-lyrics"}}, + {"result": {"title": "Glue", "artist_names": "Bicep", "url": "https://evil.example/Bicep-glue-lyrics"}} + ]} + ]}}); + assert_eq!( + best_url(&found, "Glue", "Bicep").as_deref(), + Some("https://genius.com/Bicep-glue-lyrics") + ); + assert_eq!(best_url(&found, "Glue", "Someone Else"), 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..dd64c4c --- /dev/null +++ b/crates/refryt/src/lyrics/lrclib.rs @@ -0,0 +1,147 @@ +//! 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(), + }) + .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..]), + }); + } + 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..e9e9792 --- /dev/null +++ b/crates/refryt/src/lyrics/mod.rs @@ -0,0 +1,514 @@ +//! 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 genius; +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, + /// Genius: plain text from the biggest catalogue there is. + Genius, +} + +impl Source { + /// Every source, in the default order. + pub const ALL: [Source; 8] = [ + Source::BetterLyrics, + Source::LrcRed, + Source::YouTubeSynced, + Source::Lrclib, + Source::KuGou, + Source::Unison, + Source::YouTube, + Source::Genius, + ]; + + /// 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::Genius => "genius", + 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::Genius => "Genius", + 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::Genius => "Genius", + 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." + } + Source::Genius => { + "Plain text, no timing, from the biggest catalogue. Gets the title and artist." + } + } + } +} + +/// 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. +pub fn pick(order: &[Source], answers: &HashMap) -> Pick { + let mut plain = None; + for source in order { + match answers.get(source) { + None | Some(Answer::Pending) => return Pick::Wait, + Some(Answer::Found(lyrics)) if lyrics.synced => return Pick::Use(*source), + Some(Answer::Found(_)) => { + plain.get_or_insert(*source); + } + Some(Answer::Missing) => {} + } + } + plain.map_or(Pick::Nothing, Pick::Use) +} + +/// 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> { + 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, + Source::Genius => genius::lyrics(http, track).await, + } +} + +// 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(), + }], + 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), 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), 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), Pick::Wait); + a.insert(Lrclib, Answer::Found(lyrics(true))); + assert_eq!(pick(&order, &a), Pick::Use(Lrclib)); + a.insert(Lrclib, Answer::Missing); + assert_eq!(pick(&order, &a), 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), Pick::Nothing); + assert_eq!(pick(&[], &a), Pick::Nothing); + } + + #[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), + (Genius, true), + ] + ); + assert_eq!( + asked(&saved), + vec![ + BetterLyrics, + LrcRed, + YouTubeSynced, + KuGou, + Unison, + YouTube, + Genius + ] + ); + } + + #[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..856cfba --- /dev/null +++ b/crates/refryt/src/lyrics/youtube.rs @@ -0,0 +1,181 @@ +//! 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(), + }) + }) + .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/settings.rs b/crates/refryt/src/settings.rs index 1a8f106..7817827 100644 --- a/crates/refryt/src/settings.rs +++ b/crates/refryt/src/settings.rs @@ -420,10 +420,15 @@ 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, + /// 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 +491,8 @@ impl Default for Settings { discord_rich_presence: false, cast_receiver: false, cast_networks: Vec::new(), - lrclib_lyrics: true, + lyrics_sources: Vec::new(), + lrclib_lyrics: None, local_folders: Vec::new(), playlist_default_sort: crate::app::PlaylistSort::Default, sidebar_width: None, @@ -538,6 +544,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()) { @@ -667,9 +681,42 @@ 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, + Genius + ] + ); + 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" ); } diff --git a/crates/refryt/src/ui/lyrics.rs b/crates/refryt/src/ui/lyrics.rs index 111426a..b55ab39 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() @@ -68,7 +75,7 @@ pub fn panel(app: &mut App, ui: &mut egui::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 @@ -126,11 +133,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 +150,50 @@ 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 options = app + .lyrics_order + .iter() + .filter_map(|source| match app.lyrics_answers.get(source) { + 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 +202,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..7422eb6 --- /dev/null +++ b/crates/refryt/src/ui/lyrics_sources.rs @@ -0,0 +1,259 @@ +//! 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 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); + // Padding, title, line, gaps and buttons around the rows; the rows scroll when the window + // is too short for all of them. + let chrome = 16.0 + 22.0 + 6.0 + 36.0 + 12.0 + 12.0 + 30.0 + 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("Lyrics sources") + .font(theme::semibold(15.0)) + .color(p.text), + ); + body.add_space(6.0); + body.label( + egui::RichText::new( + "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.", + ) + .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; + body.scope_builder(egui::UiBuilder::new().max_rect(switch), |ui| { + widgets::toggle(ui, &p, ui.id().with(("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(), 30.0), |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..200c942 100644 --- a/crates/refryt/src/ui/mod.rs +++ b/crates/refryt/src/ui/mod.rs @@ -15,6 +15,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; diff --git a/crates/refryt/src/ui/settings.rs b/crates/refryt/src/ui/settings.rs index a703527..f6c7398 100644 --- a/crates/refryt/src/ui/settings.rs +++ b/crates/refryt/src/ui/settings.rs @@ -955,7 +955,20 @@ 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; + // 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,15 +1015,9 @@ fn system(app: &mut App, ui: &mut egui::Ui) { "Shows what you're playing on Discord.", &mut discord, ); - 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, - ); + g.row(ui, "Lyrics sources", &lyrics_summary, |ui| { + open_lyrics_sources = widgets::outline_button(ui, &p, "Change…").clicked(); + }); }); let ctx = ui.ctx().clone(); @@ -1021,11 +1028,13 @@ 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; }); 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); } From 90c5d3e1cab8c165c6ca7d4ac8430887adb35d9a Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 18:33:58 +0200 Subject: [PATCH 02/12] fix: the album rows' hover play icon sits over the number The icon that takes a track number's place on hover was centred in the whole number column, so it landed right of the number and reached into the gap before the title. It now ends where the numbers end, and so does the loading spinner. The row test now looks for the number itself rather than any text in the column. --- crates/refryt/src/widgets.rs | 43 +++++++++++++++++------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/crates/refryt/src/widgets.rs b/crates/refryt/src/widgets.rs index 3578db2..f7dc492 100644 --- a/crates/refryt/src/widgets.rs +++ b/crates/refryt/src/widgets.rs @@ -2788,38 +2788,31 @@ 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, so what takes a number's place ends + // there too: centred in the whole column it sat right of every number and reached + // into the gap before the title. + let number_right = rect.left() + left_inset + num_w - theme::ROW_NUMBER_GAP; + let glyph = 14.0; + let in_place = Rect::from_min_size( + egui::pos2(number_right - glyph, rect.center().y - glyph / 2.0), + 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), @@ -6684,10 +6677,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; } From b6215babc9c4b0e8cada6b4c41bb398462174184 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 18:33:58 +0200 Subject: [PATCH 03/12] feat: macOS, Windows and Breeze themes, and a fresh install starts on the system's Six new built-in themes: macOS Dark and Light, Windows Dark and Light (Windows 11 Fluent), and Breeze Dark and Light (KDE Plasma). Existing installs get them in their themes folder on the next start. A first start on a Mac uses macOS Dark, and on Windows uses Windows Dark, with the matching light theme for light mode. Linux keeps Classic. A settings file that already exists keeps the theme it names, so nobody's look changes on an update. --- README.md | 3 +- crates/refryt/src/settings.rs | 46 ++++++++++++++++++++++++-- crates/refryt/src/theme/custom.rs | 38 ++++++++++++++++++++- crates/refryt/themes/Breeze Dark.css | 26 +++++++++++++++ crates/refryt/themes/Breeze Light.css | 26 +++++++++++++++ crates/refryt/themes/Windows Dark.css | 26 +++++++++++++++ crates/refryt/themes/Windows Light.css | 26 +++++++++++++++ crates/refryt/themes/macOS Dark.css | 26 +++++++++++++++ crates/refryt/themes/macOS Light.css | 26 +++++++++++++++ docs/THEMES.md | 7 ++-- 10 files changed, 243 insertions(+), 7 deletions(-) create mode 100644 crates/refryt/themes/Breeze Dark.css create mode 100644 crates/refryt/themes/Breeze Light.css create mode 100644 crates/refryt/themes/Windows Dark.css create mode 100644 crates/refryt/themes/Windows Light.css create mode 100644 crates/refryt/themes/macOS Dark.css create mode 100644 crates/refryt/themes/macOS Light.css diff --git a/README.md b/README.md index 12947ba..ee73c71 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,8 @@ Built with Rust and [egui](https://github.com/emilk/egui), [mpv](https://mpv.io/ [Tokyo Night](https://github.com/folke/tokyonight.nvim), [Dracula](https://spec.draculatheme.com), [Rosé Pine](https://github.com/rose-pine/palette), [Everforest](https://github.com/sainnhe/everforest), - [Solarized](https://ethanschoonover.com/solarized) and Spotify's own colours. Each file in + [Solarized](https://ethanschoonover.com/solarized), Spotify's own colours, the system + colours of macOS and Windows 11, and KDE Plasma's Breeze. Each file in `crates/refryt/themes` names its source. ## Licence diff --git a/crates/refryt/src/settings.rs b/crates/refryt/src/settings.rs index 7817827..b8ea075 100644 --- a/crates/refryt/src/settings.rs +++ b/crates/refryt/src/settings.rs @@ -505,6 +505,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 { @@ -628,8 +641,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"); @@ -723,6 +738,33 @@ mod tests { /// 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. + /// 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 = diff --git a/crates/refryt/src/theme/custom.rs b/crates/refryt/src/theme/custom.rs index 82b54d9..e2d9757 100644 --- a/crates/refryt/src/theme/custom.rs +++ b/crates/refryt/src/theme/custom.rs @@ -210,12 +210,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 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..fbbad25 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 From 785c48eff02247d4f4489da934dc93b5dec2e38b Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 22:50:14 +0200 Subject: [PATCH 04/12] feat: GTK and Qt themes that follow the desktop, on Linux Two more entries in the theme list, offered in both modes: "GTK" and "Qt". Like Chrome's, they take their colours from the desktop. Qt's come from kdeglobals and the colour scheme it names. GTK's come from the GTK theme's named colours, read by refryt in a child process. Both are read again when the window regains focus, so a change of desktop theme follows. Picking one sets it for light and dark alike. --- crates/refryt/src/app.rs | 42 ++- crates/refryt/src/main.rs | 11 + crates/refryt/src/settings.rs | 32 ++- crates/refryt/src/theme.rs | 1 + crates/refryt/src/theme/custom.rs | 22 +- crates/refryt/src/theme/system.rs | 445 ++++++++++++++++++++++++++++++ crates/refryt/src/ui/settings.rs | 16 +- docs/THEMES.md | 8 + 8 files changed, 564 insertions(+), 13 deletions(-) create mode 100644 crates/refryt/src/theme/system.rs diff --git a/crates/refryt/src/app.rs b/crates/refryt/src/app.rs index 86b63a0..1ef37df 100644 --- a/crates/refryt/src/app.rs +++ b/crates/refryt/src/app.rs @@ -1440,6 +1440,8 @@ pub struct App { pub(crate) custom_themes: theme::custom::Themes, /// Raised by the folder watcher when a theme file is added, removed or saved. theme_watch: theme::custom::Watcher, + /// The GTK colours, read off the UI thread (`theme::system`). + gtk_watch: theme::system::GtkWatch, /// Whether the window had focus on the last frame, to notice it coming back. was_focused: bool, history: History, @@ -2094,7 +2096,17 @@ impl App { // names a theme, so an old settings file and `--scheme` both resolve against it. theme::custom::seed(); widgets::init_reduced_motion(); - let custom_themes = theme::custom::load(); + let mut custom_themes = theme::custom::load(); + // The desktop's themes. GTK takes a child process: waited for only when it is the theme + // about to paint, so the first frame isn't another theme's; otherwise read in the + // background once the app is up. + custom_themes.set_system(theme::system::QT, theme::system::qt().into_iter().collect()); + let gtk_now = [&settings.dark_theme, &settings.light_theme] + .iter() + .any(|n| n.as_str() == theme::system::GTK); + if gtk_now { + custom_themes.set_system(theme::system::GTK, theme::system::gtk()); + } for (file, error) in &custom_themes.errors { tracing::warn!(%file, %error, "custom theme did not load"); } @@ -2165,6 +2177,7 @@ impl App { palette, custom_themes, theme_watch, + gtk_watch: theme::system::GtkWatch::default(), was_focused: true, // Open on Home, as YouTube Music does — it is a real feed now rather than a page we // assembled. `--search` starts on Search, and `--page` overrides both. @@ -2419,6 +2432,9 @@ impl App { local_browse_path: Vec::new(), local_playlists: crate::local_playlists::load(), }; + if !gtk_now { + app.gtk_watch.refresh(&cc.egui_ctx); + } app.resync_local_playlists(); if !app.settings.local_folders.is_empty() { app.local_scanning = true; @@ -2621,14 +2637,32 @@ impl App { fn reload_custom_themes(&mut self, ctx: &egui::Context) { // The way back from an editor: the window is focused again, so look at the folder. let focused = ctx.input(|i| i.viewport().focused.unwrap_or(false)); + let mut themes = None; if focused && !self.was_focused { self.theme_watch.check(); + // The desktop's theme may have changed meanwhile too. + self.gtk_watch.refresh(ctx); + let mut t = self.custom_themes.clone(); + t.set_system(theme::system::QT, theme::system::qt().into_iter().collect()); + themes = Some(t); } self.was_focused = focused; - if !self.theme_watch.take_changed() { - return; + if let Some(gtk) = self.gtk_watch.take() { + themes + .get_or_insert_with(|| self.custom_themes.clone()) + .set_system(theme::system::GTK, gtk); } - let themes = theme::custom::load(); + if self.theme_watch.take_changed() { + let mut files = theme::custom::load(); + files.system = themes + .take() + .unwrap_or_else(|| self.custom_themes.clone()) + .system; + themes = Some(files); + } + let Some(themes) = themes else { + return; + }; if themes == self.custom_themes { return; } diff --git a/crates/refryt/src/main.rs b/crates/refryt/src/main.rs index 1bc0628..fdd4f51 100644 --- a/crates/refryt/src/main.rs +++ b/crates/refryt/src/main.rs @@ -137,6 +137,17 @@ fn main() -> eframe::Result { #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] let autostart = false; + // 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. + #[cfg(target_os = "linux")] + if args.iter().any(|a| a == refryt::theme::system::GTK_ARG) { + std::process::exit(if refryt::theme::system::gtk_child() { + 0 + } else { + 1 + }); + } + // The child half of the in-app sign-in window: `webview_login::capture` starts this same // binary with `--sign-in-window `, because tao's event loop cannot be created beside // eframe's winit one in the same process (it faults natively on Windows). Handled here — diff --git a/crates/refryt/src/settings.rs b/crates/refryt/src/settings.rs index b8ea075..a717b62 100644 --- a/crates/refryt/src/settings.rs +++ b/crates/refryt/src/settings.rs @@ -525,6 +525,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) } @@ -738,6 +741,33 @@ mod tests { /// 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] @@ -989,7 +1019,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 e2d9757..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) } @@ -436,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) } @@ -500,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() { @@ -827,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..d49655d --- /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() }; + } + match serde_json::to_string(&answer) { + Ok(line) => { + println!("{line}"); + true + } + 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/settings.rs b/crates/refryt/src/ui/settings.rs index f6c7398..76ccbdf 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; diff --git a/docs/THEMES.md b/docs/THEMES.md index fbbad25..d289aed 100644 --- a/docs/THEMES.md +++ b/docs/THEMES.md @@ -26,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 From 4283c9efbc4672cc4e2ba8278faa7391200770f3 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 22:50:24 +0200 Subject: [PATCH 05/12] fix: settings rows keep a margin under long descriptions; the lyrics sources window fits its rows A settings row whose description wraps past two lines grew taller, but its last line sat on the row's bottom edge. It now keeps 10 px under it. Rows whose words fit are unchanged. In the Lyrics sources window each source's switch left the list's cursor halfway down its row, so every row started 21 px inside the one before and they overlapped, leaving empty space under the list. The switches are now placed apart from the list, and the card's height is measured from its title, description and buttons. --- crates/refryt/src/ui/lyrics_sources.rs | 53 ++++++++++++++++++-------- crates/refryt/src/widgets.rs | 10 +++++ 2 files changed, 48 insertions(+), 15 deletions(-) diff --git a/crates/refryt/src/ui/lyrics_sources.rs b/crates/refryt/src/ui/lyrics_sources.rs index 7422eb6..5daf247 100644 --- a/crates/refryt/src/ui/lyrics_sources.rs +++ b/crates/refryt/src/ui/lyrics_sources.rs @@ -13,6 +13,12 @@ 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)> { @@ -34,9 +40,23 @@ pub(crate) fn modal(app: &mut App, ui: &mut egui::Ui) { let p = app.palette; let list = lyrics::normalise(&app.settings.lyrics_sources); let width = WIDTH.min(screen.width() - 40.0); - // Padding, title, line, gaps and buttons around the rows; the rows scroll when the window - // is too short for all of them. - let chrome = 16.0 + 22.0 + 6.0 + 36.0 + 12.0 + 12.0 + 30.0 + 16.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); @@ -86,19 +106,15 @@ pub(crate) fn modal(app: &mut App, ui: &mut egui::Ui) { ); body.spacing_mut().item_spacing.y = 0.0; body.label( - egui::RichText::new("Lyrics sources") + egui::RichText::new(TITLE) .font(theme::semibold(15.0)) .color(p.text), ); body.add_space(6.0); body.label( - egui::RichText::new( - "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.", - ) - .font(theme::regular(12.0)) - .color(p.secondary), + egui::RichText::new(INTRO) + .font(theme::regular(12.0)) + .color(p.secondary), ); body.add_space(12.0); @@ -165,9 +181,16 @@ pub(crate) fn modal(app: &mut App, ui: &mut egui::Ui) { egui::vec2(40.0, 22.0), ); let mut value = *on; - body.scope_builder(egui::UiBuilder::new().max_rect(switch), |ui| { - widgets::toggle(ui, &p, ui.id().with(("lyrics-source", i)), &mut value); - }); + // 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); } @@ -196,7 +219,7 @@ pub(crate) fn modal(app: &mut App, ui: &mut egui::Ui) { }); body.add_space(12.0); - body.allocate_ui(egui::vec2(body.available_width(), 30.0), |ui| { + 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; diff --git a/crates/refryt/src/widgets.rs b/crates/refryt/src/widgets.rs index f7dc492..6150dc0 100644 --- a/crates/refryt/src/widgets.rs +++ b/crates/refryt/src/widgets.rs @@ -4893,6 +4893,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`]. @@ -4946,9 +4948,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)); + } }); }, ); From 09f933fcf5dd4e63d07c2282b26b5ee5e51d19b8 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 22:50:27 +0200 Subject: [PATCH 06/12] fix: the album rows' hover play icon centres on a one-digit number Ending it at the numbers' right edge put it left of the usual one-digit track number. It now sits over the number for tracks 1 to 9, and still covers a two-digit one. --- crates/refryt/src/widgets.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/refryt/src/widgets.rs b/crates/refryt/src/widgets.rs index 6150dc0..7a2d3b4 100644 --- a/crates/refryt/src/widgets.rs +++ b/crates/refryt/src/widgets.rs @@ -2788,13 +2788,14 @@ 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, so what takes a number's place ends - // there too: centred in the whole column it sat right of every number and reached - // into the gap before the title. + // 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 in_place = Rect::from_min_size( - egui::pos2(number_right - glyph, rect.center().y - glyph / 2.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 { From c673dc2f37e2cbca5491bc5e9b3b9ab95a0e3339 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sat, 21 Nov 2026 22:50:36 +0200 Subject: [PATCH 07/12] feat: prefer romanised lyrics, on by default For Japanese, Korean and Chinese songs, a lyrics source with romanised lines now wins over higher ones without, and each line leads with the romanisation, the original smaller under it. The first lyrics found still show at once; a romanised answer replaces them when it arrives. Romanisation comes from Apple Music's lyrics (BetterLyrics, lrc.red), which carry it alongside the lines, and from LRC files that hold the song in Japanese and again in romaji under the same timestamps: those twins are joined into one line, when they read as romaji across the whole file. The picker marks a source that has it. The setting is "Prefer romanised lyrics" in Settings. --- crates/refryt/src/api.rs | 1 + crates/refryt/src/app.rs | 10 +- crates/refryt/src/lyrics/better_lyrics.rs | 54 +++++ crates/refryt/src/lyrics/genius.rs | 6 +- crates/refryt/src/lyrics/lrclib.rs | 2 + crates/refryt/src/lyrics/mod.rs | 273 +++++++++++++++++++++- crates/refryt/src/lyrics/youtube.rs | 1 + crates/refryt/src/model.rs | 3 + crates/refryt/src/settings.rs | 5 + crates/refryt/src/ui/fullscreen.rs | 85 ++++++- crates/refryt/src/ui/lyrics.rs | 39 +++- crates/refryt/src/ui/settings.rs | 13 ++ 12 files changed, 461 insertions(+), 31 deletions(-) diff --git a/crates/refryt/src/api.rs b/crates/refryt/src/api.rs index 91d0481..0d71b8d 100644 --- a/crates/refryt/src/api.rs +++ b/crates/refryt/src/api.rs @@ -1629,6 +1629,7 @@ impl Api { .map(|l| model::LyricLine { at_ms: 0, text: l.trim_end().to_owned(), + romanised: None, }) .collect(), synced: false, diff --git a/crates/refryt/src/app.rs b/crates/refryt/src/app.rs index 1ef37df..1c1dba4 100644 --- a/crates/refryt/src/app.rs +++ b/crates/refryt/src/app.rs @@ -2721,6 +2721,10 @@ impl App { { self.fetch_lyrics(track); } + // Romanisation changes which answer is best, among the ones already in. + if self.settings.lyrics_romanisation != before.lyrics_romanisation { + self.show_lyrics(); + } if self.settings.cache_songs != before.cache_songs { self.backend .set_song_cache(self.settings.cache_songs, self.settings.cache_size.bytes()); @@ -7294,7 +7298,11 @@ impl App { }); let pick = match chosen { Some(source) => crate::lyrics::Pick::Use(source), - None => crate::lyrics::pick(&self.lyrics_order, &self.lyrics_answers), + None => crate::lyrics::pick( + &self.lyrics_order, + &self.lyrics_answers, + self.settings.lyrics_romanisation, + ), }; match pick { crate::lyrics::Pick::Wait => {} diff --git a/crates/refryt/src/lyrics/better_lyrics.rs b/crates/refryt/src/lyrics/better_lyrics.rs index 7877c02..0d15941 100644 --- a/crates/refryt/src/lyrics/better_lyrics.rs +++ b/crates/refryt/src/lyrics/better_lyrics.rs @@ -54,6 +54,7 @@ pub fn parse_ttml(ttml: &str) -> Option { .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")) { @@ -67,9 +68,19 @@ pub fn parse_ttml(ttml: &str) -> Option { 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() { @@ -87,6 +98,37 @@ pub fn parse_ttml(ttml: &str) -> Option { }) } +/// 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(" ") @@ -124,6 +166,18 @@ mod tests { 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#"shizumu you niHello

沈むように

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#"

One

Two

"#; diff --git a/crates/refryt/src/lyrics/genius.rs b/crates/refryt/src/lyrics/genius.rs index e8c0c53..177e2f9 100644 --- a/crates/refryt/src/lyrics/genius.rs +++ b/crates/refryt/src/lyrics/genius.rs @@ -48,7 +48,11 @@ pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result Vec { .map(|l| LyricLine { at_ms: 0, text: l.trim_end().to_owned(), + romanised: None, }) .collect() } @@ -76,6 +77,7 @@ pub fn parse_lrc(text: &str) -> Vec { out.push(LyricLine { at_ms, text: without_word_stamps(&line[close + 1..]), + romanised: None, }); } out.sort_by_key(|l| l.at_ms); diff --git a/crates/refryt/src/lyrics/mod.rs b/crates/refryt/src/lyrics/mod.rs index e9e9792..259f4b4 100644 --- a/crates/refryt/src/lyrics/mod.rs +++ b/crates/refryt/src/lyrics/mod.rs @@ -228,19 +228,157 @@ pub enum Pick { /// 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. -pub fn pick(order: &[Source], answers: &HashMap) -> Pick { +/// +/// 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 Pick::Wait, - Some(Answer::Found(lyrics)) if lyrics.synced => return Pick::Use(*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) => {} } } - plain.map_or(Pick::Nothing, Pick::Use) + 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 @@ -251,7 +389,7 @@ pub async fn fetch( api: &crate::api::Api, track: &crate::model::Track, ) -> anyhow::Result> { - match source { + 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), @@ -260,7 +398,11 @@ pub async fn fetch( Source::KuGou => kugou::lyrics(http, track).await, Source::Unison => unison::lyrics(http, track).await, Source::Genius => genius::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. @@ -373,6 +515,7 @@ mod tests { lines: vec![LyricLine { at_ms: 0, text: "la".to_owned(), + romanised: None, }], synced, source: String::new(), @@ -393,7 +536,7 @@ mod tests { (YouTubeSynced, Answer::Found(lyrics(true))), (Lrclib, Answer::Found(lyrics(true))), ]); - assert_eq!(pick(&order, &a), Pick::Use(YouTubeSynced)); + assert_eq!(pick(&order, &a, false), Pick::Use(YouTubeSynced)); } /// A lower source answering first doesn't jump ahead of one still out above it. @@ -404,7 +547,7 @@ mod tests { (BetterLyrics, Answer::Pending), (Lrclib, Answer::Found(lyrics(true))), ]); - assert_eq!(pick(&order, &a), Pick::Wait); + assert_eq!(pick(&order, &a, false), Pick::Wait); } #[test] @@ -414,19 +557,125 @@ mod tests { (YouTube, Answer::Found(lyrics(false))), (Lrclib, Answer::Pending), ]); - assert_eq!(pick(&order, &a), Pick::Wait); + assert_eq!(pick(&order, &a, false), Pick::Wait); a.insert(Lrclib, Answer::Found(lyrics(true))); - assert_eq!(pick(&order, &a), Pick::Use(Lrclib)); + assert_eq!(pick(&order, &a, false), Pick::Use(Lrclib)); a.insert(Lrclib, Answer::Missing); - assert_eq!(pick(&order, &a), Pick::Use(YouTube)); + 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), Pick::Nothing); - assert_eq!(pick(&[], &a), Pick::Nothing); + 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] diff --git a/crates/refryt/src/lyrics/youtube.rs b/crates/refryt/src/lyrics/youtube.rs index 856cfba..0a7fc65 100644 --- a/crates/refryt/src/lyrics/youtube.rs +++ b/crates/refryt/src/lyrics/youtube.rs @@ -87,6 +87,7 @@ fn parse_timed(page: &Value) -> Option { Some(LyricLine { at_ms, text: text.trim().to_owned(), + romanised: None, }) }) .collect(); 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 a717b62..6b5ed99 100644 --- a/crates/refryt/src/settings.rs +++ b/crates/refryt/src/settings.rs @@ -425,6 +425,10 @@ pub struct Settings { /// 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)] @@ -492,6 +496,7 @@ impl Default for Settings { cast_receiver: false, cast_networks: Vec::new(), lyrics_sources: Vec::new(), + lyrics_romanisation: true, lrclib_lyrics: None, local_folders: Vec::new(), playlist_default_sort: crate::app::PlaylistSort::Default, 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/lyrics.rs b/crates/refryt/src/ui/lyrics.rs index b55ab39..dd60362 100644 --- a/crates/refryt/src/ui/lyrics.rs +++ b/crates/refryt/src/ui/lyrics.rs @@ -71,6 +71,7 @@ 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 @@ -90,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. @@ -104,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); @@ -122,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); } @@ -171,10 +194,14 @@ pub(crate) fn picker(app: &App) -> Option { }; // 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()))) diff --git a/crates/refryt/src/ui/settings.rs b/crates/refryt/src/ui/settings.rs index 76ccbdf..beacbb4 100644 --- a/crates/refryt/src/ui/settings.rs +++ b/crates/refryt/src/ui/settings.rs @@ -961,6 +961,7 @@ 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 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); @@ -1024,6 +1025,17 @@ fn system(app: &mut App, ui: &mut egui::Ui) { g.row(ui, "Lyrics sources", &lyrics_summary, |ui| { open_lyrics_sources = widgets::outline_button(ui, &p, "Change…").clicked(); }); + toggle_row( + g, + ui, + &p, + "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, + ); }); let ctx = ui.ctx().clone(); @@ -1034,6 +1046,7 @@ fn system(app: &mut App, ui: &mut egui::Ui) { } s.hide_tray_on_close = hide_tray; s.discord_rich_presence = discord; + s.lyrics_romanisation = romanisation; }); if cast != on_here { app.set_cast_here(&ctx, cast); From de375274802d4bbdadb5bda301e517d0c5f743a6 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sun, 22 Nov 2026 01:24:02 +0200 Subject: [PATCH 08/12] fix: read the GTK theme only when it's the theme or Settings is open Reading the GTK colours starts a child process, about 0.13 s of CPU and 85 MB each time. It ran in the background at startup and again whenever the window came back into focus, even for people not using the GTK theme. Now it runs only when GTK is the light or dark theme, or once Settings, where it's offered, is open. Qt's theme is still re-read on focus. --- crates/refryt/src/app.rs | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/refryt/src/app.rs b/crates/refryt/src/app.rs index 1c1dba4..26eeb93 100644 --- a/crates/refryt/src/app.rs +++ b/crates/refryt/src/app.rs @@ -1442,6 +1442,10 @@ pub struct App { theme_watch: theme::custom::Watcher, /// The GTK colours, read off the UI thread (`theme::system`). gtk_watch: theme::system::GtkWatch, + /// Whether the GTK colours have been asked for since the window last came back into focus. + /// Reading them starts a child process (about 0.13 s of CPU), so it happens only when GTK is + /// the theme or Settings is where its name is offered. + gtk_fresh: bool, /// Whether the window had focus on the last frame, to notice it coming back. was_focused: bool, history: History, @@ -2097,9 +2101,9 @@ impl App { theme::custom::seed(); widgets::init_reduced_motion(); let mut custom_themes = theme::custom::load(); - // The desktop's themes. GTK takes a child process: waited for only when it is the theme - // about to paint, so the first frame isn't another theme's; otherwise read in the - // background once the app is up. + // The desktop's themes. GTK takes a child process: waited for when it is the theme about + // to paint, so the first frame isn't another theme's; otherwise read only once Settings + // offers it (`reload_custom_themes`). custom_themes.set_system(theme::system::QT, theme::system::qt().into_iter().collect()); let gtk_now = [&settings.dark_theme, &settings.light_theme] .iter() @@ -2178,6 +2182,7 @@ impl App { custom_themes, theme_watch, gtk_watch: theme::system::GtkWatch::default(), + gtk_fresh: gtk_now, was_focused: true, // Open on Home, as YouTube Music does — it is a real feed now rather than a page we // assembled. `--search` starts on Search, and `--page` overrides both. @@ -2432,9 +2437,6 @@ impl App { local_browse_path: Vec::new(), local_playlists: crate::local_playlists::load(), }; - if !gtk_now { - app.gtk_watch.refresh(&cc.egui_ctx); - } app.resync_local_playlists(); if !app.settings.local_folders.is_empty() { app.local_scanning = true; @@ -2640,13 +2642,18 @@ impl App { let mut themes = None; if focused && !self.was_focused { self.theme_watch.check(); - // The desktop's theme may have changed meanwhile too. - self.gtk_watch.refresh(ctx); + // The desktop's theme may have changed meanwhile too. Qt's is two small files, read + // here; GTK's is read below, if it's wanted. + self.gtk_fresh = false; let mut t = self.custom_themes.clone(); t.set_system(theme::system::QT, theme::system::qt().into_iter().collect()); themes = Some(t); } self.was_focused = focused; + if !self.gtk_fresh && self.gtk_wanted() { + self.gtk_fresh = true; + self.gtk_watch.refresh(ctx); + } if let Some(gtk) = self.gtk_watch.take() { themes .get_or_insert_with(|| self.custom_themes.clone()) @@ -2677,6 +2684,15 @@ impl App { } } + /// Whether the GTK colours are needed: GTK is the theme in either mode, or Settings is open, + /// where it is offered. + fn gtk_wanted(&self) -> bool { + [&self.settings.dark_theme, &self.settings.light_theme] + .iter() + .any(|n| n.as_str() == theme::system::GTK) + || matches!(self.current_route(), Route::Settings) + } + pub(crate) fn update_settings( &mut self, ctx: &egui::Context, From 303cc74021c6b90f3a5ad2b90890563ea929be79 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sun, 22 Nov 2026 01:24:14 +0200 Subject: [PATCH 09/12] feat: drop Genius as a lyrics source Genius has only plain lyrics, and every song meant scraping a page of about 615 KB. It was also the slowest source but one (around 0.6 s). The other sources already cover it, synced ones included. A saved order that still lists Genius drops it. --- PRIVACY.md | 1 - README.md | 4 +- crates/refryt/src/lyrics/genius.rs | 281 ----------------------------- crates/refryt/src/lyrics/mod.rs | 24 +-- crates/refryt/src/settings.rs | 10 +- 5 files changed, 5 insertions(+), 315 deletions(-) delete mode 100644 crates/refryt/src/lyrics/genius.rs diff --git a/PRIVACY.md b/PRIVACY.md index 6b16ebd..b1be447 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -29,7 +29,6 @@ Google's privacy policy applies: . - **KuGou** (mobileservice.kugou.com, lyrics.kugou.com) gets the title, artist, album and length. - **Unison** (unison.boidu.dev) gets the title, artist, album and length. -- **Genius** (genius.com) gets the title and artist. - **YouTube Music**, for its synced and plain lyrics, gets the video id. These requests are sent without your Google session. diff --git a/README.md b/README.md index ee73c71..4eee4e6 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ Sign in from the app's own window, or use Import from browser on Home or in Sett Settings, themes, the session and the log live in `~/.config/refryt` on Linux, `~/Library/Application Support/refryt` on macOS and `~/.var/app/io.github.gridoe.refryt/config/refryt` in the Flatpak. The session is stored with owner-only permissions. -There is no telemetry. refryt connects to YouTube and a few lyrics sites (BetterLyrics, lrc.red, LRCLIB, KuGou, Unison and Genius) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. Each lyrics source and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. +There is no telemetry. refryt connects to YouTube and a few lyrics sites (BetterLyrics, lrc.red, LRCLIB, KuGou and Unison) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. Each lyrics source and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. ## Status @@ -229,7 +229,7 @@ Built with Rust and [egui](https://github.com/emilk/egui), [mpv](https://mpv.io/ runs out. - **Spotify's desktop app**: the shortcuts, select-then-play clicks, and the shape of the album, playlist and artist pages. -- **[BetterLyrics](https://github.com/better-lyrics/better-lyrics)**, **[lrc.red](https://lrc.red)**, **[LRCLIB](https://lrclib.net)**, **[KuGou](https://www.kugou.com)**, **Unison** and **[Genius](https://genius.com)**: lyrics. +- **[BetterLyrics](https://github.com/better-lyrics/better-lyrics)**, **[lrc.red](https://lrc.red)**, **[LRCLIB](https://lrclib.net)**, **[KuGou](https://www.kugou.com)** and **Unison**: lyrics. - **[BitChord](https://github.com/kushagrasinghx/BitChord)**: lyrics from several sources, tried in an order you set. - **Theme palettes**: [Catppuccin](https://github.com/catppuccin/palette), [Nord](https://www.nordtheme.com/docs/colors-and-palettes), diff --git a/crates/refryt/src/lyrics/genius.rs b/crates/refryt/src/lyrics/genius.rs deleted file mode 100644 index 177e2f9..0000000 --- a/crates/refryt/src/lyrics/genius.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Genius: plain text, no timing, but the largest catalogue there is. Last in the default -//! order, and only shown when no source had timed lyrics. -//! -//! Its site search (`api/search/multi`) finds the song page; the lyrics are the page's -//! `data-lyrics-container` blocks, with `
` as line breaks. The page is read without an HTML -//! library: only those blocks are taken, and inside them only text and line breaks are kept. -//! Section headers ("[Chorus]") are dropped, since no other source has them. - -use anyhow::{Context, Result}; - -use crate::model::{Lyrics, Track}; - -pub async fn lyrics(http: &reqwest::Client, track: &Track) -> Result> { - let title = super::title_core_display(&track.title); - let artist = track.artist_line(); - let found: serde_json::Value = http - .get("https://genius.com/api/search/multi") - .query(&[("q", format!("{artist} {title}").trim())]) - .header(reqwest::header::USER_AGENT, super::USER_AGENT) - .timeout(super::SOURCE_TIMEOUT) - .send() - .await - .context("Genius search")? - .error_for_status() - .context("Genius search")? - .json() - .await - .context("Genius search")?; - let Some(url) = best_url(&found, &title, &artist) else { - return Ok(None); - }; - let page = http - .get(url) - .header(reqwest::header::USER_AGENT, super::USER_AGENT) - .timeout(super::SOURCE_TIMEOUT) - .send() - .await - .context("Genius page")? - .error_for_status() - .context("Genius page")? - .text() - .await - .context("Genius page")?; - let lines = lyric_lines(&page); - if lines.is_empty() { - return Ok(None); - } - Ok(Some(Lyrics { - lines: lines - .into_iter() - .map(|text| crate::model::LyricLine { - at_ms: 0, - text, - romanised: None, - }) - .collect(), - synced: false, - source: "Genius".to_owned(), - })) -} - -/// The song hit whose title and artist both match; a translation or romanisation page loses -/// to the original. Only genius.com song pages are followed. -fn best_url(found: &serde_json::Value, title: &str, artist: &str) -> Option { - let want_title = super::normalised(title); - let want_artists = super::artist_names(artist); - let sections = found.pointer("/response/sections")?.as_array()?; - let hits = sections - .iter() - .find(|s| s.get("type").and_then(|t| t.as_str()) == Some("song"))? - .get("hits")? - .as_array()?; - hits.iter() - .filter_map(|h| h.get("result")) - .filter_map(|r| { - let url = r.get("url")?.as_str()?; - if !url.starts_with("https://genius.com/") { - return None; - } - let name = super::normalised(&super::title_core_display(r.get("title")?.as_str()?)); - let by = r - .get("artist_names") - .and_then(|a| a.as_str()) - .unwrap_or_default(); - let artist_ok = want_artists.is_empty() - || super::artist_names(by) - .iter() - .any(|a| want_artists.contains(a)); - if name != want_title || !artist_ok { - return None; - } - let path = url.to_ascii_lowercase(); - let side_page = ["translation", "romanized", "annotated", "tracklist"] - .iter() - .any(|w| path.contains(w)); - Some((side_page, url.to_owned())) - }) - .min_by_key(|(side_page, _)| *side_page) - .map(|(_, url)| url) -} - -/// The text of every `data-lyrics-container="true"` block, one entry per line, with headers, -/// blank runs and Genius's own furniture taken out. -fn lyric_lines(html: &str) -> Vec { - let mut text = String::new(); - let mut rest = html; - while let Some(at) = rest.find("data-lyrics-container=\"true\"") { - let Some(open_end) = rest[at..].find('>') else { - break; - }; - let body = &rest[at + open_end + 1..]; - let (inner, after) = until_close(body); - text.push_str(&block_text(inner)); - text.push('\n'); - rest = after; - } - let mut lines: Vec = Vec::new(); - for line in text.lines() { - let line = line.trim(); - let header = line.starts_with('[') && line.ends_with(']'); - if header { - continue; - } - if line.is_empty() { - if lines.last().is_some_and(|l| !l.is_empty()) { - lines.push(String::new()); - } - continue; - } - lines.push(line.to_owned()); - } - while lines.last().is_some_and(String::is_empty) { - lines.pop(); - } - lines -} - -/// Split at the `` that closes the block `body` starts inside. -fn until_close(body: &str) -> (&str, &str) { - until_close_of(body, "div") -} - -/// Split at the close tag of the `name` element `body` starts inside: only `(body: &'a str, name: &str) -> (&'a str, &'a str) { - let open = format!("<{name}"); - let close = format!("' || c == '/' || c.is_whitespace()) - && !tag.split('>').next().unwrap_or_default().ends_with('/') - { - depth += 1; - } - i += lt + 1; - } - (body, "") -} - -/// A block's text: `
` as a line break, any element marked -/// `data-exclude-from-selection="true"` (Genius's "N Contributors" header and the like) -/// skipped whole, other tags removed, entities decoded. -fn block_text(block: &str) -> String { - let mut out = String::new(); - let mut rest = block; - while let Some(lt) = rest.find('<') { - out.push_str(&decode(&rest[..lt])); - let Some(gt) = rest[lt..].find('>') else { - rest = ""; - break; - }; - let tag = &rest[lt + 1..lt + gt]; - rest = &rest[lt + gt + 1..]; - let name: String = tag - .chars() - .take_while(|c| c.is_ascii_alphanumeric()) - .collect::() - .to_ascii_lowercase(); - if name == "br" { - out.push('\n'); - } else if !name.is_empty() - && !tag.ends_with('/') - && tag.contains("data-exclude-from-selection=\"true\"") - { - let (_, after) = until_close_of(rest, &name); - rest = after.split_once('>').map_or("", |(_, r)| r); - } - } - out.push_str(&decode(rest)); - out -} - -/// The entities Genius pages use: the named five, ` `, and numeric ones. -fn decode(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - let mut rest = text; - while let Some(amp) = rest.find('&') { - out.push_str(&rest[..amp]); - let after = &rest[amp..]; - let Some(semi) = after.find(';').filter(|s| *s <= 10) else { - out.push('&'); - rest = &after[1..]; - continue; - }; - let entity = &after[1..semi]; - let c = match entity { - "amp" => Some('&'), - "lt" => Some('<'), - "gt" => Some('>'), - "quot" => Some('"'), - "apos" => Some('\''), - "nbsp" => Some(' '), - _ => entity - .strip_prefix("#x") - .or_else(|| entity.strip_prefix("#X")) - .and_then(|h| u32::from_str_radix(h, 16).ok()) - .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok())) - .and_then(char::from_u32), - }; - match c { - Some(c) => { - out.push(c); - rest = &after[semi + 1..]; - } - None => { - out.push('&'); - rest = &after[1..]; - } - } - } - out.push_str(rest); - out.replace(['\u{200B}', '\u{FEFF}'], "") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn lyrics_come_out_of_the_containers_without_headers_or_furniture() { - let html = r#"
Not lyrics
-
12 Contributors
Blinding Lights Lyrics
[Intro]
Yeah

[Verse 1]
I've been tryna call
I've been on my own & long enough
-
between
-
Maybe you can show me how to love, maybe
"#; - assert_eq!( - lyric_lines(html), - [ - "Yeah", - "", - "I've been tryna call", - "I've been on my own & long enough", - "Maybe you can show me how to love, maybe", - ] - ); - } - - #[test] - fn the_original_page_wins_over_a_translation() { - let found = serde_json::json!({"response": {"sections": [ - {"type": "top_hit", "hits": []}, - {"type": "song", "hits": [ - {"result": {"title": "Glue (Traducción al Español)", "artist_names": "Genius Traducciones al Español", "url": "https://genius.com/x-translation"}}, - {"result": {"title": "Glue", "artist_names": "Bicep", "url": "https://genius.com/Bicep-glue-lyrics"}}, - {"result": {"title": "Glue", "artist_names": "Bicep", "url": "https://evil.example/Bicep-glue-lyrics"}} - ]} - ]}}); - assert_eq!( - best_url(&found, "Glue", "Bicep").as_deref(), - Some("https://genius.com/Bicep-glue-lyrics") - ); - assert_eq!(best_url(&found, "Glue", "Someone Else"), None); - } -} diff --git a/crates/refryt/src/lyrics/mod.rs b/crates/refryt/src/lyrics/mod.rs index 259f4b4..7d72b26 100644 --- a/crates/refryt/src/lyrics/mod.rs +++ b/crates/refryt/src/lyrics/mod.rs @@ -11,7 +11,6 @@ //! pick per song. pub mod better_lyrics; -pub mod genius; pub mod kugou; pub mod lrc_red; pub mod lrclib; @@ -55,13 +54,11 @@ pub enum Source { Unison, /// YouTube Music's lyrics as the website shows them: plain text, no timing. YouTube, - /// Genius: plain text from the biggest catalogue there is. - Genius, } impl Source { /// Every source, in the default order. - pub const ALL: [Source; 8] = [ + pub const ALL: [Source; 7] = [ Source::BetterLyrics, Source::LrcRed, Source::YouTubeSynced, @@ -69,7 +66,6 @@ impl Source { Source::KuGou, Source::Unison, Source::YouTube, - Source::Genius, ]; /// The name kept in the settings file. @@ -81,7 +77,6 @@ impl Source { Source::KuGou => "kugou", Source::Unison => "unison", Source::YouTube => "youtube", - Source::Genius => "genius", Source::LrcRed => "lrc_red", } } @@ -98,7 +93,6 @@ impl Source { Source::KuGou => "KuGou", Source::Unison => "Unison", Source::YouTube => "YouTube Music, plain", - Source::Genius => "Genius", Source::LrcRed => "lrc.red", } } @@ -112,7 +106,6 @@ impl Source { Source::KuGou => "KuGou", Source::Unison => "Unison", Source::YouTube => "YouTube plain", - Source::Genius => "Genius", Source::LrcRed => "lrc.red", } } @@ -143,9 +136,6 @@ impl Source { "Lyrics added by listeners, for songs nobody licenses. Gets the title, artist, \ album and length." } - Source::Genius => { - "Plain text, no timing, from the biggest catalogue. Gets the title and artist." - } } } } @@ -397,7 +387,6 @@ pub async fn fetch( Source::LrcRed => lrc_red::lyrics(http, track).await, Source::KuGou => kugou::lyrics(http, track).await, Source::Unison => unison::lyrics(http, track).await, - Source::Genius => genius::lyrics(http, track).await, }?; if let Some(lyrics) = found.as_mut() { pair_romaji(lyrics); @@ -718,20 +707,11 @@ mod tests { (KuGou, true), (Unison, true), (YouTube, true), - (Genius, true), ] ); assert_eq!( asked(&saved), - vec![ - BetterLyrics, - LrcRed, - YouTubeSynced, - KuGou, - Unison, - YouTube, - Genius - ] + vec![BetterLyrics, LrcRed, YouTubeSynced, KuGou, Unison, YouTube] ); } diff --git a/crates/refryt/src/settings.rs b/crates/refryt/src/settings.rs index 6b5ed99..656bf7e 100644 --- a/crates/refryt/src/settings.rs +++ b/crates/refryt/src/settings.rs @@ -719,15 +719,7 @@ mod tests { use crate::lyrics::Source::*; assert_eq!( crate::lyrics::asked(&old.lyrics_sources), - vec![ - BetterLyrics, - LrcRed, - YouTubeSynced, - KuGou, - Unison, - YouTube, - Genius - ] + vec![BetterLyrics, LrcRed, YouTubeSynced, KuGou, Unison, YouTube] ); let json = serde_json::to_string(&old).unwrap(); assert!( From 659bc8d4407b4aa18e45c77f6f2e5f5becdf11a9 Mon Sep 17 00:00:00 2001 From: gridoe Date: Sun, 22 Nov 2026 01:24:22 +0200 Subject: [PATCH 10/12] feat: stats pages for an artist and a song Clicking an artist or song in Stats' top lists, or "Your stats" in a song's menu, opens a page of your listening to it, worked out from the play log: - plays, listening time, and when you first and last played it - its rank all-time and over 6 months, and the most plays in one day - for an artist: the songs of theirs you've played, your top 10, and your first song by them - plays by month (by year for a long history) The header plays the song or the artist's top songs. An artist's stats link to their artist page, and a song's to its artist's stats. The artist page gets a stats button beside Mix and Shuffle. The line under the name now names a top-10 rank, "Your #2 artist" or "Your #3 artist this month", and otherwise the plays ("N total plays by you"). That line is a point larger. --- crates/refryt/src/app.rs | 79 ++++- crates/refryt/src/backend.rs | 46 ++- crates/refryt/src/entity_stats.rs | 449 +++++++++++++++++++++++++++ crates/refryt/src/lib.rs | 1 + crates/refryt/src/listening_stats.rs | 162 +++++++++- crates/refryt/src/ui/artist.rs | 32 +- crates/refryt/src/ui/entity_stats.rs | 283 +++++++++++++++++ crates/refryt/src/ui/listening.rs | 18 +- crates/refryt/src/ui/mod.rs | 26 +- crates/refryt/src/widgets.rs | 10 +- 10 files changed, 1055 insertions(+), 51 deletions(-) create mode 100644 crates/refryt/src/entity_stats.rs create mode 100644 crates/refryt/src/ui/entity_stats.rs diff --git a/crates/refryt/src/app.rs b/crates/refryt/src/app.rs index 26eeb93..b4f527f 100644 --- a/crates/refryt/src/app.rs +++ b/crates/refryt/src/app.rs @@ -527,6 +527,10 @@ pub enum Route { Stats, /// One of Stats' top lists, past the few rows Stats shows. StatsTop(crate::listening_stats::TopList), + /// One artist's listening, by their lowercased name (`entity_stats::EntityKey`). + StatsArtist(String), + /// One song's listening, by its video id. + StatsSong(String), Library, Settings, Artist(String), @@ -569,6 +573,8 @@ impl Route { Some(("album", id)) => Some(Route::Album(id.to_owned())), Some(("playlist", id)) => Some(Route::Playlist(id.to_owned())), Some(("homeshelf", title)) => Some(Route::HomeShelf(title.to_owned())), + Some(("artist-stats", name)) => Some(Route::StatsArtist(name.to_lowercase())), + Some(("song-stats", id)) => Some(Route::StatsSong(id.to_owned())), _ => None, }, } @@ -1500,6 +1506,11 @@ pub struct App { /// What the Stats page shows. An older report stays up while a newer one is added up. pub(crate) stats_report: Option>, pub(crate) stats_error: Option, + /// What an artist's or song's stats page shows, kept while a newer one is added up. + pub(crate) entity_report: Option>, + pub(crate) entity_error: Option, + /// The report last asked for, and at which `stats_epoch`: a newer epoch asks again. + entity_requested: Option<(crate::entity_stats::EntityKey, u64)>, /// Which report is wanted: bumped by a new range and a new play. stats_epoch: u64, /// The last report asked for. @@ -1507,7 +1518,7 @@ pub struct App { /// Settings' Delete stats has been pressed once, and is asking to be sure. pub(crate) stats_delete_armed: bool, /// An artist's id and how many times you've played them, for their page. - pub(crate) artist_plays: Option<(String, u64)>, + pub(crate) artist_plays: Option<(String, crate::listening_stats::ArtistHighlight)>, /// Songs being looked up for the Stats page. looking_up_songs: bool, /// Songs already asked about this run, so one YouTube won't answer isn't asked forever. @@ -2218,6 +2229,9 @@ impl App { stats_scope: Default::default(), stats_report: None, stats_error: None, + entity_report: None, + entity_error: None, + entity_requested: None, stats_epoch: 0, stats_requested: None, stats_delete_armed: false, @@ -4196,6 +4210,12 @@ impl App { Route::Moods => self.load_moods(), Route::History => self.load_history(), Route::Stats | Route::StatsTop(_) => self.load_stats(), + Route::StatsArtist(name) => { + self.load_entity_stats(crate::entity_stats::EntityKey::Artist(name)); + } + Route::StatsSong(id) => { + self.load_entity_stats(crate::entity_stats::EntityKey::Song(id)) + } Route::Search | Route::Settings => {} } } @@ -4588,6 +4608,10 @@ impl App { self.stats_error = None; self.stats_epoch += 1; } + Route::StatsArtist(_) | Route::StatsSong(_) => { + self.entity_error = None; + self.entity_requested = None; + } Route::Artist(_) | Route::ArtistLiked(_) => { self.artist_for = None; self.artist_error = None; @@ -6049,6 +6073,18 @@ impl App { self.stats_error = Some(error); } Event::StatsLoaded { .. } | Event::StatsFailed { .. } => {} + Event::EntityStatsLoaded { report, epoch } + if self.entity_requested.as_ref() == Some(&(report.key.clone(), epoch)) => + { + self.entity_report = Some(report); + self.entity_error = None; + } + Event::EntityStatsFailed { key, error, epoch } + if self.entity_requested.as_ref() == Some(&(key.clone(), epoch)) => + { + self.entity_error = Some(error); + } + Event::EntityStatsLoaded { .. } | Event::EntityStatsFailed { .. } => {} Event::TakeoutImported { result } => self.takeout_imported(result), Event::HistoryChecked { found, ok } => { self.history_checking = false; @@ -6058,8 +6094,8 @@ impl App { self.log_play(Some(play)); } } - Event::ArtistPlaysCounted { id, plays } => { - self.artist_plays = Some((id, plays)); + Event::ArtistPlaysCounted { id, highlight } => { + self.artist_plays = Some((id, highlight)); } Event::PlaylistCreated { title } => { self.toast(&format!("Created “{title}”")); @@ -7477,6 +7513,7 @@ impl App { } RowAction::GoToAlbum(id) => self.navigate(Route::Album(id)), RowAction::GoToArtist(id) => self.navigate(Route::Artist(id)), + RowAction::SongStats(id) => self.navigate(Route::StatsSong(id)), RowAction::CopyLink(id) => { self.backend.copy_text(crate::model::track_url(&id)); self.toast("Link copied"); @@ -7894,6 +7931,26 @@ impl App { .load_listening_stats(self.stats_range, self.stats_scope, self.stats_epoch); } + /// Ask for an artist's or song's report, unless it is the one already asked for. Another + /// artist's report is dropped at once, so their page never shows someone else's numbers. + fn load_entity_stats(&mut self, key: crate::entity_stats::EntityKey) { + let wanted = (key, self.stats_epoch); + if self.entity_requested.as_ref() == Some(&wanted) { + return; + } + if self + .entity_report + .as_ref() + .is_some_and(|r| r.key != wanted.0) + { + self.entity_report = None; + } + self.entity_error = None; + self.backend + .load_entity_stats(wanted.0.clone(), self.stats_scope, wanted.1); + self.entity_requested = Some(wanted); + } + /// Show another range on the Stats page. pub(crate) fn set_stats_range(&mut self, range: crate::listening_stats::StatsRange) { if self.stats_range != range { @@ -9299,6 +9356,9 @@ impl eframe::App for App { Route::History => ui::history::page(self, ui), Route::Stats => ui::listening::page(self, ui), Route::StatsTop(list) => ui::listening::top_page(self, ui, list), + Route::StatsArtist(_) | Route::StatsSong(_) => { + ui::entity_stats::page(self, ui); + } Route::Home => ui::home::page(self, ui), Route::Library => ui::library::page(self, ui), Route::Settings => ui::settings::page(self, ui), @@ -9463,6 +9523,19 @@ impl eframe::App for App { #[cfg(test)] mod tests { + #[test] + fn stats_pages_parse_from_the_command_line() { + use super::Route; + assert_eq!( + Route::parse("artist-stats:Ado"), + Some(Route::StatsArtist("ado".to_owned())) + ); + assert_eq!( + Route::parse("song-stats:dQw4w9WgXcQ"), + Some(Route::StatsSong("dQw4w9WgXcQ".to_owned())) + ); + } + /// A window restored fullscreen is taken out of it and then resized — in that order, and the /// resize only once the window reports it is out. The fullscreen player's own fullscreen is /// never touched, nor is a window that was never fullscreen, and a fullscreen that arrives diff --git a/crates/refryt/src/backend.rs b/crates/refryt/src/backend.rs index e07c7a1..4a84230 100644 --- a/crates/refryt/src/backend.rs +++ b/crates/refryt/src/backend.rs @@ -266,9 +266,18 @@ pub enum Event { error: String, epoch: u64, }, + EntityStatsLoaded { + report: Arc, + epoch: u64, + }, + EntityStatsFailed { + key: crate::entity_stats::EntityKey, + error: String, + epoch: u64, + }, ArtistPlaysCounted { id: String, - plays: u64, + highlight: crate::listening_stats::ArtistHighlight, }, TakeoutImported { result: Result, @@ -1703,6 +1712,30 @@ impl Backend { }); } + /// Add up one artist's or song's plays for their stats page, off the UI thread. + pub fn load_entity_stats( + &self, + key: crate::entity_stats::EntityKey, + scope: crate::listening_stats::StatsScope, + epoch: u64, + ) { + let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); + self.rt.spawn_blocking(move || { + let event = match crate::entity_stats::load(key.clone(), scope) { + Ok(report) => Event::EntityStatsLoaded { + report: Arc::new(report), + epoch, + }, + Err(e) => Event::EntityStatsFailed { + key, + error: format!("{e:#}"), + epoch, + }, + }; + Self::emit(&tx, &ctx, event); + }); + } + /// Look up songs an import only knew the id and title of, and save what YouTube says, a few /// at a time. A song YouTube won't answer for is left as it is. pub fn look_up_songs(&self, ids: Vec) { @@ -1752,11 +1785,14 @@ impl Backend { /// How many times an artist has been played, for their page. pub fn count_artist_plays(&self, id: String) { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); - self.rt - .spawn_blocking(move || match crate::listening_stats::artist_plays(&id) { - Ok(plays) => Self::emit(&tx, &ctx, Event::ArtistPlaysCounted { id, plays }), + self.rt.spawn_blocking( + move || match crate::listening_stats::artist_highlight(&id) { + Ok(highlight) => { + Self::emit(&tx, &ctx, Event::ArtistPlaysCounted { id, highlight }); + } Err(e) => debug!(error = %format!("{e:#}"), "could not read the play log"), - }); + }, + ); } /// What you played, in dated shelves. Signed in only — the page gates, not the call. diff --git a/crates/refryt/src/entity_stats.rs b/crates/refryt/src/entity_stats.rs new file mode 100644 index 0000000..24a5c47 --- /dev/null +++ b/crates/refryt/src/entity_stats.rs @@ -0,0 +1,449 @@ +//! One artist's or one song's listening, for their stats page: what the play log says about +//! them all-time, and where they stand against everything else in it. +//! +//! One pass over the log, on a background thread, like the Stats page's report. Ranking needs +//! every artist's (or song's) play count, so the same pass counts those too and keeps nothing +//! else of them. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use anyhow::Result; +use chrono::{DateTime, Local, NaiveDate, TimeZone}; + +use crate::listening_stats::{Bar, StatsScope, artist_key, plays_label, span_bars}; +use crate::model::{Entry, Track}; +use crate::play_log::{self, Play, SongDetails}; + +/// How far back "recent" goes for the second rank: the 6 months the Stats page means. +const RECENT_SECS: i64 = 183 * 86_400; +/// How many of an artist's songs their page lists. +pub const ARTIST_TOP_SONGS: usize = 10; + +/// What a stats page is about. An artist goes by their lowercased name, as the Stats page +/// counts them: an import knows an artist only by name. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum EntityKey { + Artist(String), + Song(String), +} + +impl EntityKey { + pub fn artist(name: &str) -> Self { + Self::Artist(name.to_lowercase()) + } + + fn matches(&self, play: &Play) -> bool { + match self { + Self::Artist(key) => play.artists.iter().any(|a| artist_key(a) == *key), + Self::Song(id) => play.video_id == *id, + } + } +} + +/// Place among everything played: 1 for the most played. Ties share a place. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rank { + pub place: u64, + pub of: u64, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct EntityReport { + pub key: EntityKey, + /// The artist's name or the song's title, as the latest play gave it. + pub name: String, + /// The artist's YouTube Music id, once any play gave it. + pub artist_id: Option, + /// The song, playable: from its latest play. + pub track: Option, + /// The song's cover, or the cover of the artist's most played song. + pub art: Option>, + pub plays: u64, + pub seconds: u64, + /// `seconds` is partly an estimate, from an import or the account's history. + pub seconds_estimated: bool, + pub first: Option, + pub last: Option, + pub rank: Option, + /// Over the last 6 months; none when not played in them. + pub rank_recent: Option, + /// Different songs played: the artist's, or 1 for a song. + pub songs: u64, + /// The day with the most plays, and how many. + pub best_day: Option<(NaiveDate, u32)>, + /// The artist's most played songs, up to [`ARTIST_TOP_SONGS`], with their plays. + pub top_songs: Vec, + /// The artist's first song played, and when. + pub first_song: Option<(Track, i64)>, + /// Plays by month from the first one, or by year for a long history. + pub bars: Vec, +} + +struct Tally { + plays: u64, + last: i64, + play: Play, +} + +/// Counts for one kind of thing (artists or songs), to rank against. +#[derive(Default)] +struct Board { + all: HashMap, + recent: HashMap, +} + +impl Board { + fn rank(map: &HashMap, key: &str) -> Option { + let mine = *map.get(key).filter(|n| **n > 0)?; + Some(Rank { + place: 1 + map.values().filter(|n| **n > mine).count() as u64, + of: map.len() as u64, + }) + } +} + +struct Builder { + key: EntityKey, + now: DateTime, + details: HashMap, + scope: StatsScope, + board: Board, + name: (i64, String), + artist_id: Option, + plays: u64, + seconds: u64, + estimated: bool, + first: Option<(i64, Play)>, + last: Option, + songs: HashMap, + days: HashMap, +} + +impl Builder { + fn new(key: EntityKey, now: DateTime, details: HashMap) -> Self { + Self { + key, + now, + details, + scope: StatsScope::Everywhere, + board: Board::default(), + name: (i64::MIN, String::new()), + artist_id: None, + plays: 0, + seconds: 0, + estimated: false, + first: None, + last: None, + songs: HashMap::new(), + days: HashMap::new(), + } + } + + fn add(&mut self, mut play: Play) { + if !self.scope.counts(&play) { + return; + } + if let Some(details) = self.details.get(&play.video_id) { + play.apply(details); + } + let recent = play.at >= self.now.timestamp() - RECENT_SECS; + // Every artist or song counts towards the ranking; an artist once per play. + let keys: Vec = match &self.key { + EntityKey::Artist(_) => { + let names: HashSet = play.artists.iter().map(artist_key).collect(); + names.into_iter().collect() + } + EntityKey::Song(_) => vec![play.video_id.clone()], + }; + for key in keys { + if recent { + *self.board.recent.entry(key.clone()).or_default() += 1; + } + *self.board.all.entry(key).or_default() += 1; + } + if !self.key.matches(&play) { + return; + } + self.plays += 1; + self.seconds += play.listened; + self.estimated |= play.source != play_log::Source::App; + let tz = self.now.timezone(); + if let Some(date) = tz + .timestamp_opt(play.at, 0) + .earliest() + .map(|at| at.date_naive()) + { + *self.days.entry(date).or_default() += 1; + } + self.last = Some(self.last.map_or(play.at, |last| last.max(play.at))); + match &self.key { + EntityKey::Artist(key) => { + if let Some(artist) = play.artists.iter().find(|a| artist_key(a) == *key) { + if play.at >= self.name.0 { + self.name = (play.at, artist.name.clone()); + } + if artist.id.is_some() { + self.artist_id.clone_from(&artist.id); + } + } + } + EntityKey::Song(_) => { + if play.at >= self.name.0 { + self.name = (play.at, play.title.clone()); + } + } + } + if self.first.as_ref().is_none_or(|(at, _)| play.at < *at) { + self.first = Some((play.at, play.clone())); + } + match self.songs.get_mut(&play.video_id) { + Some(tally) => { + tally.plays += 1; + if play.at >= tally.last { + tally.last = play.at; + tally.play = play; + } + } + None => { + self.songs.insert( + play.video_id.clone(), + Tally { + plays: 1, + last: play.at, + play, + }, + ); + } + } + } + + fn finish(self) -> EntityReport { + let board_key = match &self.key { + EntityKey::Artist(key) | EntityKey::Song(key) => key.clone(), + }; + let mut songs: Vec = self.songs.into_values().collect(); + songs.sort_unstable_by(|a, b| b.plays.cmp(&a.plays).then(b.last.cmp(&a.last))); + let art = songs + .iter() + .find_map(|t| t.play.thumbnail.as_deref()) + .map(Arc::from); + let track = match self.key { + EntityKey::Song(_) => songs.first().map(|t| t.play.track()), + EntityKey::Artist(_) => None, + }; + let top_songs = match self.key { + EntityKey::Artist(_) => songs + .iter() + .take(ARTIST_TOP_SONGS) + .map(|tally| { + let mut track = tally.play.track(); + track.plays = Some(plays_label(tally.plays)); + if track.wide { + Entry::Video(track) + } else { + Entry::Song(track) + } + }) + .collect(), + EntityKey::Song(_) => Vec::new(), + }; + let best_day = self + .days + .iter() + .max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0))) + .map(|(date, plays)| (*date, *plays)); + let today = self.now.date_naive(); + let bars = self + .days + .keys() + .min() + .map(|first| span_bars(*first, today, &self.days)) + .unwrap_or_default(); + let first_song = match self.key { + EntityKey::Artist(_) => self.first.as_ref().map(|(at, play)| (play.track(), *at)), + EntityKey::Song(_) => None, + }; + EntityReport { + rank: Board::rank(&self.board.all, &board_key), + rank_recent: Board::rank(&self.board.recent, &board_key), + key: self.key, + name: self.name.1, + artist_id: self.artist_id, + track, + art, + plays: self.plays, + seconds: self.seconds, + seconds_estimated: self.estimated, + first: self.first.map(|(at, _)| at), + last: self.last, + songs: songs.len() as u64, + best_day, + top_songs, + first_song, + bars, + } + } +} + +/// An artist's or a song's report, from the log on disk, counting the plays `scope` counts. +/// Slow enough to belong off the UI thread. +pub fn load(key: EntityKey, scope: StatsScope) -> Result { + let mut builder = Builder::new(key, Local::now(), play_log::load_details()); + builder.scope = scope; + play_log::for_each(|play| builder.add(play))?; + Ok(builder.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::play_log::{LoggedArtist, Source}; + use chrono::{FixedOffset, Timelike}; + + /// A Wednesday afternoon, two hours ahead of UTC. + fn now() -> DateTime { + FixedOffset::east_opt(2 * 3600) + .unwrap() + .with_ymd_and_hms(2026, 3, 18, 15, 0, 0) + .unwrap() + } + + /// `days_back` days before `now()`, at `hour` local time. + fn at(days_back: i64, hour: u32) -> i64 { + let day = now() - chrono::Duration::days(days_back); + day.with_hour(hour).unwrap().timestamp() + } + + fn play(song: &str, artists: &[&str], at: i64) -> Play { + Play { + video_id: song.to_owned(), + title: format!("{song} title"), + artists: artists + .iter() + .map(|a| LoggedArtist { + name: (*a).to_owned(), + id: Some(format!("id-{a}")), + }) + .collect(), + album: None, + album_id: None, + duration: Some(200), + thumbnail: Some(format!("art-{song}")), + wide: false, + local: false, + at, + listened: 100, + source: Source::App, + } + } + + fn report(key: EntityKey, plays: Vec) -> EntityReport { + let mut builder = Builder::new(key, now(), HashMap::new()); + for p in plays { + builder.add(p); + } + builder.finish() + } + + fn log() -> Vec { + vec![ + play("a1", &["Ado"], at(400, 9)), + play("a2", &["Ado", "Eve"], at(30, 22)), + play("a2", &["Ado", "Eve"], at(30, 23)), + play("a2", &["Ado", "Eve"], at(2, 22)), + play("e1", &["Eve"], at(1, 8)), + play("e1", &["Eve"], at(1, 9)), + play("e1", &["Eve"], at(1, 10)), + play("e1", &["Eve"], at(1, 11)), + play("y1", &["YOASOBI"], at(300, 12)), + ] + } + + #[test] + fn an_artist_adds_up_across_their_songs_and_features() { + let r = report(EntityKey::artist("ADO"), log()); + assert_eq!(r.name, "Ado"); + assert_eq!(r.artist_id.as_deref(), Some("id-Ado")); + assert_eq!((r.plays, r.seconds, r.songs), (4, 400, 2)); + assert_eq!((r.first, r.last), (Some(at(400, 9)), Some(at(2, 22)))); + assert_eq!( + r.art.as_deref(), + Some("art-a2"), + "the most played song's cover" + ); + let titles: Vec<&str> = r.top_songs.iter().map(|e| e.title()).collect(); + assert_eq!(titles, ["a2 title", "a1 title"]); + assert_eq!( + r.first_song.as_ref().map(|(t, _)| t.video_id.as_str()), + Some("a1") + ); + assert!(r.track.is_none()); + } + + #[test] + fn rank_is_against_every_artist_and_ties_share_a_place() { + let r = report(EntityKey::artist("eve"), log()); + // Eve 7, Ado 4, YOASOBI 1. + assert_eq!(r.rank, Some(Rank { place: 1, of: 3 })); + let ado = report(EntityKey::artist("ado"), log()); + assert_eq!(ado.rank, Some(Rank { place: 2, of: 3 })); + // In the last 6 months: Eve 7, Ado 3; YOASOBI's play is older. + assert_eq!(ado.rank_recent, Some(Rank { place: 2, of: 2 })); + let yoasobi = report(EntityKey::artist("yoasobi"), log()); + assert_eq!(yoasobi.rank_recent, None); + + let tie = vec![play("x", &["One"], at(1, 9)), play("y", &["Two"], at(1, 9))]; + let r = report(EntityKey::artist("two"), tie); + assert_eq!(r.rank, Some(Rank { place: 1, of: 2 })); + } + + #[test] + fn a_song_has_its_own_totals_and_rank() { + let r = report(EntityKey::Song("e1".into()), log()); + assert_eq!(r.name, "e1 title"); + assert_eq!((r.plays, r.songs), (4, 1)); + assert_eq!(r.rank, Some(Rank { place: 1, of: 4 })); + assert_eq!(r.track.as_ref().map(|t| t.video_id.as_str()), Some("e1")); + assert!(r.top_songs.is_empty() && r.first_song.is_none()); + assert_eq!(r.best_day.map(|(_, n)| n), Some(4)); + } + + #[test] + fn the_best_day_is_a_local_date() { + let r = report(EntityKey::artist("eve"), log()); + assert_eq!( + r.best_day, + Some(((now() - chrono::Duration::days(1)).date_naive(), 4)) + ); + } + + #[test] + fn a_long_history_charts_by_month_from_the_first_play() { + let r = report(EntityKey::artist("ado"), log()); + assert_eq!(r.bars.len(), 14, "Feb 2025 to Mar 2026"); + assert_eq!(r.bars.iter().map(|b| b.plays).sum::(), 4); + } + + #[test] + fn nothing_played_leaves_an_empty_report() { + let r = report(EntityKey::artist("nobody"), log()); + assert_eq!((r.plays, r.rank, r.first), (0, None, None)); + assert!(r.bars.is_empty() && r.name.is_empty()); + } + + #[test] + fn the_scope_leaves_out_plays_from_elsewhere() { + let mut elsewhere = play("e1", &["Eve"], at(3, 9)); + elsewhere.source = Source::Takeout; + let mut builder = Builder::new(EntityKey::artist("eve"), now(), HashMap::new()); + builder.scope = StatsScope::Here; + builder.add(elsewhere.clone()); + builder.add(play("e1", &["Eve"], at(1, 9))); + let r = builder.finish(); + assert_eq!(r.plays, 1); + assert!(!r.seconds_estimated); + let everywhere = report(EntityKey::artist("eve"), vec![elsewhere]); + assert!(everywhere.seconds_estimated); + } +} diff --git a/crates/refryt/src/lib.rs b/crates/refryt/src/lib.rs index 27e74e9..200d2d5 100644 --- a/crates/refryt/src/lib.rs +++ b/crates/refryt/src/lib.rs @@ -26,6 +26,7 @@ pub mod crash; pub mod discord; pub mod downloads; pub mod emoji; +pub mod entity_stats; pub mod flatpak; pub mod history_poll; pub mod icons; diff --git a/crates/refryt/src/listening_stats.rs b/crates/refryt/src/listening_stats.rs index fb6f46e..acc6b9a 100644 --- a/crates/refryt/src/listening_stats.rs +++ b/crates/refryt/src/listening_stats.rs @@ -39,7 +39,7 @@ impl StatsScope { } } - fn counts(self, play: &Play) -> bool { + pub(crate) fn counts(self, play: &Play) -> bool { self == StatsScope::Everywhere || play.source == play_log::Source::App } } @@ -164,10 +164,26 @@ impl Period { /// By name, not id: an import knows an artist only by their name, and they are the same artist /// as the one a play here knows by id. -fn artist_key(artist: &play_log::LoggedArtist) -> String { +pub(crate) fn artist_key(artist: &play_log::LoggedArtist) -> String { artist.name.to_lowercase() } +/// The bars of plays over time for a span starting at `since`: months, or years once there +/// are too many months to show. +pub(crate) fn span_bars( + since: NaiveDate, + today: NaiveDate, + days: &HashMap, +) -> Vec { + let months = i64::from(today.year() - since.year()) * 12 + i64::from(today.month()) + - i64::from(since.month()); + if months < MAX_MONTH_BARS { + month_bars(since, today, days) + } else { + year_bars(since, today, days) + } +} + /// One bar of plays over time. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Bar { @@ -508,15 +524,7 @@ fn bars( plays: plays(d, (d + Days::new(6)).min(today)), }) .collect(), - StatsRange::Year | StatsRange::All => { - let months = i64::from(today.year() - since.year()) * 12 + i64::from(today.month()) - - i64::from(since.month()); - if months < MAX_MONTH_BARS { - month_bars(since, today, days) - } else { - year_bars(since, today, days) - } - } + StatsRange::Year | StatsRange::All => span_bars(since, today, days), } } @@ -573,27 +581,72 @@ pub fn load(range: StatsRange, scope: StatsScope) -> Result { Ok(builder.finish()) } -/// How many times an artist has been played, for their page. +/// What an artist's page says about your listening to them: their plays, and where they rank +/// among your artists all-time and this calendar month. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ArtistHighlight { + pub plays: u64, + pub rank: Option, + pub rank_month: Option, +} + +impl ArtistHighlight { + /// A rank only reads as a highlight this high up. + const NOTABLE: u64 = 10; + + /// The line after their audience: a top-10 rank, this month's when it is the higher one, + /// or else their plays. None when you've never played them. + pub fn line(&self) -> Option { + if self.plays == 0 { + return None; + } + let all = self.rank.filter(|r| *r <= Self::NOTABLE); + let month = self.rank_month.filter(|r| *r <= Self::NOTABLE); + Some(match (all, month) { + (all, Some(month)) if all.is_none_or(|all| month < all) => { + format!("Your #{month} artist this month") + } + (Some(all), _) => format!("Your #{all} artist"), + _ if self.plays == 1 => "1 total play by you".to_owned(), + _ => format!("{} total plays by you", self.plays), + }) + } +} + +/// How an artist stands in your listening, for their page. /// /// By their name once a play with this id gives it, since an import knows them only by name. -pub fn artist_plays(id: &str) -> Result { +pub fn artist_highlight(id: &str) -> Result { let details = play_log::load_details(); - let mut count = ArtistCount::default(); + let now = Local::now(); + let today = now.date_naive(); + let month_start = today + .with_day(1) + .and_then(|d| d.and_hms_opt(0, 0, 0)) + .and_then(|at| at.and_local_timezone(Local).earliest()) + .map_or(now.timestamp(), |at| at.timestamp()); + let mut count = ArtistCount { + month_start, + ..ArtistCount::default() + }; play_log::for_each(|mut play| { if let Some(details) = details.get(&play.video_id) { play.apply(details); } count.add(id, &play); })?; - Ok(count.total()) + Ok(count.highlight()) } /// Plays by name, because an import names an artist without giving its id: one looked-up song -/// or play here is enough to tie the id to the name. +/// or play here is enough to tie the id to the name. Every artist is counted, all-time and since +/// `month_start`, which is what ranking them needs. #[derive(Default)] struct ArtistCount { name: Option, by_name: HashMap, + month_start: i64, + this_month: HashMap, } impl ArtistCount { @@ -603,6 +656,9 @@ impl ArtistCount { if artist.id.as_deref() == Some(id) { self.name.get_or_insert_with(|| key.clone()); } + if play.at >= self.month_start { + *self.this_month.entry(key.clone()).or_default() += 1; + } *self.by_name.entry(key).or_default() += 1; } } @@ -613,6 +669,18 @@ impl ArtistCount { .and_then(|name| self.by_name.get(name).copied()) .unwrap_or(0) } + + fn highlight(&self) -> ArtistHighlight { + let rank = |counts: &HashMap| { + 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/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/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/mod.rs b/crates/refryt/src/ui/mod.rs index 200c942..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; @@ -426,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 { @@ -2194,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. @@ -2396,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; @@ -3005,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( @@ -3019,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 = { @@ -3058,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/widgets.rs b/crates/refryt/src/widgets.rs index 7a2d3b4..c4886ea 100644 --- a/crates/refryt/src/widgets.rs +++ b/crates/refryt/src/widgets.rs @@ -3214,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() { @@ -3230,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() From 1e01712d0c3149c7116645f20e35bd8c0dbcfb9b Mon Sep 17 00:00:00 2001 From: gridoe Date: Sun, 22 Nov 2026 11:16:39 +0200 Subject: [PATCH 11/12] fix: the GTK theme helper no longer leaves a crash report when the app quits first The helper that reads the GTK colours is a second copy of refryt. If the app quit while GTK was still starting in it, the helper's println! hit a closed pipe and panicked, and since the crash hook was already installed, the next launch offered a crash report as if refryt had crashed. The helper now writes its answer without panicking, and starts before the log and the crash hook, so its failing only costs the GTK theme. --- crates/refryt/src/main.rs | 25 ++++++++++++++----------- crates/refryt/src/theme/system.rs | 8 ++++---- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/refryt/src/main.rs b/crates/refryt/src/main.rs index fdd4f51..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"); @@ -137,17 +151,6 @@ fn main() -> eframe::Result { #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] let autostart = false; - // 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. - #[cfg(target_os = "linux")] - if args.iter().any(|a| a == refryt::theme::system::GTK_ARG) { - std::process::exit(if refryt::theme::system::gtk_child() { - 0 - } else { - 1 - }); - } - // The child half of the in-app sign-in window: `webview_login::capture` starts this same // binary with `--sign-in-window `, because tao's event loop cannot be created beside // eframe's winit one in the same process (it faults natively on Windows). Handled here — diff --git a/crates/refryt/src/theme/system.rs b/crates/refryt/src/theme/system.rs index d49655d..3ea2c6b 100644 --- a/crates/refryt/src/theme/system.rs +++ b/crates/refryt/src/theme/system.rs @@ -338,11 +338,11 @@ pub fn gtk_child() -> bool { // 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) => { - println!("{line}"); - true - } + Ok(line) => writeln!(std::io::stdout(), "{line}").is_ok(), Err(_) => false, } } From 72a969f03fee869856c6e09ea20b4b3db3cea4da Mon Sep 17 00:00:00 2001 From: gridoe Date: Sun, 22 Nov 2026 13:07:28 +0200 Subject: [PATCH 12/12] docs: a warmer README, brought up to date with the themes, lyrics and stats The README read flat. It now speaks to the reader, lists the stats pages and lyrics sources, counts 29 themes plus GTK and Qt, and says more about installing: AppImage managers, which builds update themselves, SmartScreen's "Run anyway", and that the AUR packages may lag behind. --- README.md | 64 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 4eee4e6..a1e1081 100644 --- a/README.md +++ b/README.md @@ -21,11 +21,13 @@

-refryt is a desktop client for YouTube Music, written in Rust. It doesn't embed a browser. Playback goes through mpv, and the app talks to YouTube through the same internal API the website uses. +refryt is a native YouTube Music app for your desktop, written in Rust. There's no browser hiding inside it: music plays through mpv, and the app talks to YouTube the same way the website does. It opens fast and stays light. -- Home, Explore, search, a library, synced lyrics, an editable queue and music videos. -- 23 themes, with optional window transparency and background blur. -- Memory use is typically between 100 and 300 MB, depending on the session. +- Everything you'd expect: Home, Explore, search, your library, an editable queue and music videos. +- Synced lyrics from seven sources, picked for you automatically, and romanised for Japanese, Korean and Chinese songs. +- Your listening stats, with a page for every artist and song you play. +- 29 themes, plus GTK and Qt on Linux to match your desktop, with optional transparency and background blur. +- Usually 100 to 300 MB of memory, depending on what you're doing. - Packages for Linux (AppImage and Flatpak), Windows (installer, MSI and zip, plus an ARM64 build) and macOS (Apple Silicon DMG). ## Screenshots @@ -84,7 +86,7 @@ refryt is a desktop client for YouTube Music, written in Rust. It doesn't embed ## Install -Downloads are on the [releases page](https://github.com/gridoe/refryt/releases), with a `SHA256SUMS` file to check them against. +Grab the latest build from the [releases page](https://github.com/gridoe/refryt/releases). Each release has a `SHA256SUMS` file if you want to check your download. ### Linux @@ -94,15 +96,15 @@ Downloads are on the [releases page](https://github.com/gridoe/refryt/releases), flatpak install --user https://gridoe.github.io/refryt/refryt.flatpakref ``` -Update it with `flatpak update`. The browser import and Launch on startup are not available inside the sandbox. +`flatpak update` keeps it up to date. Inside the sandbox you'll miss two things: the browser import and Launch on startup. -**AppImage:** download `refryt--x86_64.AppImage`, make it executable with `chmod +x` and run it. +**AppImage:** download `refryt--x86_64.AppImage`, make it executable with `chmod +x`, and you're ready to go. You can also install via an AppImage manager such as Gear Lever or Shelly. Either way, it updates itself in one click when a new release is out. -**AUR:** `refryt-bin` (the AppImage) or `refryt-git` (latest git, built from source), both unofficial (maintained by [9M2PJU](https://aur.archlinux.org/account/9M2PJU)), for example `yay -S refryt-bin`. +**AUR:** on Arch, `yay -S refryt-bin` installs the AppImage, and `refryt-git` builds the latest code from source. Both are unofficial packages, kindly maintained by [9M2PJU](https://github.com/9M2PJU), and they may lag a little behind the latest release. ### Windows -**Installer:** `refryt--windows-x86_64-setup.exe`, or the `.msi` for silent installs (`msiexec /i /qn`). Both are unsigned, so SmartScreen warns on the first run. +**Installer:** run `refryt--windows-x86_64-setup.exe`, or use the `.msi` for silent installs (`msiexec /i /qn`). Both update themselves in one click when a new release is out. Neither is signed yet, so SmartScreen will warn you the first time; choose "More info", then "Run anyway". **Scoop** @@ -111,9 +113,9 @@ scoop bucket add gridoe https://github.com/gridoe/scoop-bucket scoop install gridoe/refryt ``` -**Zip:** extract the whole folder and run `refryt.exe`. +**Zip:** extract the whole folder and run `refryt.exe`. Nothing gets installed. -The ARM64 `.msi` and `.zip` are native builds that have not been tested on ARM hardware. +There are native ARM64 builds too (`.msi` and `.zip`). They haven't been tried on real ARM hardware yet, so feedback is very welcome. ### macOS @@ -123,13 +125,13 @@ Apple Silicon only. **Disk image:** open `refryt--macos-arm64.dmg` and drag Refryt to Applications. -The app is not notarised, so run `xattr -cr /Applications/Refryt.app` once before the first launch. +The app isn't notarised by Apple, so macOS will refuse to open it at first. Run `xattr -cr /Applications/Refryt.app` once and it opens normally from then on. ### Updates -refryt checks for a new release when it starts; the check can be turned off in Settings, About. The installer, the MSI and the AppImage update themselves with one click. The others show the command to run (`flatpak update`, `brew upgrade --cask refryt`, `scoop update refryt`) or a link to the release. +refryt looks for a new release when it starts, and tells you when there is one (you can turn this off in Settings, About). The installer, the MSI and the AppImage update themselves in one click. For the others, it shows you the command to run (`flatpak update`, `brew upgrade --cask refryt`, `scoop update refryt`) or links to the release. -To build from source, see [Build from source](#build-from-source). +Prefer to build it yourself? See [Build from source](#build-from-source). ## Disclaimer @@ -142,17 +144,19 @@ To build from source, see [Build from source](#build-from-source). ## Features -- Search by songs, albums or artists, each asked from YouTube directly. -- Playlists you can create, rename and reorder by dragging, with YouTube's suggestions on your own. -- Liked songs marked everywhere, and a tile on each artist page with the ones you liked. -- Home's sections in the order you choose. -- A now-playing view with the cover, synced lyrics and a queue drawer (F to open, F11 to open it fullscreen, Esc to close). -- Local folders, browsable like a file tree, and any folder as a playlist. -- Downloads with Premium, to `~/Music/refryt` with tags and cover art, and an offline mode that points to them. -- Audio quality, volume normalisation and autoplay when the queue runs out. -- Brand account switching from the account menu. -- Tray icon, start on boot, media keys, system media controls, and optional Discord Rich Presence. -- Casting from the YouTube Music app on a phone, with the phone as the remote. +- Search songs, albums or artists, straight from YouTube. +- Make playlists, rename them and drag songs around, with YouTube's suggestions for your own playlists. +- Your liked songs are marked everywhere, and each artist page has a tile with the ones you liked. +- Put Home's sections in whatever order you like. +- A now-playing view with the cover, synced lyrics and the queue (F opens it, F11 goes fullscreen, Esc closes it). +- Lyrics from BetterLyrics, lrc.red, LRCLIB, KuGou, Unison and YouTube Music. You choose which to use and in what order, and can switch sources for any song. +- Stats on what you listen to: top songs and artists, plays over time, and a page for every artist and song with your ranks, first plays and best days. +- Your local music folders, browsable like a file tree, and any folder can be played as a playlist. +- With Premium, download songs to `~/Music/refryt` with tags and cover art, and listen offline. +- Audio quality, volume normalisation, and autoplay that keeps the music going when the queue ends. +- Switch between brand accounts from the account menu. +- Tray icon, start on boot, media keys, system media controls and optional Discord Rich Presence. +- Cast from the YouTube Music app on your phone, and use the phone as the remote. - Resizable sidebars; the left one folds down to an icon rail. ## Using refryt @@ -177,7 +181,7 @@ On macOS, Ctrl is Cmd. One click selects a song and two play it, as in Spotify; ### Themes -The 23 themes are CSS files in the config folder's `themes` folder, and can be edited or added ([docs/THEMES.md](docs/THEMES.md)). Settings has window transparency and background blur. Blur works on KDE Plasma under Wayland, compositors with ext-background-effect (niri, GNOME 51 and newer), Windows and macOS. +There are 29 themes, and on Linux two more, GTK and Qt, that take their colours from your desktop. A fresh install starts on the one that matches your system. Every theme is a CSS file in the config folder's `themes` folder, so you can tweak them or make your own ([docs/THEMES.md](docs/THEMES.md)). Settings also has window transparency and background blur. Blur works on KDE Plasma under Wayland, compositors with ext-background-effect (niri, GNOME 51 and newer), Windows and macOS. ### Casting from a phone @@ -195,19 +199,19 @@ If the computer doesn't show up in the phone's Cast menu, a firewall is usually ### Signing in -Sign in from the app's own window, or use Import from browser on Home or in Settings, which takes the session of the browser you used last. It knows Firefox and its forks, Chrome, Chromium, Brave, Vivaldi, Edge, Opera, Whale and Helium. On Windows, browsers that use app-bound cookie encryption are left out, and the Flatpak has only the app's window. Signed out, refryt still searches and plays. +Sign in from the app's own window, or skip that and use Import from browser on Home or in Settings, which picks up the session from the browser you used last. It knows Firefox and its forks, Chrome, Chromium, Brave, Vivaldi, Edge, Opera, Whale and Helium. On Windows, browsers that use app-bound cookie encryption are left out, and the Flatpak has only the app's window. You don't have to sign in at all: signed out, refryt still searches and plays. ### Data and privacy Settings, themes, the session and the log live in `~/.config/refryt` on Linux, `~/Library/Application Support/refryt` on macOS and `~/.var/app/io.github.gridoe.refryt/config/refryt` in the Flatpak. The session is stored with owner-only permissions. -There is no telemetry. refryt connects to YouTube and a few lyrics sites (BetterLyrics, lrc.red, LRCLIB, KuGou and Unison) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. Each lyrics source and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. +refryt has no telemetry. It connects to YouTube and a few lyrics sites (BetterLyrics, lrc.red, LRCLIB, KuGou and Unison) for lyrics, GitHub for the update check, and Discord's local client if Rich Presence is on. Each lyrics source and the update check can be turned off in Settings. Crash reports stay on disk until you choose to copy or file them. [PRIVACY.md](PRIVACY.md) has the details. ## Status -The project is before 1.0 and changes quickly. Only the Linux builds see daily use; the Windows builds are cross-compiled with limited testing on real hardware, and the macOS build has been tested by hand. Podcasts are not supported. A change to YouTube's internal API can break playback or a page until a fix is released. +refryt is young (it hasn't reached 1.0) and moves quickly. Linux is where it gets used every day. The Windows builds are cross-compiled and have had less testing on real hardware, and the macOS build has been tested by hand. Podcasts aren't supported. Now and then YouTube changes its internal API, which can break playback or a page until a fix is out. -Bugs go to the [issue tracker](https://github.com/gridoe/refryt/issues); [CONTRIBUTING.md](CONTRIBUTING.md) says what to include. +Found a bug? Please open an [issue](https://github.com/gridoe/refryt/issues); [CONTRIBUTING.md](CONTRIBUTING.md) says what helps. Reports from Windows and macOS are especially welcome. ## Build from source