Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57e60a7fe3 | ||
|
|
1f806fd44d | ||
|
|
bb215790a7 | ||
|
|
df11d68382 | ||
|
|
a3782ed8a8 | ||
|
|
aa32dbb101 | ||
|
|
ddcd523282 | ||
|
|
5aef2cb1e7 |
No files matched your search
@@ -78,6 +78,9 @@ jobs:
|
||||
|
||||
publish:
|
||||
name: Publish release assets
|
||||
concurrency:
|
||||
group: release-assets-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -98,12 +101,67 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Hash archive bytes; manifest entries use the release asset basenames.
|
||||
for archive in artifacts/*/*; do
|
||||
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
|
||||
done > SHA256SUMS
|
||||
archives=(artifacts/*/*)
|
||||
assets=$(mktemp)
|
||||
if ! gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' > "$assets"; then
|
||||
for archive in "${archives[@]}"; do
|
||||
(cd "$(dirname "$archive")" && sha256sum "$(basename "$archive")")
|
||||
done > SHA256SUMS
|
||||
gh release create "$RELEASE_TAG" "${archives[@]}" SHA256SUMS \
|
||||
--title "furumi ${RELEASE_TAG}" \
|
||||
--notes "Release ${RELEASE_TAG}" \
|
||||
--verify-tag
|
||||
exit 0
|
||||
fi
|
||||
|
||||
gh release create "$RELEASE_TAG" artifacts/*/* SHA256SUMS \
|
||||
--title "furumi ${RELEASE_TAG}" \
|
||||
--notes "Release ${RELEASE_TAG}" \
|
||||
--verify-tag
|
||||
# Hash existing archives from the release itself. Rebuilt artifacts
|
||||
# can have different bytes even if the tag and file names match.
|
||||
published=$(mktemp -d)
|
||||
missing=()
|
||||
: > SHA256SUMS
|
||||
for archive in "${archives[@]}"; do
|
||||
name=$(basename "$archive")
|
||||
if grep -Fxq -- "$name" "$assets"; then
|
||||
gh release download "$RELEASE_TAG" --pattern "$name" --dir "$published"
|
||||
(cd "$published" && sha256sum "$name") >> SHA256SUMS
|
||||
else
|
||||
missing+=("$archive")
|
||||
(cd "$(dirname "$archive")" && sha256sum "$name") >> SHA256SUMS
|
||||
fi
|
||||
done
|
||||
|
||||
if (( ${#missing[@]} )); then
|
||||
gh release upload "$RELEASE_TAG" "${missing[@]}"
|
||||
fi
|
||||
if grep -Fxq -- SHA256SUMS "$assets"; then
|
||||
gh release download "$RELEASE_TAG" --pattern SHA256SUMS --dir "$published"
|
||||
if ! cmp -s "$published/SHA256SUMS" SHA256SUMS; then
|
||||
gh release upload "$RELEASE_TAG" SHA256SUMS --clobber
|
||||
fi
|
||||
else
|
||||
gh release upload "$RELEASE_TAG" SHA256SUMS
|
||||
fi
|
||||
|
||||
update-homebrew:
|
||||
name: Dispatch Homebrew formula update
|
||||
needs: publish
|
||||
if: github.server_url == 'https://github.com' && github.repository == 'Furumi-stack/furumi-tui'
|
||||
runs-on: ubuntu-latest
|
||||
permissions: {}
|
||||
steps:
|
||||
- name: Trigger workflow in the Homebrew tap
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Skipping Homebrew for non-stable tag $RELEASE_TAG"
|
||||
exit 0
|
||||
fi
|
||||
if [[ -z "$GH_TOKEN" ]]; then
|
||||
echo "::error::Set the HOMEBREW_TAP_TOKEN repository secret to dispatch the Homebrew update."
|
||||
exit 1
|
||||
fi
|
||||
gh workflow run update-furumi.yml \
|
||||
--repo house-of-vanity/homebrew-tap --ref main --raw-field "tag=$RELEASE_TAG"
|
||||
@@ -470,6 +470,21 @@ The TUI owns what the contract leaves to clients:
|
||||
progress generation this device saw, so a handoff target starts its
|
||||
session above it.
|
||||
|
||||
## Lyrics
|
||||
|
||||
Furumi loads saved lyrics from the library by canonical audio content ID.
|
||||
The playback runtime queries the optional `furumi/lyrics/1` stream in the
|
||||
background and adds distinct alternatives without changing the active version.
|
||||
Only tracks with local audio can be served. Save on listen persists discovered
|
||||
versions after the audio is imported. Track edits write directly to the local
|
||||
library, which keeps exclusions for deleted alternatives.
|
||||
|
||||
A single parsed LRC timeline supplies both the reader and the Rhai
|
||||
`input.lyrics` map. The map contains the current, previous and next line with
|
||||
timing and availability information. The text sent to a script is bounded on
|
||||
each frame. The bundled preset combines the `matrix_text` dot-matrix renderer
|
||||
with Unicode text, sparse Braille particles and timestamp-driven transitions.
|
||||
|
||||
## Scripted visualizations
|
||||
|
||||
Visualizations are an extension boundary rather than hard-coded rendering
|
||||
@@ -699,3 +714,14 @@ Future changes should preserve these rules:
|
||||
5. Network and storage work must remain outside the interactive UI path.
|
||||
6. More peers should improve availability; losing peers should only reduce
|
||||
remote capabilities.
|
||||
|
||||
### Device-local podcast audio
|
||||
|
||||
Episode downloads are explicit local actions. Completed files live beside the
|
||||
podcast database in `podcast-downloads`, keyed by a hash of the shared episode
|
||||
id. Temporary files become visible only after a complete response is saved.
|
||||
Playback checks this directory on the blocking pool before opening HTTP and
|
||||
uses the same progress and queue model for local audio. Downloads and retention
|
||||
settings never enter the podcast store registers or device-sync protocol.
|
||||
A background maintenance pass removes downloads after the configured age
|
||||
(default 30 days from completion); catalog, progress and subscriptions remain.
|
||||
Generated
+5
-5
@@ -1698,9 +1698,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "furumi-library"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e7eb785cc6ab5b59db8ef74ffa05d798afde45fbd86da08aecf356432a52d10"
|
||||
checksum = "fc11f57b118c407380be2bc8c05c9cff4033c8e6c37f9ada450004002801c386"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"blake3",
|
||||
@@ -1715,7 +1715,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "furumi_tui"
|
||||
version = "0.5.1"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
@@ -3240,9 +3240,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "music-dht"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce81f361952228654c28a46e41555f2c3d1520bf8c6c76562e7a53f70dd38e1"
|
||||
checksum = "f66490c90836afebfd75394d527f47abf8f0675f1eeb4b41dadbd94c13836521"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"blake3",
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "furumi_tui"
|
||||
version = "0.5.1"
|
||||
version = "0.6.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.97"
|
||||
description = "A federated P2P player for personal music libraries"
|
||||
@@ -29,12 +29,13 @@ crokey = "1.4.0"
|
||||
crossterm = { version = "0.29.0", features = ["event-stream"] }
|
||||
directories = "6.0.0"
|
||||
futures-util = "0.3.32"
|
||||
furumi-library = "0.3.0"
|
||||
furumi-library = "0.4.0"
|
||||
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
|
||||
lofty = "0.22"
|
||||
# P2P federation: library index in a shared DHT + audio streaming between
|
||||
# peers (same protocol as furumi-fd).
|
||||
music-dht = { version = "0.6.0", features = ["podcast-feed"] }
|
||||
# The library and player must share the same FRID podcast and lyrics types.
|
||||
music-dht = { version = "0.7.0", features = ["podcast-feed"] }
|
||||
ratatui = { version = "0.30.1", features = ["unstable-rendered-line-info"] }
|
||||
reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream", "blocking"] }
|
||||
rhai = { version = "1", features = ["sync"] }
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||

|
||||
|
||||
[](https://asciinema.org/a/xSCEn090SS4gk8Hk)
|
||||
|
||||
**Your music. Your devices. Your network.**
|
||||
|
||||
Furumi is a federated P2P player for your personal music library. Every
|
||||
@@ -152,6 +154,19 @@ The **Additional settings** window also contains the music save directory and
|
||||
visualization controls. Use Up/Down (or j/k) to navigate, Enter to select, and
|
||||
Esc to return to Settings. Long lists scroll with the selection.
|
||||
|
||||
### Lyrics
|
||||
|
||||
Press **l** for the selected track's lyrics or **Ctrl+L** for the playing track. Saved text opens immediately while
|
||||
Furumi looks for more versions on peers. Use **←/→** to select a version,
|
||||
**↑/↓** or **Page Up/Down** to read, and **f** to resume following timed lines.
|
||||
Federated lyrics are stored alongside local audio when **Save on listen** is
|
||||
enabled. A saved version can be served to peers that request the same audio.
|
||||
|
||||
In a local track's metadata editor, **F3** opens its lyrics versions. Use **a**
|
||||
to add a version, paste plain text or LRC, and save with **Ctrl+S** or **F2**.
|
||||
Select **Lyrics in motion** in the visualization settings for animated timed
|
||||
lyrics using the same selected alternative.
|
||||
|
||||
### Tabs and key bindings
|
||||
|
||||
The number keys open the tabs in the order they are shown, and Tab /
|
||||
@@ -186,9 +201,16 @@ take them literally and silence the notice.
|
||||
|
||||
### Podcasts
|
||||
|
||||
The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Furumi stores only
|
||||
the feed's episode information; audio stays on the publisher's server and is
|
||||
never imported into the music library or offered to other peers.
|
||||
The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Audio streams from
|
||||
the publisher unless you download an episode. Downloads stay on this device,
|
||||
are never imported into the music library or offered to other peers.
|
||||
|
||||
- Press `y` on an episode to download it; `[offline]` marks a complete local
|
||||
copy. Playback uses that copy, including resume and seeking, without HTTP.
|
||||
- Settings → Additional settings → Podcast downloads: keep days controls
|
||||
automatic cleanup (default 30 days from download completion). Cleanup runs
|
||||
while Furumi is open; expired files can be downloaded again. No episodes
|
||||
are downloaded automatically.
|
||||
|
||||
- **Add podcast** (`o`, or the first row) takes a feed URL; `feed://`,
|
||||
`podcast://` and URLs without a scheme are accepted. Nothing is stored unless
|
||||
@@ -462,7 +484,7 @@ owner_timeout_ms = 120000
|
||||
All clients must support the new coordination envelope for eventual single
|
||||
output ownership. frid's `PLAYBACK_PROTOCOL.md` describes the protocol, adapter
|
||||
contract and rollout. This release uses the published FRID crates
|
||||
`music-dht 0.6.0` and `furumi-library 0.3.0` from crates.io.
|
||||
`music-dht 0.7.0` and `furumi-library 0.4.0` from crates.io.
|
||||
|
||||
Run the local protocol checks from the TUI repository:
|
||||
|
||||
|
||||
+8
-2
@@ -32,6 +32,8 @@ pub enum Action {
|
||||
ToggleShuffle,
|
||||
CycleRepeat,
|
||||
ToggleVisualizer,
|
||||
OpenLyrics,
|
||||
OpenCurrentLyrics,
|
||||
CycleVisualizerMode,
|
||||
ToggleLike,
|
||||
ToggleTrackSelection,
|
||||
@@ -41,7 +43,7 @@ pub enum Action {
|
||||
QueueAddLast,
|
||||
MoveQueueUp,
|
||||
MoveQueueDown,
|
||||
/// Download the selected federated track(s) into the local library.
|
||||
/// Download selected federated tracks, or a podcast episode for offline playback.
|
||||
DownloadSelected,
|
||||
RemoveFromQueue,
|
||||
ClearQueue,
|
||||
@@ -129,6 +131,8 @@ impl Action {
|
||||
| Action::VolumeDown
|
||||
| Action::ToggleShuffle
|
||||
| Action::CycleRepeat
|
||||
| Action::OpenLyrics
|
||||
| Action::OpenCurrentLyrics
|
||||
| Action::ToggleVisualizer
|
||||
| Action::CycleVisualizerMode
|
||||
| Action::OpenConnectedDevices
|
||||
@@ -229,6 +233,8 @@ impl Action {
|
||||
Action::VolumeDown => "Volume down".into(),
|
||||
Action::ToggleShuffle => "Toggle shuffle".into(),
|
||||
Action::CycleRepeat => "Cycle repeat mode".into(),
|
||||
Action::OpenLyrics => "Show selected track lyrics".into(),
|
||||
Action::OpenCurrentLyrics => "Show now-playing lyrics".into(),
|
||||
Action::ToggleVisualizer => "Toggle fullscreen visualizer".into(),
|
||||
Action::CycleVisualizerMode => "Next visualizer display mode".into(),
|
||||
Action::ToggleLike => "Like / unlike".into(),
|
||||
@@ -239,7 +245,7 @@ impl Action {
|
||||
Action::QueueAddLast => "Queue: add to end".into(),
|
||||
Action::MoveQueueUp => "Queue: move track/selection up".into(),
|
||||
Action::MoveQueueDown => "Queue: move track/selection down".into(),
|
||||
Action::DownloadSelected => "Federation: download to library".into(),
|
||||
Action::DownloadSelected => "Download selected music / podcast episode".into(),
|
||||
Action::RemoveFromQueue => "Queue: remove selected".into(),
|
||||
Action::ClearQueue => "Queue: clear".into(),
|
||||
Action::OpenConnectedDevices => "Connected devices…".into(),
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::library::models::{
|
||||
/// the playback engine, imports). Tasks never touch AppState directly.
|
||||
#[derive(Debug)]
|
||||
pub enum AppEvent {
|
||||
Lyrics(super::lyrics::Event),
|
||||
UpdateChecked(Result<Option<crate::updater::Update>, String>),
|
||||
UpdateProgress(String),
|
||||
UpdateInstalled(Result<(), String>),
|
||||
@@ -273,6 +274,11 @@ pub enum AppEvent {
|
||||
},
|
||||
/// Scheduler timer: ask the store which feeds are due.
|
||||
PodcastRefreshTick,
|
||||
PodcastDownloads(Result<std::collections::HashSet<String>, String>),
|
||||
PodcastDownloaded {
|
||||
id: String,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
/// Feeds due for a background refresh.
|
||||
PodcastsDue(Result<Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>, String>),
|
||||
/// What sharing a podcast would publish (`Effect::PodcastPrepareShare`).
|
||||
|
||||
@@ -36,6 +36,47 @@ impl LineEdit {
|
||||
.unwrap_or(self.value.len())
|
||||
}
|
||||
|
||||
pub fn line_cursor(&self) -> (usize, usize) {
|
||||
let before = &self.value[..self.byte_index(self.cursor)];
|
||||
(
|
||||
before.bytes().filter(|&byte| byte == b'\n').count(),
|
||||
before
|
||||
.rsplit('\n')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.count(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn move_line(&mut self, direction: isize) {
|
||||
let (row, column) = self.line_cursor();
|
||||
self.move_to_line(row.saturating_add_signed(direction), column);
|
||||
}
|
||||
|
||||
pub fn line_edge(&mut self, end: bool) {
|
||||
let (row, _) = self.line_cursor();
|
||||
self.move_to_line(row, if end { usize::MAX } else { 0 });
|
||||
}
|
||||
|
||||
fn move_to_line(&mut self, row: usize, column: usize) {
|
||||
let mut start = 0;
|
||||
for (index, line) in self.value.split('\n').enumerate() {
|
||||
let len = line.chars().count();
|
||||
if index == row {
|
||||
self.cursor = start + column.min(len);
|
||||
return;
|
||||
}
|
||||
start += len + 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_cursor(value: impl Into<String>, cursor: usize) -> Self {
|
||||
let mut edit = Self::new(value);
|
||||
edit.cursor = edit.cursor.min(cursor);
|
||||
edit
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.value.clear();
|
||||
self.cursor = 0;
|
||||
|
||||
@@ -0,0 +1,788 @@
|
||||
//! Lyrics effects, playback selection, and the track editor.
|
||||
use super::Runtime;
|
||||
use super::event::AppEvent;
|
||||
use super::input::LineEdit;
|
||||
use super::state::{AppState, Popup, track_content_id};
|
||||
use crate::library::models::TrackItem;
|
||||
use crate::lyrics::{self, Document, SavedLyrics};
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use music_dht::lyrics::{LyricsVersion, MAX_LYRICS_TEXT_BYTES};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Playback {
|
||||
pub title: String,
|
||||
pub content_id: Option<String>,
|
||||
pub versions: Vec<LyricsVersion>,
|
||||
pub selected: usize,
|
||||
pub document: Document,
|
||||
pub document_revision: u64,
|
||||
pub loading: bool,
|
||||
track: Option<(i64, Option<String>)>,
|
||||
local_at: Option<Instant>,
|
||||
local_reading: bool,
|
||||
serial: u64,
|
||||
hidden: HashSet<String>,
|
||||
retry_at: Option<Instant>,
|
||||
task: Option<tokio::task::AbortHandle>,
|
||||
}
|
||||
|
||||
impl Playback {
|
||||
pub(super) fn refresh_local(&mut self) {
|
||||
self.local_at = Some(Instant::now());
|
||||
}
|
||||
|
||||
fn local_changed(&mut self, content_id: &str) {
|
||||
if self.content_id.as_deref() == Some(content_id)
|
||||
|| self.track.as_ref().and_then(|(_, id)| id.as_deref()) == Some(content_id)
|
||||
{
|
||||
self.refresh_local();
|
||||
}
|
||||
}
|
||||
|
||||
fn select(&mut self, index: usize) {
|
||||
self.document_revision = self.document_revision.wrapping_add(1);
|
||||
self.selected = index.min(self.versions.len().saturating_sub(1));
|
||||
self.document = self
|
||||
.versions
|
||||
.get(self.selected)
|
||||
.map(Document::new)
|
||||
.unwrap_or_default();
|
||||
}
|
||||
|
||||
fn add(&mut self, versions: Vec<LyricsVersion>) {
|
||||
let first = self.versions.is_empty();
|
||||
lyrics::merge(&mut self.versions, versions, &self.hidden);
|
||||
if first && !self.versions.is_empty() {
|
||||
self.select(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn saved(&mut self, saved: SavedLyrics) {
|
||||
if self.hidden == saved.hidden && self.versions.starts_with(&saved.versions) {
|
||||
return;
|
||||
}
|
||||
let selected = self
|
||||
.versions
|
||||
.get(self.selected)
|
||||
.map(|entry| entry.id.clone());
|
||||
self.hidden = saved.hidden;
|
||||
let existing = std::mem::replace(&mut self.versions, saved.versions);
|
||||
self.add(existing);
|
||||
self.select(
|
||||
selected
|
||||
.and_then(|id| self.versions.iter().position(|v| v.id == id))
|
||||
.unwrap_or(0),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Reader {
|
||||
pub top: Option<usize>,
|
||||
pub viewport_height: usize,
|
||||
pub preview: Option<Box<(TrackItem, Playback)>>,
|
||||
pub rows: Vec<(usize, String)>,
|
||||
pub layout_key: Option<(u64, usize)>,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
pub fn preview(track: TrackItem) -> Self {
|
||||
Self {
|
||||
preview: Some(Box::new((track, Playback::default()))),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lyrics<'a>(&'a self, playback: &'a Playback) -> &'a Playback {
|
||||
self.preview.as_ref().map_or(playback, |preview| &preview.1)
|
||||
}
|
||||
|
||||
pub fn active_line(
|
||||
&self,
|
||||
playback: &Playback,
|
||||
player: &super::state::PlayerBar,
|
||||
) -> Option<usize> {
|
||||
if let Some(preview) = &self.preview
|
||||
&& !player.current.as_ref().is_some_and(|track| {
|
||||
super::state::track_key(track) == super::state::track_key(&preview.0)
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.lyrics(playback).document.line_at(player.position_secs)
|
||||
}
|
||||
|
||||
fn cancel_preview(&mut self) {
|
||||
if let Some(task) = self
|
||||
.preview
|
||||
.as_mut()
|
||||
.and_then(|preview| preview.1.task.take())
|
||||
{
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn follow_top(&self, active: Option<usize>) -> usize {
|
||||
active
|
||||
.map(|active| self.rows.partition_point(|(index, _)| *index < active))
|
||||
.unwrap_or_default()
|
||||
.saturating_sub(self.viewport_height / 2)
|
||||
.min(self.rows.len().saturating_sub(self.viewport_height))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Editor {
|
||||
pub parent: Box<Popup>,
|
||||
pub track_id: i64,
|
||||
pub query: u64,
|
||||
pub content_id: Option<String>,
|
||||
pub versions: Vec<LyricsVersion>,
|
||||
pub cursor: usize,
|
||||
pub draft: Option<Draft>,
|
||||
pub busy: bool,
|
||||
pub confirm_delete: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Draft {
|
||||
pub replaced: Option<String>,
|
||||
pub label: LineEdit,
|
||||
pub text: LineEdit,
|
||||
pub label_focused: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Event {
|
||||
Local {
|
||||
serial: u64,
|
||||
content_id: Option<String>,
|
||||
saved: SavedLyrics,
|
||||
},
|
||||
Saved(String),
|
||||
Polled {
|
||||
serial: u64,
|
||||
saved: Option<SavedLyrics>,
|
||||
},
|
||||
Found {
|
||||
serial: u64,
|
||||
versions: Vec<LyricsVersion>,
|
||||
},
|
||||
Done {
|
||||
serial: u64,
|
||||
},
|
||||
Editor {
|
||||
query: u64,
|
||||
result: Result<(String, SavedLyrics), String>,
|
||||
},
|
||||
Edited {
|
||||
query: u64,
|
||||
result: Result<(String, SavedLyrics), String>,
|
||||
},
|
||||
}
|
||||
|
||||
fn send(tx: &tokio::sync::mpsc::UnboundedSender<AppEvent>, event: Event) {
|
||||
let _ = tx.send(AppEvent::Lyrics(event));
|
||||
}
|
||||
|
||||
pub(super) fn refresh(state: &mut AppState, runtime: &Runtime) {
|
||||
let changed = refresh_one(&mut state.lyrics, state.player.current.as_ref(), runtime);
|
||||
if let Some(Popup::Lyrics(reader)) = state.popup.as_mut() {
|
||||
let changed = match reader.preview.as_deref_mut() {
|
||||
Some((track, lyrics)) => refresh_one(lyrics, Some(track), runtime),
|
||||
None => changed,
|
||||
};
|
||||
if changed {
|
||||
reader.top = None;
|
||||
reader.layout_key = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_one(playback: &mut Playback, track: Option<&TrackItem>, runtime: &Runtime) -> bool {
|
||||
let track = track.filter(|track| !track.is_podcast());
|
||||
let key = track.map(|track| (track.id, track_content_id(track)));
|
||||
let same = playback.track == key
|
||||
|| matches!((&playback.track, &key),
|
||||
(Some((_, Some(old))), Some((_, Some(new)))) if old == new);
|
||||
if !same {
|
||||
if let Some(task) = playback.task.take() {
|
||||
task.abort();
|
||||
}
|
||||
*playback = Playback {
|
||||
title: track.map(|track| track.title.clone()).unwrap_or_default(),
|
||||
..Playback::default()
|
||||
};
|
||||
}
|
||||
playback.track = key;
|
||||
let Some(track) = track else { return !same };
|
||||
|
||||
let now = Instant::now();
|
||||
if same && (playback.loading || playback.retry_at.is_none_or(|at| at > now)) {
|
||||
if !playback.local_reading
|
||||
&& playback.local_at.is_some_and(|at| at <= now)
|
||||
&& let Some(content_id) = playback.content_id.clone()
|
||||
{
|
||||
playback.local_reading = true;
|
||||
playback.local_at = None;
|
||||
let serial = playback.serial;
|
||||
let library = Arc::clone(&runtime.library);
|
||||
let tx = runtime.event_tx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let saved = library
|
||||
.lyrics(&content_id)
|
||||
.map_err(|error| {
|
||||
tracing::warn!(%error, "could not refresh local lyrics");
|
||||
})
|
||||
.ok();
|
||||
send(&tx, Event::Polled { serial, saved });
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
playback.serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
playback.loading = true;
|
||||
playback.retry_at = None;
|
||||
playback.local_reading = false;
|
||||
playback.local_at = None;
|
||||
let serial = playback.serial;
|
||||
let id = track.id;
|
||||
let content_id = playback
|
||||
.content_id
|
||||
.clone()
|
||||
.or_else(|| track_content_id(track));
|
||||
let owner = track.fed.as_ref().map(|fed| fed.owner.clone());
|
||||
let library = Arc::clone(&runtime.library);
|
||||
let federation = Arc::clone(&runtime.federation);
|
||||
let tx = runtime.event_tx.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let local = tokio::task::spawn_blocking({
|
||||
let library = Arc::clone(&library);
|
||||
move || -> anyhow::Result<_> {
|
||||
let content_id = match content_id {
|
||||
Some(content_id) => Some(content_id),
|
||||
None if id > 0 => library.track_content_id_by_id(id)?,
|
||||
None => None,
|
||||
};
|
||||
let saved = content_id
|
||||
.as_deref()
|
||||
.map(|id| library.lyrics(id))
|
||||
.transpose();
|
||||
Ok((content_id, saved))
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Ok(Ok((content_id, saved))) = local {
|
||||
let saved = saved
|
||||
.unwrap_or_else(|error| {
|
||||
tracing::warn!(%error, "could not read local lyrics");
|
||||
None
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let hidden = saved.hidden.clone();
|
||||
send(
|
||||
&tx,
|
||||
Event::Local {
|
||||
serial,
|
||||
content_id: content_id.clone(),
|
||||
saved,
|
||||
},
|
||||
);
|
||||
if let Some(content_id) = content_id {
|
||||
let mut found = Vec::new();
|
||||
let _ = federation
|
||||
.find_lyrics(&content_id, owner.as_deref(), |versions| {
|
||||
let previous = found.len();
|
||||
lyrics::merge(&mut found, versions, &hidden);
|
||||
if found.len() > previous {
|
||||
let versions = found[previous..].to_vec();
|
||||
if federation.settings().save_on_listen {
|
||||
store_found(
|
||||
Arc::clone(&library),
|
||||
content_id.clone(),
|
||||
versions.clone(),
|
||||
tx.clone(),
|
||||
);
|
||||
}
|
||||
send(&tx, Event::Found { serial, versions });
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
} else {
|
||||
tracing::warn!("lyrics library lookup failed");
|
||||
}
|
||||
send(&tx, Event::Done { serial });
|
||||
});
|
||||
playback.task = Some(task.abort_handle());
|
||||
!same
|
||||
}
|
||||
|
||||
fn store_found(
|
||||
library: Arc<crate::library::Library>,
|
||||
content_id: String,
|
||||
versions: Vec<LyricsVersion>,
|
||||
tx: tokio::sync::mpsc::UnboundedSender<AppEvent>,
|
||||
) {
|
||||
if !versions.is_empty() {
|
||||
tokio::task::spawn_blocking(move || match library.merge_lyrics(&content_id, versions) {
|
||||
Ok(()) => send(&tx, Event::Saved(content_id)),
|
||||
Err(error) => tracing::warn!(%error, %content_id, "could not save peer lyrics"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio can become permanent after the lyrics request already completed.
|
||||
pub(super) fn on_import(state: &AppState, runtime: &Runtime, track: &TrackItem) {
|
||||
let Some(content_id) = track_content_id(track) else {
|
||||
return;
|
||||
};
|
||||
if state.lyrics.content_id.as_deref() == Some(content_id.as_str()) {
|
||||
store_found(
|
||||
Arc::clone(&runtime.library),
|
||||
content_id,
|
||||
state.lyrics.versions.clone(),
|
||||
runtime.event_tx.clone(),
|
||||
);
|
||||
} else if runtime.federation.settings().save_on_listen {
|
||||
// The queue could have advanced while the audio was still downloading.
|
||||
let federation = Arc::clone(&runtime.federation);
|
||||
let library = Arc::clone(&runtime.library);
|
||||
let tx = runtime.event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut versions = Vec::new();
|
||||
let _ = federation
|
||||
.find_lyrics(&content_id, None, |incoming| {
|
||||
lyrics::merge(&mut versions, incoming, &HashSet::new());
|
||||
})
|
||||
.await;
|
||||
store_found(library, content_id, versions, tx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_event(state: &mut AppState, event: Event) {
|
||||
let preview = match &mut state.popup {
|
||||
Some(Popup::Lyrics(reader)) => reader.preview.as_deref_mut().map(|preview| &mut preview.1),
|
||||
_ => None,
|
||||
};
|
||||
if let Event::Saved(content_id) = &event {
|
||||
state.lyrics.local_changed(content_id);
|
||||
if let Some(preview) = preview {
|
||||
preview.local_changed(content_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let serial = match &event {
|
||||
Event::Local { serial, .. }
|
||||
| Event::Polled { serial, .. }
|
||||
| Event::Found { serial, .. }
|
||||
| Event::Done { serial } => Some(*serial),
|
||||
_ => None,
|
||||
};
|
||||
let playback = match serial {
|
||||
Some(serial) if state.lyrics.serial != serial => {
|
||||
let Some(preview) = preview.filter(|preview| preview.serial == serial) else {
|
||||
return;
|
||||
};
|
||||
preview
|
||||
}
|
||||
_ => &mut state.lyrics,
|
||||
};
|
||||
match event {
|
||||
Event::Local {
|
||||
content_id, saved, ..
|
||||
} => {
|
||||
playback.content_id = content_id;
|
||||
playback
|
||||
.local_at
|
||||
.get_or_insert_with(|| Instant::now() + Duration::from_secs(1));
|
||||
playback.saved(saved);
|
||||
}
|
||||
Event::Polled { saved, .. } => {
|
||||
playback.local_reading = false;
|
||||
// A write notification may have arrived while this read was in flight.
|
||||
playback
|
||||
.local_at
|
||||
.get_or_insert_with(|| Instant::now() + Duration::from_secs(1));
|
||||
if let Some(saved) = saved {
|
||||
playback.saved(saved);
|
||||
}
|
||||
}
|
||||
Event::Found { versions, .. } => playback.add(versions),
|
||||
Event::Done { .. } => {
|
||||
playback.task = None;
|
||||
playback.loading = false;
|
||||
playback.retry_at = Some(Instant::now() + Duration::from_secs(60));
|
||||
}
|
||||
Event::Editor { query, result } | Event::Edited { query, result } => {
|
||||
if let Ok((content_id, saved)) = &result
|
||||
&& playback.content_id.as_deref() == Some(content_id)
|
||||
{
|
||||
playback.saved(SavedLyrics {
|
||||
versions: saved.versions.clone(),
|
||||
hidden: saved.hidden.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(Popup::LyricsEditor(editor)) = &mut state.popup
|
||||
&& editor.query == query
|
||||
{
|
||||
editor.busy = false;
|
||||
match result {
|
||||
Ok((content_id, saved)) => {
|
||||
editor.content_id = Some(content_id);
|
||||
editor.versions = saved.versions;
|
||||
editor.cursor = editor.cursor.min(editor.versions.len().saturating_sub(1));
|
||||
editor.draft = None;
|
||||
editor.error = None;
|
||||
}
|
||||
Err(error) => editor.error = Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Saved(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reader_key(state: &mut AppState, mut reader: Reader, key: KeyEvent) {
|
||||
if key.code == KeyCode::Char('l') {
|
||||
match key.modifiers {
|
||||
KeyModifiers::CONTROL if reader.preview.is_some() => {
|
||||
reader.cancel_preview();
|
||||
let _ = super::update::update(state, super::action::Action::OpenCurrentLyrics);
|
||||
return;
|
||||
}
|
||||
KeyModifiers::NONE if reader.preview.is_none() => {
|
||||
let _ = super::update::update(state, super::action::Action::OpenLyrics);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let last = reader.rows.len().saturating_sub(reader.viewport_height);
|
||||
let top = reader
|
||||
.top
|
||||
.unwrap_or_else(|| reader.follow_top(reader.active_line(&state.lyrics, &state.player)));
|
||||
let playback = reader
|
||||
.preview
|
||||
.as_deref_mut()
|
||||
.map_or(&mut state.lyrics, |preview| &mut preview.1);
|
||||
let page = reader.viewport_height.saturating_sub(1).max(1);
|
||||
match key.code {
|
||||
KeyCode::Esc | KeyCode::Char('l' | 'q') => {
|
||||
reader.cancel_preview();
|
||||
return;
|
||||
}
|
||||
KeyCode::Up | KeyCode::Char('k') => reader.top = Some(top.saturating_sub(1)),
|
||||
KeyCode::Down | KeyCode::Char('j') => reader.top = Some((top + 1).min(last)),
|
||||
KeyCode::PageUp => reader.top = Some(top.saturating_sub(page)),
|
||||
KeyCode::PageDown => reader.top = Some((top + page).min(last)),
|
||||
KeyCode::Home => reader.top = Some(0),
|
||||
KeyCode::End => reader.top = Some(last),
|
||||
KeyCode::Char('f') => reader.top = None,
|
||||
KeyCode::Right | KeyCode::Tab if !playback.versions.is_empty() => {
|
||||
playback.select((playback.selected + 1) % playback.versions.len());
|
||||
reader.top = None;
|
||||
}
|
||||
KeyCode::Left | KeyCode::BackTab if !playback.versions.is_empty() => {
|
||||
playback.select(
|
||||
(playback.selected + playback.versions.len() - 1) % playback.versions.len(),
|
||||
);
|
||||
reader.top = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
state.popup = Some(Popup::Lyrics(reader));
|
||||
}
|
||||
|
||||
pub(super) fn open_editor(state: &mut AppState, runtime: &Runtime, parent: Popup, track_id: i64) {
|
||||
static NEXT_QUERY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let query = NEXT_QUERY.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
state.popup = Some(Popup::LyricsEditor(Box::new(Editor {
|
||||
parent: Box::new(parent),
|
||||
track_id,
|
||||
query,
|
||||
content_id: None,
|
||||
versions: Vec::new(),
|
||||
cursor: 0,
|
||||
draft: None,
|
||||
busy: true,
|
||||
confirm_delete: false,
|
||||
error: None,
|
||||
})));
|
||||
let tx = runtime.event_tx.clone();
|
||||
let library = Arc::clone(&runtime.library);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let result = (|| -> anyhow::Result<_> {
|
||||
let content_id = match library.track_content_id_by_id(track_id)? {
|
||||
Some(id) => Some(id),
|
||||
None => library
|
||||
.tracks_by_ids(&[track_id])?
|
||||
.first()
|
||||
.and_then(|track| crate::library::audio_content_id(&track.file_path)),
|
||||
}
|
||||
.ok_or_else(|| anyhow::anyhow!("Could not identify the local audio file"))?;
|
||||
let saved = library.lyrics(&content_id)?;
|
||||
Ok((content_id, saved))
|
||||
})()
|
||||
.map_err(|error| format!("{error:#}"));
|
||||
send(&tx, Event::Editor { query, result });
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn editor_key(
|
||||
state: &mut AppState,
|
||||
runtime: &Runtime,
|
||||
mut editor: Box<Editor>,
|
||||
key: KeyEvent,
|
||||
) {
|
||||
if !editor.busy {
|
||||
if let Some(draft) = &mut editor.draft {
|
||||
match key.code {
|
||||
KeyCode::Esc => {
|
||||
editor.draft = None;
|
||||
editor.error = None;
|
||||
}
|
||||
KeyCode::F(2) => save_draft(runtime, &mut editor),
|
||||
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
save_draft(runtime, &mut editor)
|
||||
}
|
||||
KeyCode::Tab | KeyCode::BackTab => draft.label_focused = !draft.label_focused,
|
||||
_ if draft.label_focused => {
|
||||
if draft.label.len() < 512 || !matches!(key.code, KeyCode::Char(_)) {
|
||||
draft.label.handle_key(key);
|
||||
}
|
||||
}
|
||||
KeyCode::Enter if draft.text.len() < MAX_LYRICS_TEXT_BYTES => {
|
||||
draft.text.insert('\n')
|
||||
}
|
||||
KeyCode::Up => draft.text.move_line(-1),
|
||||
KeyCode::Down => draft.text.move_line(1),
|
||||
KeyCode::Home => draft.text.line_edge(false),
|
||||
KeyCode::End => draft.text.line_edge(true),
|
||||
_ => {
|
||||
if draft.text.len() < MAX_LYRICS_TEXT_BYTES
|
||||
|| !matches!(key.code, KeyCode::Char(_))
|
||||
{
|
||||
draft.text.handle_key(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if editor.confirm_delete {
|
||||
editor.confirm_delete = false;
|
||||
if matches!(key.code, KeyCode::Char('y') | KeyCode::Enter) {
|
||||
let id = editor
|
||||
.versions
|
||||
.get(editor.cursor)
|
||||
.map(|entry| entry.id.clone());
|
||||
submit(runtime, &mut editor, id, None);
|
||||
}
|
||||
} else {
|
||||
match key.code {
|
||||
KeyCode::Esc => {
|
||||
state.popup = Some(*editor.parent);
|
||||
return;
|
||||
}
|
||||
KeyCode::Up => editor.cursor = editor.cursor.saturating_sub(1),
|
||||
KeyCode::Down => {
|
||||
editor.cursor = (editor.cursor + 1).min(editor.versions.len().saturating_sub(1))
|
||||
}
|
||||
KeyCode::Char('a') if editor.content_id.is_some() => {
|
||||
editor.error = None;
|
||||
editor.draft = Some(Draft {
|
||||
replaced: None,
|
||||
label: LineEdit::default(),
|
||||
text: LineEdit::default(),
|
||||
label_focused: false,
|
||||
});
|
||||
}
|
||||
KeyCode::Enter if editor.content_id.is_some() => {
|
||||
if let Some(entry) = editor.versions.get(editor.cursor) {
|
||||
editor.error = None;
|
||||
editor.draft = Some(Draft {
|
||||
replaced: Some(entry.id.clone()),
|
||||
label: LineEdit::new(
|
||||
lyrics::clean_text(&entry.label).replace('\n', " "),
|
||||
),
|
||||
text: LineEdit::new(lyrics::clean_text(
|
||||
entry
|
||||
.synced_lrc
|
||||
.as_deref()
|
||||
.or(entry.plain_text.as_deref())
|
||||
.unwrap_or_default(),
|
||||
)),
|
||||
label_focused: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
KeyCode::Delete | KeyCode::Char('d') if !editor.versions.is_empty() => {
|
||||
editor.confirm_delete = true
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
state.popup = Some(Popup::LyricsEditor(editor));
|
||||
}
|
||||
|
||||
fn save_draft(runtime: &Runtime, editor: &mut Editor) {
|
||||
if let Some(draft) = editor.draft.as_ref() {
|
||||
match lyrics::manual_version(&draft.label, &draft.text) {
|
||||
Ok(version) => submit(runtime, editor, draft.replaced.clone(), Some(version)),
|
||||
Err(error) => editor.error = Some(format!("{error:#}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(
|
||||
runtime: &Runtime,
|
||||
editor: &mut Editor,
|
||||
replaced: Option<String>,
|
||||
version: Option<LyricsVersion>,
|
||||
) {
|
||||
let Some(content_id) = editor.content_id.clone() else {
|
||||
return;
|
||||
};
|
||||
let library = Arc::clone(&runtime.library);
|
||||
let track_id = editor.track_id;
|
||||
let tx = runtime.event_tx.clone();
|
||||
let query = editor.query;
|
||||
editor.busy = true;
|
||||
editor.error = None;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let result = (|| -> anyhow::Result<_> {
|
||||
let track = library
|
||||
.tracks_by_ids(&[track_id])?
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("The local track has been removed"))?;
|
||||
let current_id = track_content_id(&track)
|
||||
.or_else(|| crate::library::audio_content_id(&track.file_path));
|
||||
anyhow::ensure!(
|
||||
current_id.as_deref() == Some(&content_id),
|
||||
"The local audio has changed"
|
||||
);
|
||||
let saved = library.edit_lyrics(track_id, &content_id, replaced.as_deref(), version)?;
|
||||
Ok((content_id, saved))
|
||||
})()
|
||||
.map_err(|error| format!("{error:#}"));
|
||||
send(&tx, Event::Edited { query, result });
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn paste(editor: &mut Editor, pasted: &str) {
|
||||
if editor.busy {
|
||||
return;
|
||||
}
|
||||
let Some(draft) = &mut editor.draft else {
|
||||
return;
|
||||
};
|
||||
let cleaned = lyrics::clean_text(pasted);
|
||||
let (input, text, limit): (_, _, usize) = if draft.label_focused {
|
||||
(&mut draft.label, cleaned.replace('\n', " "), 512)
|
||||
} else {
|
||||
(&mut draft.text, cleaned, MAX_LYRICS_TEXT_BYTES)
|
||||
};
|
||||
if text.len() <= limit.saturating_sub(input.len()) {
|
||||
input.insert_str(&text);
|
||||
editor.error = None;
|
||||
} else {
|
||||
editor.error = Some("Pasted text exceeds the field size limit".into());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn late_peer_results_cannot_replace_the_current_track_or_selected_version() {
|
||||
let mut state = AppState::default();
|
||||
state.lyrics.serial = 2;
|
||||
let local = lyrics::manual_version("Local", "Current song").unwrap();
|
||||
state.lyrics.saved(SavedLyrics {
|
||||
versions: vec![local.clone()],
|
||||
..Default::default()
|
||||
});
|
||||
handle_event(
|
||||
&mut state,
|
||||
Event::Found {
|
||||
serial: 1,
|
||||
versions: vec![lyrics::manual_version("Old", "Previous song").unwrap()],
|
||||
},
|
||||
);
|
||||
assert_eq!(state.lyrics.versions, [local]);
|
||||
handle_event(
|
||||
&mut state,
|
||||
Event::Found {
|
||||
serial: 2,
|
||||
versions: vec![lyrics::manual_version("Peer", "[00:01]Timed song").unwrap()],
|
||||
},
|
||||
);
|
||||
assert_eq!(state.lyrics.versions.len(), 2);
|
||||
assert_eq!(state.lyrics.document.lines, ["Current song"]);
|
||||
reader_key(
|
||||
&mut state,
|
||||
Reader::default(),
|
||||
KeyEvent::new(KeyCode::Right, KeyModifiers::NONE),
|
||||
);
|
||||
assert_eq!(state.lyrics.document.line_at(1.0), Some(0));
|
||||
assert_eq!(state.lyrics.document.lines, ["Timed song"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_lyrics_refresh_playback_even_after_network_lookup_ended() {
|
||||
let mut state = AppState::default();
|
||||
let content_id = format!("b3:{}", "a".repeat(64));
|
||||
state.lyrics.content_id = Some(content_id.clone());
|
||||
state.lyrics.serial = 2;
|
||||
handle_event(&mut state, Event::Done { serial: 2 });
|
||||
let retry_at = state.lyrics.retry_at;
|
||||
handle_event(&mut state, Event::Saved(content_id));
|
||||
assert!(state.lyrics.local_at.unwrap() <= Instant::now());
|
||||
|
||||
// The local read is independent of the pending network retry.
|
||||
let version = lyrics::manual_version("Saved", "[00:01]Received words").unwrap();
|
||||
handle_event(
|
||||
&mut state,
|
||||
Event::Polled {
|
||||
serial: 2,
|
||||
saved: Some(SavedLyrics {
|
||||
versions: vec![version],
|
||||
..Default::default()
|
||||
}),
|
||||
},
|
||||
);
|
||||
assert_eq!(state.lyrics.document.lines, ["Received words"]);
|
||||
assert_eq!(state.lyrics.document.line_at(1.0), Some(0));
|
||||
assert_eq!(state.lyrics.retry_at, retry_at);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_scrolls_plain_text_one_row_per_keypress() {
|
||||
let mut state = AppState::default();
|
||||
let reader = Reader {
|
||||
viewport_height: 4,
|
||||
rows: (0..8)
|
||||
.map(|index| (index, format!("Line {index}")))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
reader_key(
|
||||
&mut state,
|
||||
reader,
|
||||
KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
|
||||
);
|
||||
assert!(matches!(
|
||||
state.popup,
|
||||
Some(Popup::Lyrics(Reader { top: Some(1), .. }))
|
||||
));
|
||||
}
|
||||
}
|
||||
+28
-6
@@ -4,6 +4,7 @@ pub mod command;
|
||||
mod enrichment;
|
||||
pub mod event;
|
||||
pub mod input;
|
||||
pub(crate) mod lyrics;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod podcast_fixtures;
|
||||
pub(crate) mod podcast_runtime;
|
||||
@@ -422,6 +423,7 @@ pub async fn run(
|
||||
status_message,
|
||||
..AppState::default()
|
||||
};
|
||||
state.podcast_retention_days = settings.podcast_retention_days;
|
||||
state.player.volume = settings.volume;
|
||||
state.global.filters = settings.library;
|
||||
state.music_dir = settings.music_dir.clone();
|
||||
@@ -546,22 +548,30 @@ pub async fn run(
|
||||
terminal.clear()?;
|
||||
runtime.force_redraw = false;
|
||||
}
|
||||
ui::lyrics::prepare_reader(&mut state, terminal.get_frame().area());
|
||||
terminal.draw(|frame| ui::draw(frame, &state, &keymap))?;
|
||||
}
|
||||
|
||||
redraw = true;
|
||||
tokio::select! {
|
||||
maybe_event = input.next() => match maybe_event {
|
||||
Some(Ok(event)) => handle_terminal_event(&mut state, &mut keymap, &mut runtime, event),
|
||||
Some(Ok(event)) => {
|
||||
handle_terminal_event(&mut state, &mut keymap, &mut runtime, event);
|
||||
lyrics::refresh(&mut state, &runtime);
|
||||
},
|
||||
Some(Err(err)) => return Err(err.into()),
|
||||
None => state.should_quit = true,
|
||||
},
|
||||
Some(app_event) = event_rx.recv() => handle_app_event(&mut state, &mut runtime, app_event),
|
||||
Some(app_event) = event_rx.recv() => {
|
||||
handle_app_event(&mut state, &mut runtime, app_event);
|
||||
lyrics::refresh(&mut state, &runtime);
|
||||
},
|
||||
_ = tick.tick() => {
|
||||
reconcile_personal_playback(&mut state, &mut runtime);
|
||||
state.advance_spinner();
|
||||
expire_quit_confirmation(&mut state);
|
||||
sync_player_shared(&mut state, &runtime);
|
||||
lyrics::refresh(&mut state, &runtime);
|
||||
podcast_runtime::tick(&state, &mut runtime);
|
||||
runtime
|
||||
.status_publisher
|
||||
@@ -1728,7 +1738,9 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
|
||||
});
|
||||
}
|
||||
// Executed by podcast_runtime::perform above.
|
||||
Effect::PodcastsReload
|
||||
Effect::SavePodcastSettings
|
||||
| Effect::PodcastDownload(_)
|
||||
| Effect::PodcastsReload
|
||||
| Effect::PodcastLoadSeasons(_)
|
||||
| Effect::PodcastLoadEpisodes { .. }
|
||||
| Effect::PodcastSubscribe(_)
|
||||
@@ -3133,14 +3145,19 @@ fn refresh_artists(state: &mut AppState, runtime: &Runtime) {
|
||||
});
|
||||
}
|
||||
|
||||
fn save_app_settings(state: &AppState) {
|
||||
let settings = crate::config::settings::AppSettings {
|
||||
fn app_settings(state: &AppState) -> crate::config::settings::AppSettings {
|
||||
crate::config::settings::AppSettings {
|
||||
podcast_retention_days: state.podcast_retention_days,
|
||||
playback: state.device_playback.config.clone(),
|
||||
volume: state.player.volume,
|
||||
library: state.global.filters,
|
||||
music_dir: state.music_dir.clone(),
|
||||
similarity: state.similarity.settings.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn save_app_settings(state: &AppState) {
|
||||
let settings = app_settings(state);
|
||||
if let Err(err) = crate::config::settings::save(&settings) {
|
||||
tracing::warn!(%err, "saving app settings failed");
|
||||
}
|
||||
@@ -3523,6 +3540,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
return;
|
||||
};
|
||||
match event {
|
||||
AppEvent::Lyrics(event) => lyrics::handle_event(state, event),
|
||||
// Folded in by podcast_runtime::handle_event above.
|
||||
AppEvent::PodcastStoreOpened(_)
|
||||
| AppEvent::PodcastsSynced { .. }
|
||||
@@ -3535,6 +3553,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
| AppEvent::PodcastProgress(_)
|
||||
| AppEvent::PodcastEpisodeStarted { .. }
|
||||
| AppEvent::PodcastEpisodeFailed { .. }
|
||||
| AppEvent::PodcastDownloads(_)
|
||||
| AppEvent::PodcastDownloaded { .. }
|
||||
| AppEvent::PodcastRefreshTick
|
||||
| AppEvent::PodcastsDue(_)
|
||||
| AppEvent::PodcastSharePrepared { .. }
|
||||
@@ -3913,6 +3933,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
match result {
|
||||
Ok(playable) => {
|
||||
if playable.imported {
|
||||
lyrics::on_import(state, runtime, &playable.track);
|
||||
if let Some(content_id) = state::track_content_id(&playable.track) {
|
||||
state.local_content_ids.insert(content_id.clone());
|
||||
let _ = runtime
|
||||
@@ -4275,6 +4296,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
|
||||
}
|
||||
AppEvent::Player(player::PlayerEvent::Started) => {
|
||||
runtime.player_start_pending = false;
|
||||
state.lyrics.refresh_local();
|
||||
}
|
||||
AppEvent::Player(player::PlayerEvent::TrackFinished { has_next }) => {
|
||||
// An episode that played to the end is complete; one whose
|
||||
|
||||
@@ -41,6 +41,8 @@ const PUBLICATION_FLUSH_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
pub struct PodcastRuntime {
|
||||
pub services: Services,
|
||||
refresh_slots: Arc<tokio::sync::Semaphore>,
|
||||
download_slots: Arc<tokio::sync::Semaphore>,
|
||||
downloads_cancelled: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// Writes progress in order on its own thread; `None` if it could not
|
||||
/// start (episodes then play without saving progress).
|
||||
progress: Option<ProgressWriter>,
|
||||
@@ -187,6 +189,18 @@ fn services(runtime: &Runtime) -> Option<Services> {
|
||||
|
||||
/// Executes a podcast [`Effect`]; any other effect is handed back.
|
||||
pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> Option<Effect> {
|
||||
if matches!(effect, Effect::SavePodcastSettings) {
|
||||
let settings = super::app_settings(state);
|
||||
let tx = runtime.event_tx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let message = match crate::config::settings::save(&settings) {
|
||||
Ok(()) => "podcasts: download retention saved".to_string(),
|
||||
Err(_) => "podcasts: could not save download retention".to_string(),
|
||||
};
|
||||
let _ = tx.send(AppEvent::StatusMessage(message));
|
||||
});
|
||||
return None;
|
||||
}
|
||||
let Some(services) = services(runtime) else {
|
||||
if is_podcast_effect(&effect) {
|
||||
if let Effect::PodcastRefresh { targets, .. } = &effect {
|
||||
@@ -219,6 +233,30 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
|
||||
};
|
||||
let tx = runtime.event_tx.clone();
|
||||
match effect {
|
||||
Effect::SavePodcastSettings => unreachable!("handled before store lookup"),
|
||||
Effect::PodcastDownload(episode) => {
|
||||
let slots = Arc::clone(&runtime.podcasts.as_ref().unwrap().download_slots);
|
||||
let cancelled = Arc::clone(&runtime.podcasts.as_ref().unwrap().downloads_cancelled);
|
||||
tokio::spawn(async move {
|
||||
let Ok(permit) = slots.acquire_owned().await else {
|
||||
return;
|
||||
};
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
let id = episode.episode_id.as_str().to_owned();
|
||||
let result = crate::podcasts::offline::download_with_cancel(
|
||||
&services.downloads_dir,
|
||||
&episode,
|
||||
CancelToken::new(move || {
|
||||
cancelled.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}),
|
||||
)
|
||||
.map_err(|_| "could not download episode audio".to_string());
|
||||
let _ = tx.send(AppEvent::PodcastDownloaded { id, result });
|
||||
})
|
||||
.await;
|
||||
});
|
||||
}
|
||||
Effect::PodcastsReload => {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let result = load_rows(&services.store).map_err(err_string);
|
||||
@@ -411,7 +449,9 @@ fn set_shared(
|
||||
fn is_podcast_effect(effect: &Effect) -> bool {
|
||||
matches!(
|
||||
effect,
|
||||
Effect::PodcastsReload
|
||||
Effect::SavePodcastSettings
|
||||
| Effect::PodcastDownload(_)
|
||||
| Effect::PodcastsReload
|
||||
| Effect::PodcastLoadSeasons(_)
|
||||
| Effect::PodcastLoadEpisodes { .. }
|
||||
| Effect::PodcastSubscribe(_)
|
||||
@@ -477,6 +517,8 @@ pub fn handle_event(
|
||||
runtime.podcasts = Some(PodcastRuntime {
|
||||
services,
|
||||
refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)),
|
||||
download_slots: Arc::new(tokio::sync::Semaphore::new(2)),
|
||||
downloads_cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
||||
progress,
|
||||
publication,
|
||||
});
|
||||
@@ -599,7 +641,34 @@ pub fn handle_event(
|
||||
episode_failed(state, runtime, generation, message);
|
||||
Vec::new()
|
||||
}
|
||||
AppEvent::PodcastDownloaded { id, result } => {
|
||||
state.podcast_downloading.remove(&id);
|
||||
state.status_message = Some(match result {
|
||||
Ok(()) => "podcasts: episode downloaded".into(),
|
||||
Err(e) => e,
|
||||
});
|
||||
let _ = runtime.event_tx.send(AppEvent::PodcastRefreshTick);
|
||||
Vec::new()
|
||||
}
|
||||
AppEvent::PodcastDownloads(result) => {
|
||||
if let Ok(downloads) = result {
|
||||
state.podcast_downloads = downloads;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
AppEvent::PodcastRefreshTick => {
|
||||
let offline_services = services(runtime)?;
|
||||
let days = state.podcast_retention_days.max(1);
|
||||
let tx = runtime.event_tx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let result = crate::podcasts::offline::cleanup(
|
||||
&offline_services.downloads_dir,
|
||||
days,
|
||||
std::time::SystemTime::now(),
|
||||
)
|
||||
.map_err(err_string);
|
||||
let _ = tx.send(AppEvent::PodcastDownloads(result));
|
||||
});
|
||||
if let Some(services) = services(runtime) {
|
||||
let tx = runtime.event_tx.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -1148,6 +1217,12 @@ fn progress_event(
|
||||
/// also one still being written) reach the overlay. Logs a warning when a
|
||||
/// card of a private podcast may still be live.
|
||||
pub(crate) async fn shutdown(runtime: &mut Runtime) {
|
||||
if let Some(podcasts) = &runtime.podcasts {
|
||||
podcasts
|
||||
.downloads_cancelled
|
||||
.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
podcasts.download_slots.close();
|
||||
}
|
||||
end_playback(runtime);
|
||||
let Some(podcasts) = runtime.podcasts.as_mut() else {
|
||||
return;
|
||||
|
||||
@@ -97,6 +97,8 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
|
||||
return;
|
||||
};
|
||||
match popup {
|
||||
Popup::Lyrics(reader) => super::lyrics::reader_key(state, reader, key),
|
||||
Popup::LyricsEditor(editor) => super::lyrics::editor_key(state, runtime, editor, key),
|
||||
Popup::AddToPlaylist { target, cursor } => {
|
||||
handle_picker(state, runtime, target, cursor, key);
|
||||
}
|
||||
@@ -614,6 +616,20 @@ fn handle_fed_input(
|
||||
!state.federation.settings.network_id.is_empty();
|
||||
super::fed_apply_settings(state, runtime);
|
||||
}
|
||||
FedInputField::PodcastRetention => match value.parse::<u32>() {
|
||||
Ok(days) if (1..=36500).contains(&days) => {
|
||||
state.podcast_retention_days = days;
|
||||
super::perform_effect(
|
||||
state,
|
||||
runtime,
|
||||
crate::app::update::Effect::SavePodcastSettings,
|
||||
);
|
||||
}
|
||||
_ => {
|
||||
state.status_message =
|
||||
Some("enter a retention period from 1 to 36500 days".into())
|
||||
}
|
||||
},
|
||||
FedInputField::MusicDirectory => {
|
||||
if value.is_empty() {
|
||||
state.status_message = Some("music directory is empty".into());
|
||||
@@ -836,6 +852,10 @@ fn handle_device_leave(state: &mut AppState, runtime: &mut Runtime, key: KeyEven
|
||||
|
||||
/// Pasted text goes into the focused text field when one is open.
|
||||
pub fn handle_paste(state: &mut AppState, runtime: &mut Runtime, pasted: &str) {
|
||||
if let Some(Popup::LyricsEditor(editor)) = &mut state.popup {
|
||||
super::lyrics::paste(editor, pasted);
|
||||
return;
|
||||
}
|
||||
let cleaned: String = pasted.chars().filter(|c| !c.is_control()).collect();
|
||||
let mut search = None;
|
||||
match &mut state.popup {
|
||||
@@ -880,6 +900,17 @@ fn handle_edit(
|
||||
) {
|
||||
match key.code {
|
||||
KeyCode::Esc => return,
|
||||
KeyCode::F(3) if let EditTarget::Track(id) = target => {
|
||||
let parent = Popup::Edit {
|
||||
target,
|
||||
title,
|
||||
fields,
|
||||
focus,
|
||||
error,
|
||||
};
|
||||
super::lyrics::open_editor(state, runtime, parent, id);
|
||||
return;
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
match save_edit(runtime, target, &fields) {
|
||||
Ok(message) => {
|
||||
|
||||
+43
-9
@@ -740,6 +740,8 @@ impl PlaylistAddTarget {
|
||||
/// Modal dialog over the main screen.
|
||||
#[derive(Debug)]
|
||||
pub enum Popup {
|
||||
Lyrics(super::lyrics::Reader),
|
||||
LyricsEditor(Box<super::lyrics::Editor>),
|
||||
/// Pick one of the playlists (last row = "create new"); the target is
|
||||
/// added on Enter (federated tracks are downloaded first).
|
||||
AddToPlaylist {
|
||||
@@ -762,7 +764,10 @@ pub enum Popup {
|
||||
error: Option<String>,
|
||||
},
|
||||
/// Delete confirmation; Enter/y deletes, Esc/n cancels.
|
||||
ConfirmDelete { target: DeleteTarget, label: String },
|
||||
ConfirmDelete {
|
||||
target: DeleteTarget,
|
||||
label: String,
|
||||
},
|
||||
/// Unsubscribe confirmation; progress and history are kept.
|
||||
ConfirmPodcastUnsubscribe {
|
||||
podcast_id: music_dht::podcast::PodcastId,
|
||||
@@ -795,11 +800,15 @@ pub enum Popup {
|
||||
max_scroll: std::cell::Cell<u16>,
|
||||
},
|
||||
/// Enabling network similarity reveals an embedding query to peers.
|
||||
SimilarityPrivacyConsent { enable_federation: bool },
|
||||
SimilarityPrivacyConsent {
|
||||
enable_federation: bool,
|
||||
},
|
||||
/// Derived data is safe to recreate but potentially expensive.
|
||||
ConfirmClearEmbeddings,
|
||||
/// Library-home filters. Cursor is kept for the next filters added here.
|
||||
LibraryFilters { cursor: usize },
|
||||
LibraryFilters {
|
||||
cursor: usize,
|
||||
},
|
||||
/// Track metadata viewer; left/right switch between selected tracks.
|
||||
TrackInfo {
|
||||
tracks: Vec<TrackItem>,
|
||||
@@ -822,7 +831,10 @@ pub enum Popup {
|
||||
input: LineEdit,
|
||||
},
|
||||
/// Wrapped read-only text (this peer's connection ticket).
|
||||
FedText { title: String, text: String },
|
||||
FedText {
|
||||
title: String,
|
||||
text: String,
|
||||
},
|
||||
/// Wrapped text that can be copied to the system clipboard.
|
||||
FedCopyText {
|
||||
title: String,
|
||||
@@ -834,10 +846,14 @@ pub enum Popup {
|
||||
/// The app loop temporarily leaves the alternate screen while this is
|
||||
/// active so terminal selection does not acquire TUI borders or hard
|
||||
/// line breaks.
|
||||
PlainText { text: String },
|
||||
PlainText {
|
||||
text: String,
|
||||
},
|
||||
/// The destination is already write-tested; Enter/y migrates managed
|
||||
/// files, while n changes only the destination for future downloads.
|
||||
ConfirmMusicDirectory { path: std::path::PathBuf },
|
||||
ConfirmMusicDirectory {
|
||||
path: std::path::PathBuf,
|
||||
},
|
||||
/// Incoming trusted-device pairing request.
|
||||
DevicePairing {
|
||||
request_id: String,
|
||||
@@ -848,13 +864,20 @@ pub enum Popup {
|
||||
requester_group_active_devices: usize,
|
||||
},
|
||||
/// Confirmation before revoking a trusted device.
|
||||
ConfirmDeviceRevoke { device_id: String, name: String },
|
||||
ConfirmDeviceRevoke {
|
||||
device_id: String,
|
||||
name: String,
|
||||
},
|
||||
/// Confirmation before this device leaves the trusted-device group.
|
||||
ConfirmDeviceLeave,
|
||||
/// Connected playback devices and their current role/status.
|
||||
ConnectedDevices { cursor: usize },
|
||||
ConnectedDevices {
|
||||
cursor: usize,
|
||||
},
|
||||
/// Qualified listening history from every trusted device.
|
||||
ListenHistory { cursor: usize },
|
||||
ListenHistory {
|
||||
cursor: usize,
|
||||
},
|
||||
/// Full federation, transport and device status details.
|
||||
FederationStatusDetails {
|
||||
focus: StatusDetailFocus,
|
||||
@@ -923,6 +946,7 @@ impl StatusDetailFocus {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FedInputField {
|
||||
MusicDirectory,
|
||||
PodcastRetention,
|
||||
SimilarityWorkers,
|
||||
SimilarityMinimumScore,
|
||||
SimilarityMaxTracksPerArtist,
|
||||
@@ -940,6 +964,7 @@ pub enum FedInputField {
|
||||
impl FedInputField {
|
||||
pub fn title(self) -> &'static str {
|
||||
match self {
|
||||
FedInputField::PodcastRetention => "Keep podcast downloads (days)",
|
||||
FedInputField::MusicDirectory => "Music save directory",
|
||||
FedInputField::SimilarityWorkers => "Similarity background workers",
|
||||
FedInputField::SimilarityMinimumScore => "Minimum similarity score",
|
||||
@@ -956,6 +981,9 @@ impl FedInputField {
|
||||
|
||||
pub fn help(self) -> &'static str {
|
||||
match self {
|
||||
FedInputField::PodcastRetention => {
|
||||
"Enter 1–36500 days. Downloads expire from the time they finish. Default: 30 days. Only this device is affected."
|
||||
}
|
||||
FedInputField::MusicDirectory => {
|
||||
"Federated tracks saved to your library use this directory. The directory is checked for write access before anything changes."
|
||||
}
|
||||
@@ -1047,6 +1075,7 @@ pub enum SettingsRow {
|
||||
CheckUpdate,
|
||||
InstallUpdate,
|
||||
MusicDirectory,
|
||||
PodcastRetention,
|
||||
Similarity(SimilarityRow),
|
||||
Federation(FedRow),
|
||||
StatusDetails,
|
||||
@@ -1188,6 +1217,7 @@ pub fn device_status_order(state: &AppState) -> Vec<usize> {
|
||||
pub fn additional_settings_rows(state: &AppState) -> Vec<SettingsRow> {
|
||||
let mut rows = vec![
|
||||
SettingsRow::MusicDirectory,
|
||||
SettingsRow::PodcastRetention,
|
||||
SettingsRow::CheckUpdate,
|
||||
SettingsRow::InstallUpdate,
|
||||
];
|
||||
@@ -1958,7 +1988,11 @@ pub struct AppState {
|
||||
/// Root for music permanently downloaded from federation peers.
|
||||
pub music_dir: std::path::PathBuf,
|
||||
pub music_dir_changing: bool,
|
||||
pub podcast_retention_days: u32,
|
||||
pub podcast_downloads: std::collections::HashSet<String>,
|
||||
pub podcast_downloading: std::collections::HashSet<String>,
|
||||
pub player: PlayerBar,
|
||||
pub(crate) lyrics: super::lyrics::Playback,
|
||||
pub device_playback: DevicePlaybackState,
|
||||
pub jam: crate::jam::JamStatus,
|
||||
pub visualizer: crate::visualizer::VisualizerState,
|
||||
|
||||
@@ -112,6 +112,8 @@ pub enum Effect {
|
||||
LoadListenHistory,
|
||||
/// Reload the subscribed podcasts with their fetch state.
|
||||
PodcastsReload,
|
||||
PodcastDownload(music_dht::podcast::PodcastEpisodeRef),
|
||||
SavePodcastSettings,
|
||||
/// Load the season groups of a podcast.
|
||||
PodcastLoadSeasons(music_dht::podcast::PodcastId),
|
||||
/// Load one page of episodes; `seq` drops stale results.
|
||||
@@ -389,6 +391,21 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
|
||||
}
|
||||
None
|
||||
}
|
||||
Action::OpenLyrics => {
|
||||
if let Some(track) = selected_track(state).filter(|track| !track.is_podcast()) {
|
||||
state.popup = Some(super::state::Popup::Lyrics(super::lyrics::Reader::preview(
|
||||
track,
|
||||
)));
|
||||
} else {
|
||||
state.status_message = Some("Select a music track to view its lyrics".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
Action::OpenCurrentLyrics => {
|
||||
state.lyrics.refresh_local();
|
||||
state.popup = Some(super::state::Popup::Lyrics(super::lyrics::Reader::default()));
|
||||
None
|
||||
}
|
||||
Action::CycleVisualizerMode => {
|
||||
if state.visualizer.active {
|
||||
if let Err(err) = state.visualizer.cycle_mode() {
|
||||
@@ -3067,6 +3084,13 @@ fn select_settings_row(state: &mut AppState, row: super::state::SettingsRow) ->
|
||||
state.updater.message = "Downloading update...".into();
|
||||
Some(Effect::InstallUpdate(update))
|
||||
}
|
||||
SettingsRow::PodcastRetention => {
|
||||
state.popup = Some(Popup::FedInput {
|
||||
field: FedInputField::PodcastRetention,
|
||||
input: crate::app::input::LineEdit::new(state.podcast_retention_days.to_string()),
|
||||
});
|
||||
None
|
||||
}
|
||||
SettingsRow::MusicDirectory => {
|
||||
if state.music_dir_changing {
|
||||
state.status_message = Some("music directory change is already running".into());
|
||||
|
||||
@@ -54,6 +54,31 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option<Option<Eff
|
||||
open_add(state);
|
||||
None
|
||||
}
|
||||
Action::DownloadSelected => {
|
||||
if !store_ready(state) {
|
||||
return Some(None);
|
||||
}
|
||||
let Some(track) = state.podcasts.selected_episode_track() else {
|
||||
return Some(None);
|
||||
};
|
||||
let episode = track.podcast_episode_ref().unwrap().clone();
|
||||
if state
|
||||
.podcast_downloads
|
||||
.contains(&crate::podcasts::offline::key(episode.episode_id.as_str()))
|
||||
{
|
||||
state.status_message =
|
||||
Some("podcasts: episode is already available offline".into());
|
||||
return Some(None);
|
||||
}
|
||||
if !state
|
||||
.podcast_downloading
|
||||
.insert(episode.episode_id.as_str().to_owned())
|
||||
{
|
||||
return Some(None);
|
||||
}
|
||||
state.status_message = Some("podcasts: downloading episode…".into());
|
||||
Some(Effect::PodcastDownload(episode))
|
||||
}
|
||||
Action::RefreshPodcast => refresh_current(state),
|
||||
Action::RefreshAllPodcasts => refresh_all(state),
|
||||
Action::CycleEpisodeSort => cycle_sort(state),
|
||||
|
||||
@@ -2827,3 +2827,76 @@ mod podcast_discovery {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn episode_download_requires_explicit_action_and_deduplicates_requests() {
|
||||
use crate::app::podcast_fixtures as fx;
|
||||
let mut state = fx::with_episodes(
|
||||
fx::ready_state(vec![fx::row("Show", 1, 1, 0)]),
|
||||
vec![fx::episode(1, "Episode", None)],
|
||||
);
|
||||
assert!(state.podcast_downloading.is_empty());
|
||||
let expected = state
|
||||
.podcasts
|
||||
.selected_episode_track()
|
||||
.unwrap()
|
||||
.podcast_episode_ref()
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(
|
||||
update(&mut state, Action::DownloadSelected),
|
||||
Some(Effect::PodcastDownload(expected.clone()))
|
||||
);
|
||||
assert_eq!(update(&mut state, Action::DownloadSelected), None);
|
||||
assert_eq!(state.podcast_downloading.len(), 1);
|
||||
state.podcast_downloading.clear();
|
||||
state
|
||||
.podcast_downloads
|
||||
.insert(crate::podcasts::offline::key(expected.episode_id.as_str()));
|
||||
assert_eq!(update(&mut state, Action::DownloadSelected), None);
|
||||
assert!(state.podcast_downloading.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn podcast_retention_opens_a_numeric_editor_in_additional_settings() {
|
||||
use crate::app::state::{FedInputField, Popup, SettingsRow, additional_settings_rows};
|
||||
let mut state = AppState {
|
||||
additional_settings_open: true,
|
||||
podcast_retention_days: 30,
|
||||
..Default::default()
|
||||
};
|
||||
state.additional_settings_cursor = additional_settings_rows(&state)
|
||||
.iter()
|
||||
.position(|row| *row == SettingsRow::PodcastRetention)
|
||||
.unwrap();
|
||||
assert_eq!(update(&mut state, Action::Select), None);
|
||||
assert!(matches!(
|
||||
state.popup,
|
||||
Some(Popup::FedInput {
|
||||
field: FedInputField::PodcastRetention,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lyrics_preview_uses_queue_cursor_and_current_action_follows_playback() {
|
||||
let mut state = AppState {
|
||||
active_tab: Tab::Queue,
|
||||
..Default::default()
|
||||
};
|
||||
state.player.current = Some(test_track(1));
|
||||
state.player.queue = vec![test_track(1), test_track(2)];
|
||||
state.queue_tab.cursor = 1;
|
||||
update(&mut state, Action::OpenLyrics);
|
||||
let Some(crate::app::state::Popup::Lyrics(reader)) = &state.popup else {
|
||||
panic!("expected lyrics preview")
|
||||
};
|
||||
assert_eq!(reader.preview.as_ref().unwrap().0.id, 2);
|
||||
update(&mut state, Action::OpenCurrentLyrics);
|
||||
let Some(crate::app::state::Popup::Lyrics(reader)) = &state.popup else {
|
||||
panic!("expected now-playing lyrics")
|
||||
};
|
||||
assert!(reader.preview.is_none());
|
||||
assert_eq!(state.player.current.as_ref().unwrap().id, 1);
|
||||
}
|
||||
@@ -137,7 +137,11 @@ command = "MoveLeft"
|
||||
|
||||
[[keymaps]]
|
||||
key_sequence = "l"
|
||||
command = "MoveRight"
|
||||
command = "OpenLyrics"
|
||||
|
||||
[[keymaps]]
|
||||
key_sequence = "ctrl-l"
|
||||
command = "OpenCurrentLyrics"
|
||||
|
||||
[[keymaps]]
|
||||
key_sequence = "right"
|
||||
|
||||
@@ -456,6 +456,19 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lyrics_keys_distinguish_selected_and_playing_track() {
|
||||
let mut km = keymap_from(DEFAULT_KEYMAP);
|
||||
assert_eq!(
|
||||
km.resolve(key!(l), KeyContext::Library),
|
||||
KeyResolution::Action(Action::OpenLyrics)
|
||||
);
|
||||
assert_eq!(
|
||||
km.resolve(key!(ctrl - l), KeyContext::Library),
|
||||
KeyResolution::Action(Action::OpenCurrentLyrics)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chord_sequence_resolves() {
|
||||
let mut km = keymap_from(DEFAULT_KEYMAP);
|
||||
|
||||
@@ -50,6 +50,8 @@ impl Default for SimilaritySettings {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AppSettings {
|
||||
#[serde(default = "default_podcast_retention_days")]
|
||||
pub podcast_retention_days: u32,
|
||||
#[serde(default)]
|
||||
pub playback: music_dht::playback::Config,
|
||||
#[serde(default = "default_volume")]
|
||||
@@ -66,6 +68,7 @@ pub struct AppSettings {
|
||||
impl Default for AppSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
podcast_retention_days: 30,
|
||||
playback: music_dht::playback::Config::default(),
|
||||
volume: default_volume(),
|
||||
library: LibraryFilters::default(),
|
||||
@@ -77,6 +80,7 @@ impl Default for AppSettings {
|
||||
|
||||
impl AppSettings {
|
||||
pub fn normalized(mut self) -> Self {
|
||||
self.podcast_retention_days = self.podcast_retention_days.clamp(1, 36500);
|
||||
self.volume = self.volume.min(100);
|
||||
if self.music_dir.as_os_str().is_empty() {
|
||||
self.music_dir = default_music_dir();
|
||||
@@ -97,6 +101,10 @@ impl AppSettings {
|
||||
}
|
||||
}
|
||||
|
||||
fn default_podcast_retention_days() -> u32 {
|
||||
30
|
||||
}
|
||||
|
||||
fn default_volume() -> u8 {
|
||||
80
|
||||
}
|
||||
@@ -186,6 +194,7 @@ hide_featured_only = true
|
||||
let settings = settings.normalized();
|
||||
|
||||
assert_eq!(settings.volume, 100);
|
||||
assert_eq!(settings.podcast_retention_days, 30);
|
||||
assert!(settings.library.hide_featured_only);
|
||||
assert_eq!(settings.library.source_mode, LibrarySourceMode::Global);
|
||||
assert_eq!(settings.music_dir, default_music_dir());
|
||||
|
||||
@@ -67,7 +67,11 @@ pub struct ObservedVersions {
|
||||
/// peers never dial an overlay that failed to open here.
|
||||
fn local_manifest(podcast_dht: bool) -> CapabilityManifest {
|
||||
let manifest = CapabilityManifest::frid("furumi", env!("CARGO_PKG_VERSION"))
|
||||
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION);
|
||||
.with_protocol("audio", super::audio::AUDIO_PROTOCOL_VERSION)
|
||||
.with_protocol(
|
||||
music_dht::lyrics::LYRICS_ID,
|
||||
music_dht::lyrics::LYRICS_PROTOCOL_VERSION,
|
||||
);
|
||||
if podcast_dht {
|
||||
manifest.with_podcast_dht()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Optional lyrics streams use audio content identities, independent of the catalog schema.
|
||||
use super::Federation;
|
||||
use crate::library::Library;
|
||||
use anyhow::{Context, Result};
|
||||
use futures_util::{StreamExt, stream};
|
||||
use music_dht::lyrics::{self, LyricsRequest, LyricsResponse, LyricsVersion};
|
||||
use music_dht::{ByteStream, EndpointId, MusicDhtService, StreamAcceptor};
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
const PEER_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
|
||||
impl Federation {
|
||||
pub(crate) async fn find_lyrics(
|
||||
&self,
|
||||
content_id: &str,
|
||||
preferred: Option<&str>,
|
||||
mut on_versions: impl FnMut(Vec<LyricsVersion>),
|
||||
) -> Result<()> {
|
||||
let request = LyricsRequest::new(content_id)?;
|
||||
let service = self.service().await?;
|
||||
let own = service.endpoint_id();
|
||||
|
||||
// Start with the audio source while content discovery looks for other copies.
|
||||
let preferred = preferred
|
||||
.and_then(|id| id.parse::<EndpointId>().ok())
|
||||
.filter(|id| *id != own);
|
||||
let direct = async {
|
||||
if let Some(peer) = preferred {
|
||||
fetch(&service, peer, &request).await.ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let discovery = tokio::time::timeout(PEER_TIMEOUT, service.search_content_id(content_id));
|
||||
tokio::pin!(direct, discovery);
|
||||
|
||||
let found = tokio::select! {
|
||||
result = &mut direct => {
|
||||
if let Some(versions) = result {
|
||||
on_versions(versions);
|
||||
}
|
||||
discovery.await
|
||||
}
|
||||
result = &mut discovery => {
|
||||
if let Some(versions) = direct.await {
|
||||
on_versions(versions);
|
||||
}
|
||||
result
|
||||
}
|
||||
};
|
||||
|
||||
let mut seen = HashSet::from([own]);
|
||||
seen.extend(preferred);
|
||||
let owners = found
|
||||
.ok()
|
||||
.and_then(Result::ok)
|
||||
.into_iter()
|
||||
.flat_map(|outcome| {
|
||||
outcome
|
||||
.local_results
|
||||
.into_iter()
|
||||
.chain(outcome.network_results)
|
||||
})
|
||||
.filter(|item| {
|
||||
item.kind == music_dht::ItemKind::Track
|
||||
&& item.content_id.as_deref() == Some(content_id)
|
||||
})
|
||||
.map(|item| item.owner);
|
||||
|
||||
// Connected peers can also have newly stored copies that aren't indexed yet.
|
||||
let candidates = owners
|
||||
.chain(service.connected_peers())
|
||||
.filter(|peer| seen.insert(*peer))
|
||||
.take(16);
|
||||
let mut responses = stream::iter(candidates)
|
||||
.map(|peer| fetch(&service, peer, &request))
|
||||
.buffer_unordered(6);
|
||||
while let Some(result) = responses.next().await {
|
||||
match result {
|
||||
Ok(versions) => on_versions(versions),
|
||||
Err(error) => {
|
||||
tracing::trace!(error = %format!("{error:#}"), "peer lyrics unavailable")
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch(
|
||||
service: &MusicDhtService,
|
||||
peer: EndpointId,
|
||||
request: &LyricsRequest,
|
||||
) -> Result<Vec<LyricsVersion>> {
|
||||
tokio::time::timeout(PEER_TIMEOUT, async {
|
||||
let mut retried = false;
|
||||
loop {
|
||||
let mut stream = service
|
||||
.open_stream(peer, lyrics::LYRICS_ALPN)
|
||||
.await
|
||||
.context("opening peer lyrics stream")?;
|
||||
lyrics::write_request(&mut stream, request).await?;
|
||||
stream.send.finish()?;
|
||||
match lyrics::read_response_from(&mut stream.recv).await {
|
||||
Ok(response) => {
|
||||
anyhow::ensure!(
|
||||
response.content_id == request.content_id,
|
||||
"lyrics response content identity mismatch"
|
||||
);
|
||||
return Ok(response.versions);
|
||||
}
|
||||
Err(music_dht::MusicDhtError::Network(_)) if !retried => retried = true,
|
||||
Err(error) => return Err(error).context("reading peer lyrics response"),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
pub(super) async fn serve(mut acceptor: StreamAcceptor, library: Arc<Library>) {
|
||||
let limit = Arc::new(tokio::sync::Semaphore::new(16));
|
||||
while let Some(stream) = acceptor.accept().await {
|
||||
let Ok(permit) = Arc::clone(&limit).try_acquire_owned() else {
|
||||
continue;
|
||||
};
|
||||
let library = Arc::clone(&library);
|
||||
tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
match tokio::time::timeout(Duration::from_secs(12), serve_one(stream, library)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => tracing::debug!(%error, "could not serve lyrics"),
|
||||
Err(_) => tracing::debug!("lyrics stream timed out"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_one(mut stream: ByteStream, library: Arc<Library>) -> Result<()> {
|
||||
let request = lyrics::read_request_from(&mut stream.recv).await?;
|
||||
let content_id = request.content_id.clone();
|
||||
let versions = tokio::task::spawn_blocking(move || -> Result<_> {
|
||||
let local = library.track_by_content_id(&content_id)?;
|
||||
if local.is_some_and(|track| std::path::Path::new(&track.file_path).is_file()) {
|
||||
Ok(library.lyrics(&content_id)?.versions)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
// JSON can be larger than the stored UTF-8 text because of escapes.
|
||||
let mut response = LyricsResponse {
|
||||
version: lyrics::LYRICS_PROTOCOL_VERSION,
|
||||
content_id: request.content_id,
|
||||
versions,
|
||||
};
|
||||
// Leave space for the bounded envelope and the comma before each entry.
|
||||
let mut remaining = lyrics::MAX_LYRICS_RESPONSE_BYTES - 256;
|
||||
response.versions.retain(|version| {
|
||||
let Ok(encoded) = serde_json::to_vec(version) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = remaining.checked_sub(encoded.len() + 1) else {
|
||||
return false;
|
||||
};
|
||||
remaining = rest;
|
||||
true
|
||||
});
|
||||
lyrics::write_response(&mut stream, &response).await?;
|
||||
stream.send.finish()?;
|
||||
// ByteStream also owns its connection. Keep it alive through FIN delivery.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), stream.send.stopped()).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::library::import::{TrackImport, upsert_track};
|
||||
use music_dht::{MusicDhtConfig, NetworkId};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn localhost_lyrics_stream_serves_only_saved_content_and_all_versions() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let network = NetworkId::from_name(&format!("lyrics-test-{}", temp.path().display()));
|
||||
let start = |name| {
|
||||
let dir = temp.path().join(name);
|
||||
async move {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (service, mut events) = MusicDhtService::start(
|
||||
MusicDhtConfig::builder()
|
||||
.data_dir(dir)
|
||||
.network_id(network)
|
||||
.schema_independent_stream_protocol(lyrics::LYRICS_ALPN)
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::spawn(async move { while events.recv().await.is_some() {} });
|
||||
service
|
||||
}
|
||||
};
|
||||
let (server, client) = tokio::join!(start("server"), start("client"));
|
||||
let library = Arc::new(Library::open(&temp.path().join("library.db")).unwrap());
|
||||
let path = temp.path().join("track.flac");
|
||||
std::fs::write(&path, b"immutable music bytes").unwrap();
|
||||
let track_id = upsert_track(
|
||||
&library,
|
||||
&TrackImport {
|
||||
file_path: path.to_string_lossy().into_owned(),
|
||||
title: "Track".into(),
|
||||
artists: vec!["Artist".into()],
|
||||
album_artists: vec!["Artist".into()],
|
||||
featured_artists: vec![],
|
||||
release_title: "Release".into(),
|
||||
release_type: None,
|
||||
year: None,
|
||||
track_number: None,
|
||||
disc_number: None,
|
||||
duration_seconds: 5.0,
|
||||
audio_format: None,
|
||||
audio_bitrate: None,
|
||||
audio_sample_rate: None,
|
||||
audio_bit_depth: None,
|
||||
file_size_bytes: None,
|
||||
cover: None,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.0;
|
||||
let id = library.track_content_id_by_id(track_id).unwrap().unwrap();
|
||||
library
|
||||
.edit_lyrics(
|
||||
track_id,
|
||||
&id,
|
||||
None,
|
||||
Some(crate::lyrics::manual_version("Plain", "Words").unwrap()),
|
||||
)
|
||||
.unwrap();
|
||||
library
|
||||
.edit_lyrics(
|
||||
track_id,
|
||||
&id,
|
||||
None,
|
||||
Some(crate::lyrics::manual_version("Timed", "[00:01]Words").unwrap()),
|
||||
)
|
||||
.unwrap();
|
||||
let task = tokio::spawn(serve(
|
||||
server.stream_acceptor(lyrics::LYRICS_ALPN).unwrap(),
|
||||
library,
|
||||
));
|
||||
client
|
||||
.connect(server.ticket().await.unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let versions = fetch(
|
||||
&client,
|
||||
server.endpoint_id(),
|
||||
&LyricsRequest::new(&id).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(versions.len(), 2);
|
||||
assert_eq!(versions[0].synced_lrc.as_deref(), Some("[00:01]Words"));
|
||||
assert_eq!(versions[1].plain_text.as_deref(), Some("Words"));
|
||||
std::fs::remove_file(path).unwrap();
|
||||
assert!(
|
||||
fetch(
|
||||
&client,
|
||||
server.endpoint_id(),
|
||||
&LyricsRequest::new(id).unwrap()
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
task.abort();
|
||||
server.shutdown().await.unwrap();
|
||||
client.shutdown().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
mod audio;
|
||||
mod capabilities;
|
||||
pub mod catalog;
|
||||
mod lyrics;
|
||||
mod similarity;
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -780,6 +781,7 @@ impl Federation {
|
||||
.schema_independent_stream_protocol(PODCAST_DHT_ALPN)
|
||||
// Informational application/protocol versions.
|
||||
.schema_independent_stream_protocol(capabilities::CAPABILITIES_ALPN)
|
||||
.schema_independent_stream_protocol(music_dht::lyrics::LYRICS_ALPN)
|
||||
.build()
|
||||
.map_err(|err| anyhow::anyhow!("invalid federation config: {err}"))?;
|
||||
let (service, mut events) = MusicDhtService::start(config)
|
||||
@@ -905,11 +907,15 @@ impl Federation {
|
||||
podcast_dht.clone(),
|
||||
));
|
||||
|
||||
let lyrics_acceptor = service.stream_acceptor(music_dht::lyrics::LYRICS_ALPN)?;
|
||||
let lyrics_task = tokio::spawn(lyrics::serve(lyrics_acceptor, Arc::clone(&self.library)));
|
||||
|
||||
let mut tasks = podcast_dht_tasks;
|
||||
tasks.extend([
|
||||
event_task,
|
||||
sync_task,
|
||||
audio_task,
|
||||
lyrics_task,
|
||||
catalog_task,
|
||||
similarity_task,
|
||||
device_sync_task,
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
//! Content-addressed lyrics and the playback timeline shared by the UI and scripts.
|
||||
pub(crate) use crate::library::lyrics::{SavedLyrics, identity, merge};
|
||||
use music_dht::lyrics::LyricsVersion;
|
||||
|
||||
pub(crate) fn clean_text(text: &str) -> String {
|
||||
text.replace("\r\n", "\n")
|
||||
.replace('\r', "\n")
|
||||
.chars()
|
||||
.filter_map(|c| match c {
|
||||
'\t' => Some(' '),
|
||||
'\n' => Some('\n'),
|
||||
c if !c.is_control() => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Document {
|
||||
pub lines: Vec<String>,
|
||||
times: Vec<u64>,
|
||||
pub instrumental: bool,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn new(version: &LyricsVersion) -> Self {
|
||||
let timed = version
|
||||
.synced_lrc
|
||||
.as_deref()
|
||||
.map(parse_lrc)
|
||||
.unwrap_or_default();
|
||||
let (mut times, lines): (Vec<_>, Vec<_>) = timed.into_iter().unzip();
|
||||
let lines = if times.is_empty() {
|
||||
let text = version
|
||||
.plain_text
|
||||
.as_deref()
|
||||
.or(version.synced_lrc.as_deref());
|
||||
text.map(clean_text)
|
||||
.map(|text| text.lines().map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
// Some LRC releases split a duet over two lines with the same timestamp.
|
||||
let mut combined: Vec<String> = Vec::new();
|
||||
let mut previous = None;
|
||||
let mut keep = Vec::new();
|
||||
for (time, line) in times.into_iter().zip(lines) {
|
||||
if previous == Some(time) {
|
||||
if let Some(last) = combined.last_mut() {
|
||||
last.push_str(" / ");
|
||||
last.push_str(&line);
|
||||
}
|
||||
} else {
|
||||
keep.push(time);
|
||||
combined.push(line);
|
||||
previous = Some(time);
|
||||
}
|
||||
}
|
||||
times = keep;
|
||||
combined
|
||||
};
|
||||
Self {
|
||||
lines,
|
||||
times,
|
||||
instrumental: version.instrumental,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timed(&self) -> bool {
|
||||
!self.times.is_empty()
|
||||
}
|
||||
|
||||
pub fn line_at(&self, position: f64) -> Option<usize> {
|
||||
let millis = (position * 1000.0) as u64;
|
||||
self.times
|
||||
.partition_point(|&time| time <= millis)
|
||||
.checked_sub(1)
|
||||
}
|
||||
|
||||
pub fn time(&self, index: usize) -> Option<f64> {
|
||||
self.times.get(index).map(|&time| time as f64 / 1000.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_lrc(value: &str) -> Vec<(u64, String)> {
|
||||
let offset = value
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
line.trim()
|
||||
.trim_start_matches('\u{feff}')
|
||||
.strip_prefix("[offset:")?
|
||||
.strip_suffix(']')?
|
||||
.trim()
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.clamp(-3_600_000, 3_600_000);
|
||||
let mut lines = Vec::new();
|
||||
for line in value.lines() {
|
||||
let mut rest = line.trim().trim_start_matches('\u{feff}');
|
||||
let mut times = Vec::new();
|
||||
while let Some((tag, tail)) = rest.strip_prefix('[').and_then(|s| s.split_once(']')) {
|
||||
let Some((minutes, seconds)) = tag.split_once(':') else {
|
||||
break;
|
||||
};
|
||||
let (Ok(minutes), Ok(seconds)) = (minutes.parse::<u32>(), seconds.parse::<f64>())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if minutes > 1440 || !(0.0..60.0).contains(&seconds) {
|
||||
break;
|
||||
}
|
||||
let ms = ((f64::from(minutes) * 60.0 + seconds) * 1000.0).round() as i64;
|
||||
times.push((ms + offset).max(0) as u64);
|
||||
rest = tail;
|
||||
}
|
||||
if !times.is_empty() {
|
||||
let line = clean_text(rest.trim());
|
||||
lines.extend(times.into_iter().map(|time| (time, line.clone())));
|
||||
}
|
||||
}
|
||||
lines.sort_by_key(|(time, _)| *time);
|
||||
lines
|
||||
}
|
||||
|
||||
pub(crate) fn manual_version(label: &str, text: &str) -> anyhow::Result<LyricsVersion> {
|
||||
let label = clean_text(label);
|
||||
let text = clean_text(text);
|
||||
anyhow::ensure!(
|
||||
!text.trim().is_empty() && text.len() <= music_dht::lyrics::MAX_LYRICS_TEXT_BYTES,
|
||||
"Enter lyrics up to 256 KiB"
|
||||
);
|
||||
let timed = !parse_lrc(&text).is_empty();
|
||||
let mut version = LyricsVersion {
|
||||
id: "manual".into(),
|
||||
label: if label.trim().is_empty() {
|
||||
"Manual".into()
|
||||
} else {
|
||||
label.trim().into()
|
||||
},
|
||||
source: "manual".into(),
|
||||
source_id: None,
|
||||
language: None,
|
||||
plain_text: (!timed).then(|| text.clone()),
|
||||
synced_lrc: timed.then_some(text),
|
||||
instrumental: false,
|
||||
};
|
||||
version.id = identity(&version);
|
||||
version.validate()?;
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn lrc_handles_offsets_repeated_timestamps_and_seeks() {
|
||||
let version = manual_version(
|
||||
"Duet",
|
||||
"[offset:-500]\n[00:02][00:08]Hello\n[00:02]Hi\n[00:04.25]\n[00:05]Bye",
|
||||
)
|
||||
.unwrap();
|
||||
let doc = Document::new(&version);
|
||||
assert_eq!(doc.lines, ["Hello / Hi", "", "Bye", "Hello"]);
|
||||
assert_eq!(doc.line_at(1.49), None);
|
||||
assert_eq!(doc.line_at(1.5), Some(0));
|
||||
assert_eq!(doc.line_at(8.0), Some(3));
|
||||
assert_eq!(doc.line_at(3.8), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_are_deduplicated_by_representations() {
|
||||
let first = manual_version("One", "Words").unwrap();
|
||||
let second = manual_version("Another label", "Words").unwrap();
|
||||
let timed = manual_version("Timed", "[00:01]Words").unwrap();
|
||||
let mut versions = vec![first.clone()];
|
||||
merge(&mut versions, [second, timed], &HashSet::new());
|
||||
assert_eq!(versions.len(), 2);
|
||||
assert_eq!(versions[0], first);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod devices;
|
||||
mod federation;
|
||||
mod jam;
|
||||
mod library;
|
||||
mod lyrics;
|
||||
mod media;
|
||||
mod player;
|
||||
mod podcasts;
|
||||
|
||||
+8
-40
@@ -6,6 +6,7 @@
|
||||
|
||||
mod analyzer;
|
||||
mod opus;
|
||||
mod output;
|
||||
mod spectrum;
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -13,7 +14,8 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
|
||||
use std::time::Duration;
|
||||
|
||||
use rodio::{Decoder, DeviceSinkBuilder, Player, Source, stream::MixerDeviceSink};
|
||||
use output::Output;
|
||||
use rodio::{Decoder, Source};
|
||||
|
||||
pub use analyzer::AudioAnalysisSnapshot;
|
||||
pub use spectrum::{BAND_CENTERS_HZ, FLOOR_DB};
|
||||
@@ -266,12 +268,6 @@ struct Generations {
|
||||
start_paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
struct Output {
|
||||
/// Keeps the audio device open; dropping it stops the mixer.
|
||||
_device: MixerDeviceSink,
|
||||
player: Player,
|
||||
}
|
||||
|
||||
/// Audio-thread state besides the output device.
|
||||
struct Playing {
|
||||
track_loaded: bool,
|
||||
@@ -395,9 +391,7 @@ fn handle(
|
||||
seekable,
|
||||
volume,
|
||||
} => {
|
||||
let Some(out) = ensure_output(output, on_event) else {
|
||||
return;
|
||||
};
|
||||
let out = output.get_or_insert_with(Output::new);
|
||||
match decode_source(reader, byte_len, mime_type.as_deref(), seekable) {
|
||||
Ok(source) => start_source(out, source, volume, false, shared, on_event),
|
||||
Err(err) => {
|
||||
@@ -414,9 +408,7 @@ fn handle(
|
||||
start,
|
||||
generation: _,
|
||||
} => {
|
||||
let Some(out) = ensure_output(output, on_event) else {
|
||||
return;
|
||||
};
|
||||
let out = output.get_or_insert_with(Output::new);
|
||||
let paused = start_paused.load(Ordering::SeqCst);
|
||||
start_source(out, source, volume, paused, shared, on_event);
|
||||
playing.track_loaded = true;
|
||||
@@ -461,7 +453,7 @@ fn handle(
|
||||
}
|
||||
Command::Seek(position) => {
|
||||
let result = match output {
|
||||
Some(out) => out.player.try_seek(position).map_err(|err| err.to_string()),
|
||||
Some(out) => out.seek(position),
|
||||
None => Err("nothing is playing".to_string()),
|
||||
};
|
||||
match &result {
|
||||
@@ -484,33 +476,9 @@ fn handle(
|
||||
}
|
||||
}
|
||||
|
||||
/// The device is opened lazily on first playback so the app works on
|
||||
/// machines with no audio output until you actually press play.
|
||||
fn ensure_output<'a>(
|
||||
output: &'a mut Option<Output>,
|
||||
on_event: &impl Fn(PlayerEvent),
|
||||
) -> Option<&'a Output> {
|
||||
if output.is_none() {
|
||||
match DeviceSinkBuilder::open_default_sink() {
|
||||
Ok(device) => {
|
||||
let player = Player::connect_new(device.mixer());
|
||||
*output = Some(Output {
|
||||
_device: device,
|
||||
player,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
on_event(PlayerEvent::Failed(format!("no audio device: {err}")));
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
output.as_ref()
|
||||
}
|
||||
|
||||
/// Replace whatever is playing with `source`.
|
||||
fn start_source(
|
||||
out: &Output,
|
||||
out: &mut Output,
|
||||
source: DecodedSource,
|
||||
volume: f32,
|
||||
paused: bool,
|
||||
@@ -518,7 +486,7 @@ fn start_source(
|
||||
on_event: &impl Fn(PlayerEvent),
|
||||
) {
|
||||
shared.analysis.clear();
|
||||
out.player.stop();
|
||||
out.reset_player();
|
||||
out.player.set_volume(volume);
|
||||
out.player.append(analyzer::AnalyzedSource::new(
|
||||
source,
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Hardware output is replaceable. Rodio's source queue and playback controls
|
||||
//! outlive the hardware sink, so unplugging never finishes or reopens a track.
|
||||
use std::num::{NonZeroU16, NonZeroU32};
|
||||
use std::sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},
|
||||
mpsc::{self, RecvTimeoutError},
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rodio::{
|
||||
DeviceSinkBuilder, Player, Source,
|
||||
cpal::{
|
||||
self,
|
||||
traits::{DeviceTrait, HostTrait},
|
||||
},
|
||||
queue::SourcesQueueOutput,
|
||||
source::UniformSourceIterator,
|
||||
stream::MixerDeviceSink,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct AudioFormat {
|
||||
channels: NonZeroU16,
|
||||
sample_rate: NonZeroU32,
|
||||
}
|
||||
|
||||
impl AudioFormat {
|
||||
const FALLBACK: Self = Self {
|
||||
channels: NonZeroU16::new(2).unwrap(),
|
||||
sample_rate: NonZeroU32::new(48_000).unwrap(),
|
||||
};
|
||||
|
||||
fn current_default() -> Self {
|
||||
let config = cpal::default_host()
|
||||
.default_output_device()
|
||||
.and_then(|device| device.default_output_config().ok());
|
||||
config
|
||||
.and_then(|config| {
|
||||
Some(Self {
|
||||
channels: NonZeroU16::new(config.channels())?,
|
||||
sample_rate: NonZeroU32::new(config.sample_rate())?,
|
||||
})
|
||||
})
|
||||
.unwrap_or(Self::FALLBACK)
|
||||
}
|
||||
|
||||
fn queue(self, input: SourcesQueueOutput) -> UniformSourceIterator<SourcesQueueOutput> {
|
||||
UniformSourceIterator::new(input, self.channels, self.sample_rate)
|
||||
}
|
||||
|
||||
fn aligned_samples(self, suggested: usize) -> usize {
|
||||
let channels = usize::from(self.channels.get());
|
||||
(suggested / channels).max(1) * channels
|
||||
}
|
||||
}
|
||||
const CHUNK: usize = 64;
|
||||
const PROBE_INTERVAL: Duration = Duration::from_millis(500);
|
||||
const STALL_TIME: Duration = Duration::from_secs(2);
|
||||
|
||||
struct Audio {
|
||||
format: AudioFormat,
|
||||
queue: Mutex<UniformSourceIterator<SourcesQueueOutput>>,
|
||||
// Rodio services synchronous seek orders when the source is consumed.
|
||||
// Without hardware, the monitor can advance a muted buffer to service one.
|
||||
seeking: AtomicBool,
|
||||
samples: AtomicU64,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
|
||||
pub(super) struct Output {
|
||||
// Keeping the sender alive keeps the monitor active.
|
||||
_monitor: mpsc::Sender<()>,
|
||||
audio: Arc<Audio>,
|
||||
pub(super) player: Player,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
pub fn new() -> Self {
|
||||
let (player, queue) = Player::new();
|
||||
// Keep the starting device's native format in steady state. A
|
||||
// replacement sink resamples only when its format differs.
|
||||
let format = AudioFormat::current_default();
|
||||
let audio = Arc::new(Audio {
|
||||
format,
|
||||
queue: Mutex::new(format.queue(queue)),
|
||||
seeking: AtomicBool::new(false),
|
||||
samples: AtomicU64::new(0),
|
||||
generation: AtomicU64::new(0),
|
||||
});
|
||||
let (monitor, rx) = mpsc::channel();
|
||||
let monitor_audio = Arc::clone(&audio);
|
||||
std::thread::Builder::new()
|
||||
.name("audio-output".into())
|
||||
.spawn(move || watch_outputs(rx, monitor_audio))
|
||||
.expect("spawning the audio output monitor cannot fail");
|
||||
Self {
|
||||
_monitor: monitor,
|
||||
audio,
|
||||
player,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset_player(&mut self) {
|
||||
// Rodio waits for the previous callback when appending after stop.
|
||||
// Replace the queue instead, so starting another track can never wait
|
||||
// for a callback from a disconnected device.
|
||||
let (player, queue) = Player::new();
|
||||
*self
|
||||
.audio
|
||||
.queue
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = self.audio.format.queue(queue);
|
||||
self.audio.generation.fetch_add(1, Relaxed);
|
||||
self.player = player;
|
||||
}
|
||||
|
||||
pub fn seek(&self, position: Duration) -> Result<(), String> {
|
||||
self.audio.seeking.store(true, Relaxed);
|
||||
let result = self
|
||||
.player
|
||||
.try_seek(position)
|
||||
.map_err(|error| error.to_string());
|
||||
self.audio.seeking.store(false, Relaxed);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
struct DeviceOutput {
|
||||
id: Option<cpal::DeviceId>,
|
||||
_sink: MixerDeviceSink,
|
||||
failed: Arc<AtomicBool>,
|
||||
last_samples: u64,
|
||||
last_callback: Instant,
|
||||
}
|
||||
|
||||
impl DeviceOutput {
|
||||
fn open(
|
||||
device: cpal::Device,
|
||||
id: Option<cpal::DeviceId>,
|
||||
audio: &Arc<Audio>,
|
||||
) -> Result<Self, rodio::stream::DeviceSinkError> {
|
||||
let failed = Arc::new(AtomicBool::new(false));
|
||||
let signal = Arc::clone(&failed);
|
||||
let mut sink = DeviceSinkBuilder::from_device(device)?
|
||||
.with_error_callback(move |_| signal.store(true, Relaxed))
|
||||
.open_sink_or_fallback()?;
|
||||
sink.log_on_drop(false);
|
||||
sink.mixer().add(RoutedSource::new(Arc::clone(audio)));
|
||||
Ok(Self {
|
||||
id,
|
||||
_sink: sink,
|
||||
failed,
|
||||
last_samples: audio.samples.load(Relaxed),
|
||||
last_callback: Instant::now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn watch_outputs(rx: mpsc::Receiver<()>, audio: Arc<Audio>) {
|
||||
let host = cpal::default_host();
|
||||
let mut active: Option<DeviceOutput> = None;
|
||||
let mut unavailable = false;
|
||||
loop {
|
||||
let device = host.default_output_device();
|
||||
let id = device.as_ref().and_then(|device| device.id().ok());
|
||||
let now = Instant::now();
|
||||
if let Some(output) = &mut active {
|
||||
let samples = audio.samples.load(Relaxed);
|
||||
if samples != output.last_samples {
|
||||
output.last_samples = samples;
|
||||
output.last_callback = now;
|
||||
}
|
||||
if output.failed.load(Relaxed)
|
||||
|| now.duration_since(output.last_callback) >= STALL_TIME
|
||||
|| device.is_none()
|
||||
|| matches!((&output.id, &id), (Some(old), Some(new)) if old != new)
|
||||
{
|
||||
// Drop the old callback first: only one sink may draw samples.
|
||||
active = None;
|
||||
}
|
||||
}
|
||||
if active.is_none() {
|
||||
if let Some(device) = device {
|
||||
match DeviceOutput::open(device, id, &audio) {
|
||||
Ok(output) => {
|
||||
if unavailable {
|
||||
tracing::info!("audio output restored");
|
||||
}
|
||||
active = Some(output);
|
||||
}
|
||||
Err(error) if !unavailable => {
|
||||
tracing::debug!(%error, "could not open audio output")
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
if active.is_none() && !unavailable {
|
||||
tracing::warn!("waiting for a usable default audio output");
|
||||
}
|
||||
unavailable = active.is_none();
|
||||
}
|
||||
|
||||
if active.is_none() && audio.seeking.load(Relaxed) {
|
||||
let mut queue = audio
|
||||
.queue
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let channels = usize::from(audio.format.channels.get());
|
||||
for _ in 0..(1024 / channels).max(1) {
|
||||
if !audio.seeking.load(Relaxed) {
|
||||
break;
|
||||
}
|
||||
for _ in 0..channels {
|
||||
queue.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
match rx.recv_timeout(PROBE_INTERVAL) {
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
Err(RecvTimeoutError::Timeout) | Ok(()) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RoutedSource {
|
||||
audio: Arc<Audio>,
|
||||
chunk: Vec<f32>,
|
||||
index: usize,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl RoutedSource {
|
||||
fn new(audio: Arc<Audio>) -> Self {
|
||||
let size = audio.format.aligned_samples(CHUNK);
|
||||
Self {
|
||||
audio,
|
||||
chunk: vec![0.0; size],
|
||||
index: size,
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for RoutedSource {
|
||||
type Item = f32;
|
||||
|
||||
fn next(&mut self) -> Option<f32> {
|
||||
let generation = self.audio.generation.load(Relaxed);
|
||||
if self.index == self.chunk.len() || self.generation != generation {
|
||||
let mut queue = self
|
||||
.audio
|
||||
.queue
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for sample in &mut self.chunk {
|
||||
*sample = queue.next().unwrap_or(0.0);
|
||||
}
|
||||
self.audio
|
||||
.samples
|
||||
.fetch_add(self.chunk.len() as u64, Relaxed);
|
||||
self.index = 0;
|
||||
self.generation = generation;
|
||||
}
|
||||
let sample = self.chunk[self.index];
|
||||
self.index += 1;
|
||||
Some(sample)
|
||||
}
|
||||
}
|
||||
|
||||
impl Source for RoutedSource {
|
||||
fn current_span_len(&self) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
fn channels(&self) -> NonZeroU16 {
|
||||
self.audio.format.channels
|
||||
}
|
||||
fn sample_rate(&self) -> NonZeroU32 {
|
||||
self.audio.format.sample_rate
|
||||
}
|
||||
fn total_duration(&self) -> Option<Duration> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replacing_the_sink_preserves_the_rodio_queue_and_position() {
|
||||
let (player, queue) = Player::new();
|
||||
let format = AudioFormat::FALLBACK;
|
||||
let audio = Arc::new(Audio {
|
||||
format,
|
||||
queue: Mutex::new(format.queue(queue)),
|
||||
seeking: AtomicBool::new(false),
|
||||
samples: AtomicU64::new(0),
|
||||
generation: AtomicU64::new(0),
|
||||
});
|
||||
player.append(rodio::buffer::SamplesBuffer::new(
|
||||
format.channels,
|
||||
format.sample_rate,
|
||||
vec![0.5; 96_000],
|
||||
));
|
||||
player.append(rodio::buffer::SamplesBuffer::new(
|
||||
format.channels,
|
||||
format.sample_rate,
|
||||
vec![0.8; 96_000],
|
||||
));
|
||||
let mut first = RoutedSource::new(Arc::clone(&audio));
|
||||
first.by_ref().take(9_600).for_each(|_| {});
|
||||
let previous = player.get_pos();
|
||||
drop(first);
|
||||
assert_eq!(player.len(), 2);
|
||||
player.pause();
|
||||
let mut reconnected = RoutedSource::new(audio);
|
||||
reconnected.by_ref().take(9_600).for_each(|_| {});
|
||||
assert!(player.is_paused());
|
||||
assert!(player.get_pos() - previous < Duration::from_millis(10));
|
||||
player.play();
|
||||
reconnected.take(9_600).for_each(|_| {});
|
||||
assert!(player.get_pos() > previous + Duration::from_millis(50));
|
||||
assert_eq!(player.len(), 2);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -25,10 +25,11 @@
|
||||
//! "already subscribed" mark, an episode preview read from the feed and
|
||||
//! subscribing from a card.
|
||||
//!
|
||||
//! Only RSS metadata is stored. Audio stays on the publisher's server.
|
||||
//! Audio is streamed unless the user explicitly downloads an episode.
|
||||
|
||||
pub mod discovery;
|
||||
pub mod fetch;
|
||||
pub mod offline;
|
||||
pub mod playback;
|
||||
pub mod progress;
|
||||
pub mod publication;
|
||||
@@ -125,6 +126,7 @@ pub fn open_services(db_path: &Path, covers_dir: PathBuf, log: Arc<dyn OpLog>) -
|
||||
let confirmations =
|
||||
publication::ShareConfirmations::open(publication::confirmations_path(db_path));
|
||||
Ok(Services {
|
||||
downloads_dir: db_path.with_file_name("podcast-downloads"),
|
||||
store: Arc::new(store),
|
||||
fetcher: Arc::new(Fetcher::new(covers_dir)?),
|
||||
log,
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Explicit device-local downloads, outside the podcast sync store.
|
||||
use anyhow::{Result, bail};
|
||||
use music_dht::podcast::PodcastEpisodeRef;
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
pub fn key(id: &str) -> String {
|
||||
blake3::hash(id.as_bytes()).to_hex().to_string()
|
||||
}
|
||||
pub fn path(dir: &Path, ep: &PodcastEpisodeRef) -> PathBuf {
|
||||
dir.join(key(ep.episode_id.as_str()))
|
||||
}
|
||||
pub fn available(dir: &Path) -> Result<std::collections::HashSet<String>> {
|
||||
if !dir.exists() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
Ok(fs::read_dir(dir)?
|
||||
.filter_map(Result::ok)
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.filter_map(|e| {
|
||||
let n = e.file_name().to_str()?.to_owned();
|
||||
(n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit())).then_some(n)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
pub fn cleanup(
|
||||
dir: &Path,
|
||||
days: u32,
|
||||
now: SystemTime,
|
||||
) -> Result<std::collections::HashSet<String>> {
|
||||
for name in available(dir)? {
|
||||
let p = dir.join(name);
|
||||
if now
|
||||
.duration_since(fs::metadata(&p)?.modified()?)
|
||||
.unwrap_or_default()
|
||||
>= Duration::from_secs(u64::from(days.max(1)) * 86400)
|
||||
{
|
||||
let _ = fs::remove_file(p);
|
||||
}
|
||||
}
|
||||
available(dir)
|
||||
}
|
||||
pub fn open(dir: &Path, ep: &PodcastEpisodeRef) -> Result<Option<File>> {
|
||||
match File::open(path(dir, ep)) {
|
||||
Ok(f) => Ok(Some(f)),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn download(dir: &Path, ep: &PodcastEpisodeRef) -> Result<()> {
|
||||
download_with_cancel(dir, ep, super::stream::CancelToken::never())
|
||||
}
|
||||
pub fn download_with_cancel(
|
||||
dir: &Path,
|
||||
ep: &PodcastEpisodeRef,
|
||||
cancel: super::stream::CancelToken,
|
||||
) -> Result<()> {
|
||||
let target = path(dir, ep);
|
||||
let dir = target.parent().unwrap();
|
||||
fs::create_dir_all(dir)?;
|
||||
if target.is_file() {
|
||||
return Ok(());
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut stream = super::stream::open_with(
|
||||
&ep.audio_url,
|
||||
super::stream::CancelToken::new(move || {
|
||||
cancel.is_cancelled() || started.elapsed() > Duration::from_secs(7200)
|
||||
}),
|
||||
)?;
|
||||
let mut temp = tempfile::NamedTempFile::new_in(dir)?;
|
||||
let mut buf = [0; 65536];
|
||||
let mut total = 0u64;
|
||||
loop {
|
||||
let n = stream.reader.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > 4 * 1024 * 1024 * 1024 {
|
||||
bail!("episode exceeds 4 GiB");
|
||||
}
|
||||
temp.write_all(&buf[..n])?;
|
||||
}
|
||||
if total == 0
|
||||
|| stream.probe.end() == super::stream::StreamEnd::Failed
|
||||
|| stream.byte_len.is_some_and(|len| len != total)
|
||||
{
|
||||
bail!("incomplete episode download");
|
||||
}
|
||||
temp.as_file().sync_all()?;
|
||||
temp.persist(target)
|
||||
.map_err(|_| anyhow::anyhow!("cannot save episode"))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -163,6 +163,9 @@ pub fn open_at(
|
||||
start_ms: i64,
|
||||
cancel: &CancelToken,
|
||||
) -> Result<PreparedEpisode> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
let opened = stream::open_with(&episode.audio_url, cancel.clone())?;
|
||||
let seekable = opened.seekable;
|
||||
let probe = opened.probe.clone();
|
||||
@@ -218,6 +221,43 @@ pub fn open_at(
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode a completed local download. Blocking; no HTTP requests.
|
||||
pub fn open_local(
|
||||
episode: &PodcastEpisodeRef,
|
||||
start_ms: i64,
|
||||
file: std::fs::File,
|
||||
) -> Result<PreparedEpisode> {
|
||||
let len = file.metadata()?.len();
|
||||
let mut source = decode_source_with(
|
||||
Box::new(file),
|
||||
Some(len),
|
||||
episode.mime.as_deref(),
|
||||
true,
|
||||
true,
|
||||
)
|
||||
.map_err(|e| anyhow!(e))?;
|
||||
if start_ms > 0 {
|
||||
source
|
||||
.try_seek(Duration::from_millis(start_ms as u64))
|
||||
.map_err(|_| CannotResume {
|
||||
position_ms: start_ms,
|
||||
})?;
|
||||
}
|
||||
let measured = source
|
||||
.total_duration()
|
||||
.and_then(|d| i64::try_from(d.as_millis()).ok())
|
||||
.filter(|ms| *ms > 0);
|
||||
Ok(PreparedEpisode {
|
||||
episode: episode.clone(),
|
||||
source,
|
||||
start_ms,
|
||||
duration_ms: measured.or(episode.duration_ms),
|
||||
duration_measured: measured.is_some(),
|
||||
seekable: true,
|
||||
probe: StreamProbe::local(),
|
||||
})
|
||||
}
|
||||
|
||||
/// [`resolve`] + [`open_at`], refreshing the feed once when the audio URL
|
||||
/// answers with a client error (moved or expired file).
|
||||
pub async fn prepare(
|
||||
@@ -233,8 +273,25 @@ pub async fn prepare(
|
||||
let lookup = queued.clone();
|
||||
let (episode, start_ms) = blocking(move || resolve(store.as_deref(), &lookup, start)).await?;
|
||||
let attempt = episode.clone();
|
||||
let downloads_dir = services.as_ref().map(|s| s.downloads_dir.clone());
|
||||
let attempt_cancel = cancel.clone();
|
||||
let error = match blocking(move || open_at(&attempt, start_ms, &attempt_cancel)).await {
|
||||
let error = match blocking(move || {
|
||||
if attempt_cancel.is_cancelled() {
|
||||
return Err(Cancelled.into());
|
||||
}
|
||||
let local = downloads_dir
|
||||
.as_ref()
|
||||
.map(|dir| super::offline::open(dir, &attempt))
|
||||
.transpose()?
|
||||
.flatten();
|
||||
if let Some(file) = local {
|
||||
open_local(&attempt, start_ms, file)
|
||||
} else {
|
||||
open_at(&attempt, start_ms, &attempt_cancel)
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(prepared) => return Ok(prepared),
|
||||
Err(error) => error,
|
||||
};
|
||||
|
||||
@@ -834,3 +834,98 @@ fn a_superseded_resume_stops_reading_up_to_its_offset() {
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn downloaded_episode_plays_and_seeks_without_publisher() {
|
||||
let f = fixture();
|
||||
let (_, mut episode) = subscribed(&f).await;
|
||||
f.server
|
||||
.set("/offline.wav", Route::new(wav(8), "audio/wav"));
|
||||
episode.audio_url = f.server.url("/offline.wav");
|
||||
let download_dir = f.services.downloads_dir.clone();
|
||||
let download_episode = episode.clone();
|
||||
tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &download_episode))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(
|
||||
super::offline::available(&f.services.downloads_dir)
|
||||
.unwrap()
|
||||
.contains(&super::offline::key(episode.episode_id.as_str()))
|
||||
);
|
||||
// No store lookup can replace this reference with the fixture's old URL.
|
||||
episode.audio_url = "http://127.0.0.1:1/unavailable".into();
|
||||
let file = super::offline::open(&f.services.downloads_dir, &episode)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let prepared = playback::open_local(&episode, 2000, file).unwrap();
|
||||
assert_eq!(prepared.start_ms, 2000);
|
||||
assert!(prepared.seekable);
|
||||
assert_eq!(prepared.probe.end(), StreamEnd::Complete);
|
||||
assert!(prepared.source.take(100).count() > 0);
|
||||
// Prepare must prefer the same local file even though resolve finds the old HTTP URL.
|
||||
let prepared = playback::prepare(
|
||||
Some(f.services.clone()),
|
||||
episode,
|
||||
StartAt::Position { ms: 2000 },
|
||||
NOW,
|
||||
CancelToken::never(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(prepared.start_ms, 2000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_cleanup_expires_only_completed_files_at_the_boundary() {
|
||||
use std::fs::{File, FileTimes};
|
||||
use std::time::SystemTime;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let now = SystemTime::now();
|
||||
let expired = dir.path().join(super::offline::key("old"));
|
||||
let fresh = dir.path().join(super::offline::key("new"));
|
||||
File::create(&expired)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(now - Duration::from_secs(30 * 86400)))
|
||||
.unwrap();
|
||||
File::create(&fresh)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(now - Duration::from_secs(29 * 86400)))
|
||||
.unwrap();
|
||||
let unrelated = dir.path().join("notes.txt");
|
||||
std::fs::write(&unrelated, b"keep").unwrap();
|
||||
let remaining = super::offline::cleanup(dir.path(), 30, now).unwrap();
|
||||
assert!(!expired.exists());
|
||||
assert!(fresh.exists());
|
||||
assert!(unrelated.exists());
|
||||
assert_eq!(remaining.len(), 1);
|
||||
assert_eq!(
|
||||
super::offline::cleanup(dir.path(), 30, now).unwrap(),
|
||||
remaining
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_download_never_becomes_available_offline() {
|
||||
let f = fixture();
|
||||
let (_, mut episode) = subscribed(&f).await;
|
||||
episode.audio_url = f.server.url("/missing-audio");
|
||||
let download_dir = f.services.downloads_dir.clone();
|
||||
assert!(
|
||||
tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &episode))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
super::offline::available(&f.services.downloads_dir)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(&f.services.downloads_dir)
|
||||
.unwrap()
|
||||
.count(),
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ pub const FAILURE_BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
#[derive(Clone)]
|
||||
pub struct Services {
|
||||
pub store: Arc<PodcastStore>,
|
||||
pub downloads_dir: std::path::PathBuf,
|
||||
pub fetcher: Arc<Fetcher>,
|
||||
pub log: Arc<dyn OpLog>,
|
||||
/// Device-local privacy confirmations for sharing (never synced).
|
||||
|
||||
@@ -162,7 +162,7 @@ pub enum StreamEnd {
|
||||
/// Read-only view of a stream's state that outlives handing the reader to
|
||||
/// the decoder.
|
||||
#[derive(Clone)]
|
||||
pub struct StreamProbe(Arc<Shared>);
|
||||
pub struct StreamProbe(Option<Arc<Shared>>);
|
||||
|
||||
impl std::fmt::Debug for StreamProbe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
@@ -171,8 +171,14 @@ impl std::fmt::Debug for StreamProbe {
|
||||
}
|
||||
|
||||
impl StreamProbe {
|
||||
pub fn local() -> Self {
|
||||
Self(None)
|
||||
}
|
||||
pub fn end(&self) -> StreamEnd {
|
||||
let state = self.0.lock();
|
||||
let Some(shared) = &self.0 else {
|
||||
return StreamEnd::Complete;
|
||||
};
|
||||
let state = shared.lock();
|
||||
if state.read_failed {
|
||||
StreamEnd::Failed
|
||||
} else if state.declared_total {
|
||||
@@ -385,7 +391,7 @@ pub fn open_with(url: &str, cancel: CancelToken) -> Result<OpenedStream> {
|
||||
.spawn(move || downloader.run(response))
|
||||
.context("spawning the podcast stream thread")?;
|
||||
Ok(OpenedStream {
|
||||
probe: StreamProbe(Arc::clone(&shared)),
|
||||
probe: StreamProbe(Some(Arc::clone(&shared))),
|
||||
reader: HttpStream { pos: 0, shared },
|
||||
byte_len: opened.total,
|
||||
mime_type,
|
||||
|
||||
@@ -57,6 +57,11 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
|
||||
selected = items.len();
|
||||
}
|
||||
let (label, value, enabled) = match row {
|
||||
SettingsRow::PodcastRetention => (
|
||||
"Podcast downloads: keep days".into(),
|
||||
state.podcast_retention_days.to_string(),
|
||||
true,
|
||||
),
|
||||
SettingsRow::MusicDirectory => (
|
||||
"Music save directory".into(),
|
||||
if state.music_dir_changing {
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
use crate::app::{
|
||||
lyrics::{Editor, Reader},
|
||||
state::{AppState, Popup},
|
||||
};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::{Alignment, Rect},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Clear, Paragraph, Wrap},
|
||||
};
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
use super::theme;
|
||||
|
||||
fn popup_area(screen: Rect) -> Rect {
|
||||
let width = screen.width.saturating_sub(4).min(96);
|
||||
let height = screen.height.saturating_sub(4).min(30);
|
||||
Rect::new(
|
||||
screen.x + (screen.width - width) / 2,
|
||||
screen.y + (screen.height - height) / 2,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_reader(state: &mut AppState, screen: Rect) {
|
||||
if let Some(Popup::Lyrics(reader)) = &mut state.popup {
|
||||
let area = popup_area(screen);
|
||||
reader.viewport_height = usize::from(area.height.saturating_sub(4));
|
||||
let width = usize::from(area.width.saturating_sub(4)).max(1);
|
||||
let key = (reader.lyrics(&state.lyrics).document_revision, width);
|
||||
if reader.layout_key != Some(key) {
|
||||
reader.layout_key = Some(key);
|
||||
reader.rows.clear();
|
||||
let document = &reader
|
||||
.preview
|
||||
.as_ref()
|
||||
.map_or(&state.lyrics, |preview| &preview.1)
|
||||
.document;
|
||||
for (index, line) in document.lines.iter().enumerate() {
|
||||
let mut row = String::new();
|
||||
let mut columns = 0;
|
||||
for ch in line.chars() {
|
||||
let char_width = ch.width().unwrap_or_default();
|
||||
if columns + char_width > width && !row.is_empty() {
|
||||
reader.rows.push((index, std::mem::take(&mut row)));
|
||||
columns = 0;
|
||||
}
|
||||
row.push(ch);
|
||||
columns += char_width;
|
||||
}
|
||||
reader.rows.push((index, row));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shell(frame: &mut Frame, state: &AppState, title: String) -> Rect {
|
||||
let area = popup_area(frame.area());
|
||||
let block = Block::bordered()
|
||||
.title(title)
|
||||
.border_style(theme::strong_border_for(state))
|
||||
.title_style(theme::header_for(state));
|
||||
let inner = block.inner(area);
|
||||
frame.render_widget(Clear, area);
|
||||
frame.render_widget(block, area);
|
||||
inner
|
||||
}
|
||||
|
||||
fn row(area: Rect, index: u16) -> Rect {
|
||||
Rect::new(
|
||||
area.x,
|
||||
area.y.saturating_add(index),
|
||||
area.width,
|
||||
u16::from(index < area.height),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn draw_reader(frame: &mut Frame, state: &AppState, reader: &Reader) {
|
||||
let playback = reader.lyrics(&state.lyrics);
|
||||
let title = if playback.title.is_empty() {
|
||||
" Lyrics ".into()
|
||||
} else {
|
||||
format!(" Lyrics · {} ", playback.title)
|
||||
};
|
||||
let inner = shell(frame, state, title);
|
||||
if inner.height < 3 || inner.width < 4 {
|
||||
return;
|
||||
}
|
||||
let body = Rect::new(inner.x + 1, inner.y + 1, inner.width - 2, inner.height - 2);
|
||||
let active = reader.active_line(&state.lyrics, &state.player);
|
||||
let version = playback.versions.get(playback.selected);
|
||||
if let Some(version) = version {
|
||||
let label = crate::lyrics::clean_text(&version.label).replace('\n', " ");
|
||||
let loading = if playback.loading {
|
||||
" · Looking for versions…"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(
|
||||
"{} / {} · {label}{loading}",
|
||||
playback.selected + 1,
|
||||
playback.versions.len()
|
||||
))
|
||||
.alignment(Alignment::Center)
|
||||
.style(theme::dim()),
|
||||
row(inner, 0),
|
||||
);
|
||||
}
|
||||
if reader.rows.is_empty() {
|
||||
let message = if playback.title.is_empty() {
|
||||
"No music track selected".into()
|
||||
} else if playback.document.instrumental {
|
||||
"Instrumental".into()
|
||||
} else if playback.loading {
|
||||
format!("{} Looking for lyrics…", state.spinner())
|
||||
} else {
|
||||
"Could not find lyrics".into()
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(message)
|
||||
.alignment(Alignment::Center)
|
||||
.style(theme::accent_for(state)),
|
||||
row(body, body.height / 2),
|
||||
);
|
||||
} else {
|
||||
let visible = usize::from(body.height);
|
||||
let start = reader
|
||||
.top
|
||||
.unwrap_or_else(|| reader.follow_top(active))
|
||||
.min(reader.rows.len().saturating_sub(visible));
|
||||
for (offset, (index, text)) in reader.rows.iter().skip(start).take(visible).enumerate() {
|
||||
let style = if Some(*index) == active {
|
||||
theme::header_for(state)
|
||||
} else if playback.document.timed() {
|
||||
theme::dim()
|
||||
} else {
|
||||
ratatui::style::Style::default()
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(text.as_str())
|
||||
.alignment(Alignment::Center)
|
||||
.style(style),
|
||||
row(body, offset as u16),
|
||||
);
|
||||
}
|
||||
}
|
||||
let footer = if playback.document.timed() {
|
||||
"↑↓ / PgUp PgDn scroll · f follow · ←→ version · esc close"
|
||||
} else {
|
||||
"↑↓ / PgUp PgDn scroll · ←→ version · esc close"
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(footer)
|
||||
.alignment(Alignment::Center)
|
||||
.style(theme::dim()),
|
||||
row(inner, inner.height - 1),
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn draw_editor(frame: &mut Frame, state: &AppState, editor: &Editor) {
|
||||
let inner = shell(frame, state, " Track lyrics ".into());
|
||||
if inner.height < 4 || inner.width < 4 {
|
||||
return;
|
||||
}
|
||||
let body = Rect::new(inner.x + 1, inner.y, inner.width - 2, inner.height - 1);
|
||||
let mut footer = if editor.busy {
|
||||
"Working…"
|
||||
} else {
|
||||
"↑↓ select · a add · enter edit · d delete · esc back"
|
||||
};
|
||||
if let Some(draft) = &editor.draft {
|
||||
if !editor.busy {
|
||||
footer =
|
||||
"Tab label/text · paste plain text or LRC · Ctrl+S / F2 save · esc cancel";
|
||||
}
|
||||
let label = if draft.label_focused {
|
||||
super::line_edit_spans(&draft.label, usize::from(body.width.saturating_sub(7)))
|
||||
} else {
|
||||
vec![Span::raw(draft.label.as_str())]
|
||||
};
|
||||
let mut label_line = vec![Span::styled("Label ", theme::accent_for(state))];
|
||||
label_line.extend(label);
|
||||
frame.render_widget(Paragraph::new(Line::from(label_line)), row(body, 0));
|
||||
|
||||
let (cursor_row, cursor_col) = draft.text.line_cursor();
|
||||
let height = usize::from(body.height - 1);
|
||||
let start = cursor_row.saturating_sub(height.saturating_sub(1));
|
||||
for (offset, text) in draft.text.split('\n').skip(start).take(height).enumerate() {
|
||||
let line = if !draft.label_focused && start + offset == cursor_row {
|
||||
let edit = crate::app::input::LineEdit::with_cursor(text, cursor_col);
|
||||
Line::from(super::line_edit_spans(&edit, usize::from(body.width)))
|
||||
} else {
|
||||
Line::from(text)
|
||||
};
|
||||
frame.render_widget(Paragraph::new(line), row(body, offset as u16 + 1));
|
||||
}
|
||||
} else if editor.confirm_delete {
|
||||
footer = "Enter / y delete · any other key cancels";
|
||||
let label = editor
|
||||
.versions
|
||||
.get(editor.cursor)
|
||||
.map(|version| version.label.as_str())
|
||||
.unwrap_or_default();
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!("Delete {}?", crate::lyrics::clean_text(label)))
|
||||
.alignment(Alignment::Center)
|
||||
.wrap(Wrap { trim: true }),
|
||||
body,
|
||||
);
|
||||
} else if editor.versions.is_empty() {
|
||||
let message = if editor.busy {
|
||||
format!("{} Loading lyrics…", state.spinner())
|
||||
} else {
|
||||
"No saved lyrics. Press a to add a version.".into()
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(message).alignment(Alignment::Center),
|
||||
row(body, body.height / 2),
|
||||
);
|
||||
} else {
|
||||
let start = editor
|
||||
.cursor
|
||||
.saturating_sub(usize::from(body.height).saturating_sub(1));
|
||||
for (offset, version) in editor
|
||||
.versions
|
||||
.iter()
|
||||
.skip(start)
|
||||
.take(usize::from(body.height))
|
||||
.enumerate()
|
||||
{
|
||||
let synced = if version.synced_lrc.is_some() {
|
||||
"Timed"
|
||||
} else if version.instrumental {
|
||||
"Instrumental"
|
||||
} else {
|
||||
"Plain"
|
||||
};
|
||||
let label = crate::lyrics::clean_text(&version.label).replace('\n', " ");
|
||||
let style = if start + offset == editor.cursor {
|
||||
theme::header_for(state)
|
||||
} else {
|
||||
theme::dim()
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!("{label} · {synced}")).style(style),
|
||||
row(body, offset as u16),
|
||||
);
|
||||
}
|
||||
}
|
||||
frame.render_widget(
|
||||
Paragraph::new(editor.error.as_deref().unwrap_or(footer)).style(theme::accent_for(state)),
|
||||
row(inner, inner.height - 1),
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ pub mod art;
|
||||
mod federation;
|
||||
pub(crate) mod global;
|
||||
mod logs;
|
||||
pub(crate) mod lyrics;
|
||||
mod playlists;
|
||||
mod podcast_card;
|
||||
mod podcasts;
|
||||
@@ -561,6 +562,7 @@ mod tests {
|
||||
pub fn draw(frame: &mut Frame, state: &AppState, keymap: &Keymap) {
|
||||
if state.visualizer.active {
|
||||
crate::visualizer::draw(frame, state);
|
||||
popup::draw(frame, state);
|
||||
if state.shutting_down {
|
||||
draw_shutdown(frame, state);
|
||||
}
|
||||
|
||||
@@ -652,6 +652,17 @@ fn draw_episode_row(
|
||||
_ => String::new(),
|
||||
};
|
||||
let mut title = episode.title.clone();
|
||||
if state
|
||||
.podcast_downloading
|
||||
.contains(episode.episode_id.as_str())
|
||||
{
|
||||
title.push_str(" [downloading]");
|
||||
} else if state
|
||||
.podcast_downloads
|
||||
.contains(&crate::podcasts::offline::key(episode.episode_id.as_str()))
|
||||
{
|
||||
title.push_str(" [offline]");
|
||||
}
|
||||
if !item.in_feed {
|
||||
title.push_str(" (no longer in the feed)");
|
||||
}
|
||||
|
||||
+17
-2
@@ -13,6 +13,8 @@ use crate::library::models::{ArtistRef, TrackItem};
|
||||
|
||||
pub fn draw(frame: &mut Frame, state: &AppState) {
|
||||
match state.popup.as_ref() {
|
||||
Some(Popup::Lyrics(reader)) => super::lyrics::draw_reader(frame, state, reader),
|
||||
Some(Popup::LyricsEditor(editor)) => super::lyrics::draw_editor(frame, state, editor),
|
||||
Some(Popup::AddToPlaylist { target, cursor }) => {
|
||||
draw_picker(frame, state, &target.label(), *cursor)
|
||||
}
|
||||
@@ -22,8 +24,16 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
|
||||
fields,
|
||||
focus,
|
||||
error,
|
||||
..
|
||||
}) => draw_edit(frame, state, title, fields, *focus, error.as_deref()),
|
||||
target,
|
||||
}) => draw_edit(
|
||||
frame,
|
||||
state,
|
||||
title,
|
||||
fields,
|
||||
*focus,
|
||||
error.as_deref(),
|
||||
matches!(target, crate::app::state::EditTarget::Track(_)),
|
||||
),
|
||||
Some(Popup::ConfirmDelete { label, .. }) => draw_confirm_delete(frame, state, label),
|
||||
Some(Popup::ConfirmPodcastUnsubscribe { title, .. }) => {
|
||||
draw_confirm_podcast_unsubscribe(frame, state, title)
|
||||
@@ -1213,6 +1223,7 @@ fn draw_edit(
|
||||
fields: &[EditField],
|
||||
focus: usize,
|
||||
error: Option<&str>,
|
||||
track: bool,
|
||||
) {
|
||||
let height = (fields.len() as u16 * 3 + 4).min(frame.area().height.saturating_sub(2));
|
||||
let area = centered(frame.area(), 60, height);
|
||||
@@ -1257,6 +1268,10 @@ fn draw_edit(
|
||||
let footer = areas[areas.len() - 1];
|
||||
let hint = match error {
|
||||
Some(error) => Line::styled(error.to_string(), theme::accent_for(state)),
|
||||
None if track => Line::styled(
|
||||
"F3 lyrics · tab/↑↓ field · enter save · esc cancel",
|
||||
theme::dim(),
|
||||
),
|
||||
None => Line::styled("tab/↑↓ field · enter save · esc cancel", theme::dim()),
|
||||
};
|
||||
frame.render_widget(Paragraph::new(hint).alignment(Alignment::Center), footer);
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// name: Lyrics in motion
|
||||
// protocol: furumi-visualizer-v3
|
||||
// bundle-version: 3
|
||||
//
|
||||
// Playback timestamps drive the entrance and highlight. The active glyphs
|
||||
// are cached across frames and rebuilt when the terminal changes size.
|
||||
|
||||
fn clamp(value, low, high) {
|
||||
if value < low { low } else if value > high { high } else { value }
|
||||
}
|
||||
|
||||
fn rgb(r, g, b) { (r << 16) | (g << 8) | b }
|
||||
|
||||
fn glow(color, gain) {
|
||||
let amount = clamp(gain, 0.0, 1.0);
|
||||
rgb(to_int(to_float((color >> 16) & 255) * amount),
|
||||
to_int(to_float((color >> 8) & 255) * amount),
|
||||
to_int(to_float(color & 255) * amount))
|
||||
}
|
||||
|
||||
fn text_at(text, x, y, width, height, fg) {
|
||||
if text == "" || y < 0 || y >= height || x >= width { return; }
|
||||
let left = if x < 0 { 0 } else { x };
|
||||
let text = cut_cells(text, left - x, width - left);
|
||||
if text != "" {
|
||||
this.push(#{ op: "text", x: left, y: y, text: text, fg: fg, bg: 0x080b18, bold: true });
|
||||
}
|
||||
}
|
||||
|
||||
fn center(text, dx, y, w, h, fg) {
|
||||
let text = if cell_width(text) <= w { text } else { cut_cells(text, 0, w - 1) + "…" };
|
||||
this.text_at(text, (w - cell_width(text)) / 2 + dx, y, w, h, fg);
|
||||
}
|
||||
|
||||
fn stage(input, w, h, tint, arrival) {
|
||||
if w < 20 || h < 12 { return; }
|
||||
let band = max(1, h / 40);
|
||||
for y in range(3, h - 3, band) {
|
||||
let distance = abs(to_float(2 * y - h)) / to_float(h);
|
||||
let level = 0.04 + pow(1.0 - distance, 3.0) * (0.12 + input.bass * 0.12 + arrival * 0.08);
|
||||
this.push(#{ op: "rect", x: 0, y: y, w: w, h: min(band, h - 3 - y), bg: glow(tint, level) });
|
||||
}
|
||||
let dots = [];
|
||||
let shapes = ["✦", "✧", "⋄", "⟡", "+", "∙"];
|
||||
for i in 0..64 {
|
||||
let angle = to_float(i) * 2.399963 + input.time * 0.09;
|
||||
let radius = 0.48 + 0.46 * abs(sin(to_float(i) * 8.17 + input.time * 0.24));
|
||||
let x = w + to_int(cos(angle) * to_float(w - 2) * radius);
|
||||
let y = h * 2 + to_int(sin(angle) * to_float(h * 2 - 12) * radius);
|
||||
if abs(2 * x - 2 * w) > w || abs(y - h * 2) > h {
|
||||
if i % 5 == 0 {
|
||||
let twinkle = 0.5 + 0.5 * sin(input.time * 2.4 + to_float(i) * 1.83);
|
||||
let ch = shapes[(i / 5) % shapes.len()];
|
||||
let fg = glow(tint, 0.28 + twinkle * 0.38 + input.treble * 0.25);
|
||||
this.push(#{ op: "cell", x: x / 2, y: y / 4, ch: ch, fg: fg, preserve_bg: true });
|
||||
} else {
|
||||
dots.push(x); dots.push(y);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.push(#{ op: "dots", points: dots, fg: glow(tint, 0.48 + input.treble * 0.40), preserve_bg: true });
|
||||
|
||||
let samples = min(24, w / 4);
|
||||
for i in 0..samples {
|
||||
let wave = 0.5 + 0.5 * sin(input.time * 5.0 + to_float(i) * 0.67);
|
||||
let rise = min(max(1, h / 5 - 3), 1 + to_int(wave * (2.0 + 4.0 * input.bass + 3.0 * input.beat)));
|
||||
let x = 2 + i * (w / 2 - 3) / samples;
|
||||
let fg = glow(tint, 0.27 + wave * 0.25 + input.energy * 0.26);
|
||||
this.push(#{ op: "vline", x: x, y: h - 3 - rise, h: rise, ch: "▌", fg: fg, bg: 0x080b18 });
|
||||
this.push(#{ op: "vline", x: w - 1 - x, y: h - 3 - rise, h: rise, ch: "▐", fg: fg, bg: 0x080b18 });
|
||||
}
|
||||
}
|
||||
|
||||
fn phrase(glyph, slot, total, mode, p, progress, y, w, h, tint, beat) {
|
||||
let drift = pow(1.0 - p, 3.0);
|
||||
let side = if slot % 2 == 0 { -1 } else { 1 };
|
||||
let height = glyph.len();
|
||||
let headline = height >= 10 || total == 1;
|
||||
for i in 0..height {
|
||||
let row = glyph[i];
|
||||
if row == "" { continue; }
|
||||
let width = cell_width(row);
|
||||
let space = w - width;
|
||||
let anchor = if total == 1 { space / 2 }
|
||||
else if (slot + mode) % 2 == 0 { space / 5 }
|
||||
else { space * 4 / 5 };
|
||||
let dx = if mode == 0 { side * to_int(drift * to_float(min(22, w / 5))) }
|
||||
else if mode == 2 { to_int(drift * to_float(i * 2 - height)) }
|
||||
else { 0 };
|
||||
let dy = if mode == 1 { to_int(drift * to_float(min(5, h / 6))) } else { 0 };
|
||||
let x = anchor + dx;
|
||||
let brightness = if headline { 1.0 } else { 0.72 };
|
||||
let shade = brightness * (1.0 - 0.27 * to_float(i) / to_float(height));
|
||||
// Reveal from opposing edges in the third entrance.
|
||||
let shown = if mode == 2 { max(1, to_int(to_float(width) * (1.0 - drift))) } else { width };
|
||||
let start = if mode == 2 && side > 0 { width - shown } else { 0 };
|
||||
let visible = cut_cells(row, start, shown);
|
||||
let lift = y + i + dy;
|
||||
this.text_at(visible, x + start + 1, lift, w, h, glow(tint, 0.40 + beat * 0.22));
|
||||
this.text_at(visible, x + start, lift, w, h, glow(tint, shade * (0.76 + 0.24 * p)));
|
||||
let sweep = to_int(to_float(width) * progress);
|
||||
this.text_at(cut_cells(row, start, max(0, min(shown, sweep - start))), x + start, lift,
|
||||
w, h, glow(0xfff6ff, shade + 0.20));
|
||||
}
|
||||
}
|
||||
|
||||
fn render(input) {
|
||||
let w = input.width;
|
||||
let h = input.height;
|
||||
let commands = [#{ op: "clear", bg: 0x080b18 }];
|
||||
if w < 4 || h < 3 { return commands; }
|
||||
let l = if "lyrics" in input { input.lyrics } else {
|
||||
#{ available: false, timed: false, instrumental: false, loading: false,
|
||||
active: "", previous: "", next: "", index: -1, elapsed: 0.0, progress: 0.0, until_next: -1.0 }
|
||||
};
|
||||
let st = if type_of(input.state) == "map" { input.state } else { #{} };
|
||||
let tint = if l.index % 2 == 0 { 0x93c5ff } else { 0xffa5da };
|
||||
let p = clamp(l.elapsed / 0.40, 0.0, 1.0);
|
||||
let arrival = if l.index >= 0 { pow(1.0 - p, 3.0) } else { 0.0 };
|
||||
commands.stage(input, w, h, tint, arrival);
|
||||
|
||||
if h > 7 {
|
||||
let title_width = if input.show_clock && w >= 32 { w - 24 } else { w };
|
||||
let title = if cell_width(input.track_title) <= title_width { input.track_title }
|
||||
else { cut_cells(input.track_title, 0, title_width - 1) + "…" };
|
||||
commands.center(title, 0, 1, w, h, glow(tint, 0.78));
|
||||
if input.show_clock && w >= 32 {
|
||||
commands.text_at(input.clock, w - 10, 1, w, h, glow(tint, 0.72));
|
||||
}
|
||||
}
|
||||
|
||||
if l.index >= 0 {
|
||||
let font_width = w - 8;
|
||||
let font_height = if h >= 12 { min(32, h * 3 / 5) } else { 0 };
|
||||
if !("active" in st) || st.active != l.active || st.width != font_width || st.height != font_height {
|
||||
st.active = l.active;
|
||||
st.width = font_width;
|
||||
st.height = font_height;
|
||||
st.phrases = lyric_layout(l.active, font_width, font_height);
|
||||
}
|
||||
let total = st.phrases.len();
|
||||
let rows = max(1, total - 1);
|
||||
if total > 0 {
|
||||
rows = total - 1;
|
||||
for glyph in st.phrases { rows += glyph.len(); }
|
||||
}
|
||||
let top = (h - rows) / 2;
|
||||
let y = top;
|
||||
if total == 0 {
|
||||
commands.center(l.active, 0, y, w, h, 0xf6f3ff);
|
||||
}
|
||||
let mode = l.index % 3;
|
||||
let duration = if l.until_next >= 0.0 { l.elapsed + l.until_next } else { 2.0 };
|
||||
let entrance = clamp(duration * 0.28, 0.08, 0.60);
|
||||
for slot in 0..total {
|
||||
let glyph = st.phrases[slot];
|
||||
let phase = clamp(l.elapsed / entrance * 1.5 - 0.5 * to_float(slot), 0.0, 1.0);
|
||||
let progress = clamp(l.progress * to_float(total) - to_float(slot), 0.0, 1.0);
|
||||
commands.phrase(glyph, slot, total, mode, phase, progress, y, w, h, tint, input.beat);
|
||||
y += glyph.len() + 1;
|
||||
}
|
||||
if h >= 12 {
|
||||
let exit = 1.0 - arrival;
|
||||
let side = if mode == 1 { -1 } else { 1 };
|
||||
commands.center(l.previous, side * to_int(exit * to_float(w / 12)),
|
||||
top - 2, w, h, glow(tint, 0.32 + arrival * 0.38));
|
||||
commands.center(l.next, 0, min(h - 3, top + rows + 3), w, h, glow(tint, 0.66));
|
||||
}
|
||||
} else {
|
||||
let message = if l.instrumental { "Instrumental" }
|
||||
else if l.timed { "Waiting for the first line" }
|
||||
else if l.available { "Plain lyrics · Ctrl+L to read" }
|
||||
else if l.loading { "Looking for lyrics…" }
|
||||
else { "No lyrics found" };
|
||||
commands.center(message, 0, h / 2, w, h, glow(tint, 0.82));
|
||||
}
|
||||
|
||||
if h >= 10 && l.index >= 0 && l.until_next >= 0.0 && w >= 14 {
|
||||
let count = clamp(to_int(to_float(w - 8) * l.progress), 0, w - 8);
|
||||
commands.push(#{ op: "hline", x: 4, y: h - 2, w: w - 8, ch: "─", fg: 0x394568, bg: 0x080b18 });
|
||||
if count > 0 {
|
||||
commands.push(#{ op: "hline", x: 4, y: h - 2, w: count, ch: "━", fg: tint, bg: 0x080b18 });
|
||||
commands.text_at("◆", min(w - 5, 4 + count), h - 2, w, h, 0xfff6ff);
|
||||
}
|
||||
}
|
||||
#{ commands: commands, state: st }
|
||||
}
|
||||
+198
-8
@@ -13,6 +13,7 @@ use anyhow::{Context as _, Result};
|
||||
use ratatui::Frame;
|
||||
use ratatui::buffer::Buffer;
|
||||
|
||||
mod matrix;
|
||||
pub mod status;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
@@ -61,6 +62,13 @@ const BUNDLED_SCRIPTS: &[BundledScript] = &[
|
||||
version: 8,
|
||||
source: include_str!("visualizations/vfd_panel.rhai"),
|
||||
},
|
||||
BundledScript {
|
||||
id: "lyrics_in_motion",
|
||||
file_name: "lyrics_in_motion.rhai",
|
||||
display_name: "Lyrics in motion",
|
||||
version: 3,
|
||||
source: include_str!("visualizations/lyrics_in_motion.rhai"),
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -380,9 +388,64 @@ fn input_map_with_features(area: Rect, state: &AppState, features: AudioFeatures
|
||||
input.insert("track_artist".into(), artist.into());
|
||||
insert_meter(&mut input, &state.player.audio_analysis);
|
||||
insert_track_details(&mut input, state);
|
||||
input.insert(
|
||||
"lyrics".into(),
|
||||
lyrics_input(state, features.position_secs).into(),
|
||||
);
|
||||
input
|
||||
}
|
||||
|
||||
fn lyrics_input(state: &AppState, position: f64) -> Map {
|
||||
let playback = &state.lyrics;
|
||||
let doc = &playback.document;
|
||||
let active = doc.line_at(position);
|
||||
let previous = active.and_then(|index| index.checked_sub(1));
|
||||
let next = if doc.timed() {
|
||||
Some(active.map_or(0, |index| index + 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let line = |index: Option<usize>| {
|
||||
index
|
||||
.and_then(|index| doc.lines.get(index))
|
||||
.map(|line| line.chars().take(512).collect::<String>())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let mut lyrics = Map::new();
|
||||
lyrics.insert("loading".into(), playback.loading.into());
|
||||
lyrics.insert("timed".into(), doc.timed().into());
|
||||
lyrics.insert("instrumental".into(), doc.instrumental.into());
|
||||
lyrics.insert("available".into(), (!playback.versions.is_empty()).into());
|
||||
lyrics.insert("active".into(), line(active).into());
|
||||
lyrics.insert("previous".into(), line(previous).into());
|
||||
lyrics.insert("next".into(), line(next).into());
|
||||
insert_int(
|
||||
&mut lyrics,
|
||||
"index",
|
||||
active.map_or(-1, |index| index as i64),
|
||||
);
|
||||
let start = active.and_then(|index| doc.time(index));
|
||||
let end = next.and_then(|index| doc.time(index));
|
||||
insert_float(
|
||||
&mut lyrics,
|
||||
"elapsed",
|
||||
start.map_or(0.0, |start| (position - start).max(0.0)),
|
||||
);
|
||||
insert_float(
|
||||
&mut lyrics,
|
||||
"until_next",
|
||||
end.map_or(-1.0, |end| (end - position).max(0.0)),
|
||||
);
|
||||
insert_float(
|
||||
&mut lyrics,
|
||||
"progress",
|
||||
start.zip(end).map_or(0.0, |(start, end)| {
|
||||
((position - start) / (end - start)).clamp(0.0, 1.0)
|
||||
}),
|
||||
);
|
||||
lyrics
|
||||
}
|
||||
|
||||
/// Analyzer meter fields (protocol v3). They report the decoded signal as a
|
||||
/// level meter would, so unlike `energy`/`bass`/... they are not scaled by
|
||||
/// the output volume; while paused or stopped they fall on their own.
|
||||
@@ -637,6 +700,12 @@ impl Default for ScriptRuntime {
|
||||
engine.register_fn("sqrt", |value: FLOAT| value.sqrt());
|
||||
engine.register_fn("abs", |value: FLOAT| value.abs());
|
||||
engine.register_fn("pow", |value: FLOAT, power: FLOAT| value.powf(power));
|
||||
engine.register_fn("matrix_text", matrix::matrix_text);
|
||||
engine.register_fn("lyric_layout", matrix::lyric_layout);
|
||||
engine.register_fn("cut_cells", matrix::cut_cells);
|
||||
engine.register_fn("cell_width", |text: &str| {
|
||||
unicode_width::UnicodeWidthStr::width(text) as i64
|
||||
});
|
||||
Self {
|
||||
engine,
|
||||
cached_path: None,
|
||||
@@ -753,7 +822,7 @@ enum DrawCommand {
|
||||
y: u16,
|
||||
ch: String,
|
||||
fg: Color,
|
||||
bg: Color,
|
||||
bg: Option<Color>,
|
||||
mods: Modifier,
|
||||
},
|
||||
HLine {
|
||||
@@ -808,7 +877,7 @@ enum DrawCommand {
|
||||
Dots {
|
||||
points: Vec<(u16, u16)>,
|
||||
fg: Color,
|
||||
bg: Color,
|
||||
bg: Option<Color>,
|
||||
mods: Modifier,
|
||||
},
|
||||
/// A thin straight line of braille dots between two dot coordinates.
|
||||
@@ -833,6 +902,11 @@ impl DrawCommand {
|
||||
.ok_or_else(|| "missing op".to_string())?;
|
||||
let fg = map_color(&map, "fg").unwrap_or(Color::White);
|
||||
let bg = map_color(&map, "bg").unwrap_or(Color::Black);
|
||||
let preserve_bg = map
|
||||
.get("preserve_bg")
|
||||
.and_then(|value| value.as_bool().ok())
|
||||
.unwrap_or(false);
|
||||
let overlay_bg = (!preserve_bg).then_some(bg);
|
||||
let mods = map_modifiers(&map);
|
||||
match op.as_str() {
|
||||
"clear" => Ok(DrawCommand::Clear { bg }),
|
||||
@@ -841,7 +915,7 @@ impl DrawCommand {
|
||||
y: map_u16(&map, "y").ok_or_else(|| "cell.y must be an integer".to_string())?,
|
||||
ch: map_string(&map, "ch").unwrap_or_else(|| " ".to_string()),
|
||||
fg,
|
||||
bg,
|
||||
bg: overlay_bg,
|
||||
mods,
|
||||
}),
|
||||
"hline" => Ok(DrawCommand::HLine {
|
||||
@@ -905,7 +979,7 @@ impl DrawCommand {
|
||||
.map(|[x, y]| (*x, *y))
|
||||
.collect(),
|
||||
fg,
|
||||
bg,
|
||||
bg: overlay_bg,
|
||||
mods,
|
||||
})
|
||||
}
|
||||
@@ -930,13 +1004,18 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) {
|
||||
fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCommand]) {
|
||||
// Each command sets the cell's whole attribute set, so a plain command
|
||||
// drawn over a bold or dim one does not inherit its attributes.
|
||||
let styled = |fg: Color, bg: Color, mods: Modifier| {
|
||||
let foreground = |fg: Color, mods: Modifier| {
|
||||
Style::new()
|
||||
.fg(fg)
|
||||
.bg(bg)
|
||||
.add_modifier(mods)
|
||||
.remove_modifier(Modifier::all().difference(mods))
|
||||
};
|
||||
let styled = |fg, bg, mods| foreground(fg, mods).bg(bg);
|
||||
// Leaving Style.bg unset preserves the background already drawn into a cell.
|
||||
let overlay = |fg, bg: Option<Color>, mods| {
|
||||
let style = foreground(fg, mods);
|
||||
bg.map_or(style, |bg| style.bg(bg))
|
||||
};
|
||||
for command in commands {
|
||||
match command {
|
||||
DrawCommand::Clear { bg } => fill_rect(
|
||||
@@ -953,7 +1032,7 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo
|
||||
bg,
|
||||
mods,
|
||||
} => {
|
||||
write_cell(buffer, area, *x, *y, ch, styled(*fg, *bg, *mods));
|
||||
write_cell(buffer, area, *x, *y, ch, overlay(*fg, *bg, *mods));
|
||||
}
|
||||
DrawCommand::HLine {
|
||||
x,
|
||||
@@ -1073,7 +1152,7 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo
|
||||
bg,
|
||||
mods,
|
||||
} => {
|
||||
let style = styled(*fg, *bg, *mods);
|
||||
let style = overlay(*fg, *bg, *mods);
|
||||
for (dot_x, dot_y) in points {
|
||||
plot_dot(buffer, area, *dot_x, *dot_y, style);
|
||||
}
|
||||
@@ -1488,6 +1567,85 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lyric_preset_animates_timed_lines_and_uses_unicode_fallback() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
file.path(),
|
||||
include_str!("visualizations/lyrics_in_motion.rhai"),
|
||||
)
|
||||
.unwrap();
|
||||
let mut runtime = ScriptRuntime::default();
|
||||
let mut state = AppState::default();
|
||||
let version = crate::lyrics::manual_version(
|
||||
"Timed",
|
||||
"[00:01]FIRST\n[00:05]SECOND\n[00:09]歌詞\n[00:13]Снова над городом встаёт солнце",
|
||||
)
|
||||
.unwrap();
|
||||
state.lyrics.document = crate::lyrics::Document::new(&version);
|
||||
state.lyrics.versions.push(version);
|
||||
let mut render = |position, width, height| {
|
||||
let mut input = test_input();
|
||||
insert_int(&mut input, "width", width);
|
||||
insert_int(&mut input, "height", height);
|
||||
input.insert("lyrics".into(), lyrics_input(&state, position).into());
|
||||
runtime.render(file.path(), input).unwrap()
|
||||
};
|
||||
let matrix_start = |commands: &[DrawCommand]| {
|
||||
commands
|
||||
.iter()
|
||||
.find_map(|command| match command {
|
||||
DrawCommand::Text { x, y, text, .. }
|
||||
if text.chars().any(|c| ('▀'..='▟').contains(&c)) =>
|
||||
{
|
||||
Some((*x, *y))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("block lyric spans")
|
||||
};
|
||||
assert_ne!(
|
||||
matrix_start(&render(1.05, 80, 24)),
|
||||
matrix_start(&render(1.75, 80, 24))
|
||||
);
|
||||
assert!(
|
||||
render(5.1, 80, 24)
|
||||
.iter()
|
||||
.any(|command| matches!(command, DrawCommand::Dots { .. }))
|
||||
);
|
||||
assert!(
|
||||
render(10.0, 80, 24)
|
||||
.iter()
|
||||
.any(|command| matches!(command, DrawCommand::Text { text, .. } if text == "歌詞"))
|
||||
);
|
||||
let wide = render(14.0, 180, 45);
|
||||
let block_widths: std::collections::BTreeSet<_> = wide
|
||||
.iter()
|
||||
.filter_map(|command| match command {
|
||||
DrawCommand::Text { text, .. }
|
||||
if text.chars().any(|c| ('▀'..='▟').contains(&c)) =>
|
||||
{
|
||||
Some(text.chars().count())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
block_widths.contains(&63),
|
||||
"expected a large Cyrillic headline"
|
||||
);
|
||||
assert!(
|
||||
block_widths.contains(&27),
|
||||
"expected smaller supporting text"
|
||||
);
|
||||
assert!(
|
||||
render(14.0, 34, 8)
|
||||
.iter()
|
||||
.any(|command| matches!(command, DrawCommand::Text { text, .. }
|
||||
if text.starts_with("Снова над городом")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_default_script_is_migrated() {
|
||||
let scope = primary_bundled_script();
|
||||
@@ -2179,6 +2337,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn particle_overlays_preserve_the_background_under_dots_and_shapes() {
|
||||
let file = tempfile::NamedTempFile::new().unwrap();
|
||||
std::fs::write(
|
||||
file.path(),
|
||||
r#"
|
||||
fn render(input) {
|
||||
[
|
||||
#{op: "rect", x: 0, y: 1, w: 4, h: 1, bg: 0x254368},
|
||||
#{op: "dots", points: [0, 4, 1, 4], fg: 0xcceeff, preserve_bg: true},
|
||||
#{op: "cell", x: 1, y: 1, ch: "✦", fg: 0xffffff, preserve_bg: true},
|
||||
#{op: "cell", x: 2, y: 1, ch: "+", fg: 0xffffff}
|
||||
]
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let commands = ScriptRuntime::default()
|
||||
.render(file.path(), test_input())
|
||||
.unwrap();
|
||||
let area = Rect::new(0, 0, 4, 3);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
render_commands_to_buffer(&mut buffer, area, &commands);
|
||||
|
||||
for (column, symbol) in [(0, "⠉"), (1, "✦")] {
|
||||
let cell = buffer.cell((column, 1)).unwrap();
|
||||
assert_eq!(cell.symbol(), symbol);
|
||||
assert_eq!(cell.bg, Color::Rgb(0x25, 0x43, 0x68));
|
||||
}
|
||||
assert_eq!(buffer.cell((2, 1)).unwrap().bg, Color::Black);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_modifiers_reach_the_buffer() {
|
||||
let command = DrawCommand::from_dynamic(Dynamic::from_map(
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! VFD dot-matrix glyphs encoded as two rows of Braille cells.
|
||||
use rhai::{Array, Dynamic};
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
pub(super) fn matrix_text(text: &str, width: i64) -> Array {
|
||||
let limit = (width.clamp(0, 512) / 3) as usize;
|
||||
let mut top = String::new();
|
||||
let mut bottom = String::new();
|
||||
for (index, ch) in text.chars().enumerate() {
|
||||
if index >= limit {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut uppercase = ch.to_uppercase();
|
||||
let Some(first) = uppercase.next() else {
|
||||
return Vec::new();
|
||||
};
|
||||
if uppercase.next().is_some() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(glyph) = glyph(first) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut cells = [[0; 3]; 2];
|
||||
for (y, row) in glyph.into_iter().enumerate() {
|
||||
for x in 0..5 {
|
||||
if row & (16 >> x) != 0 {
|
||||
cells[y / 4][x / 2] |= super::BRAILLE_BITS[y % 4][x % 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (first, second) in cells[0].into_iter().zip(cells[1]) {
|
||||
top.push(char::from_u32(super::BRAILLE_BASE | first).unwrap_or(' '));
|
||||
bottom.push(char::from_u32(super::BRAILLE_BASE | second).unwrap_or(' '));
|
||||
}
|
||||
}
|
||||
vec![Dynamic::from(top), Dynamic::from(bottom)]
|
||||
}
|
||||
|
||||
/// Fit the largest block glyphs that leave room for the surrounding UI.
|
||||
pub(super) fn lyric_layout(text: &str, width: i64, height: i64) -> Array {
|
||||
let words: Vec<_> = text.split_whitespace().collect();
|
||||
if words.len() >= 3 && width >= 60 && height >= 16 {
|
||||
// Pick a substantial word that fits the headline scale. Keep reading order.
|
||||
let focus = words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, word)| word.chars().count() as i64 * 9 <= width - 8)
|
||||
.max_by_key(|(index, word)| (word.chars().count(), usize::MAX - index));
|
||||
if let Some((index, word)) = focus {
|
||||
let headline = lyric_blocks(word, width - 8, 11, 3);
|
||||
let before = words[..index].join(" ");
|
||||
let after = words[index + 1..].join(" ");
|
||||
let supporting = |phrase: &str| lyric_blocks(phrase, width - 8, 9, 1);
|
||||
let above = supporting(&before);
|
||||
let below = supporting(&after);
|
||||
let fits = !headline.is_empty()
|
||||
&& (before.is_empty() || !above.is_empty())
|
||||
&& (after.is_empty() || !below.is_empty())
|
||||
&& (headline.len() + above.len() + below.len() + 2) as i64 <= height;
|
||||
if fits {
|
||||
return [above, headline, below]
|
||||
.into_iter()
|
||||
.filter(|rows| !rows.is_empty())
|
||||
.map(Dynamic::from)
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
let rows = lyric_blocks(text, width, height, 3);
|
||||
if rows.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![Dynamic::from(rows)]
|
||||
}
|
||||
}
|
||||
|
||||
fn lyric_blocks(text: &str, width: i64, height: i64, max_scale: usize) -> Array {
|
||||
let width = width.clamp(0, 512) as usize;
|
||||
let height = height.clamp(0, 32) as usize;
|
||||
let Some(words) = text
|
||||
.split_whitespace()
|
||||
.map(|word| {
|
||||
word.chars()
|
||||
.map(|ch| {
|
||||
let mut uppercase = ch.to_uppercase();
|
||||
let first = uppercase.next()?;
|
||||
if uppercase.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
glyph(first)
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
if words.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
// 2×2 pixels per terminal cell, with a blank pixel column per letter.
|
||||
const BLOCKS: [char; 16] = [
|
||||
' ', '▘', '▝', '▀', '▖', '▌', '▞', '▛', '▗', '▚', '▐', '▜', '▄', '▙', '▟', '█',
|
||||
];
|
||||
for scale in (1..=max_scale).rev() {
|
||||
let columns = width / (3 * scale);
|
||||
let rows = (7 * scale).div_ceil(2);
|
||||
let max_lines = ((height + 1) / (rows + 1)).min(3);
|
||||
if max_lines == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut lines: Vec<Vec<[u8; 7]>> = vec![Vec::new()];
|
||||
for word in &words {
|
||||
let line = lines.last_mut().unwrap();
|
||||
if word.len() > columns {
|
||||
lines.clear();
|
||||
break;
|
||||
}
|
||||
if line.is_empty() {
|
||||
line.extend(word);
|
||||
} else if line.len() + word.len() < columns {
|
||||
line.push([0; 7]);
|
||||
line.extend(word);
|
||||
} else {
|
||||
lines.push(word.clone());
|
||||
}
|
||||
}
|
||||
if lines.is_empty() || lines.len() > max_lines {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
for line in lines {
|
||||
if !result.is_empty() {
|
||||
result.push(Dynamic::from(String::new()));
|
||||
}
|
||||
for y in 0..rows {
|
||||
let mut row = String::new();
|
||||
for letter in &line {
|
||||
for x in 0..3 * scale {
|
||||
let mut mask = 0;
|
||||
for dy in 0..2 {
|
||||
let pixel_y = (2 * y + dy) / scale;
|
||||
for dx in 0..2 {
|
||||
let pixel_x = (2 * x + dx) / scale;
|
||||
if pixel_y < 7 && letter[pixel_y] & (32 >> (pixel_x + 1)) != 0 {
|
||||
mask |= 1 << (2 * dy + dx);
|
||||
}
|
||||
}
|
||||
}
|
||||
row.push(BLOCKS[mask]);
|
||||
}
|
||||
}
|
||||
result.push(Dynamic::from(row));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub(super) fn cut_cells(text: &str, skip: i64, width: i64) -> String {
|
||||
let start = skip.max(0) as usize;
|
||||
let end = start.saturating_add(width.clamp(0, 512) as usize);
|
||||
let mut position = 0_usize;
|
||||
let mut result = String::new();
|
||||
for ch in text.chars() {
|
||||
let width = ch.width().unwrap_or_default();
|
||||
let next = position.saturating_add(width);
|
||||
if next > end {
|
||||
break;
|
||||
}
|
||||
if position >= start && (width > 0 || !result.is_empty()) {
|
||||
result.push(ch);
|
||||
} else if next > start && position < start {
|
||||
result.extend(std::iter::repeat_n(' ', next - start));
|
||||
}
|
||||
position = next;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn glyph(ch: char) -> Option<[u8; 7]> {
|
||||
Some(match ch {
|
||||
'A' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'B' => [30, 17, 17, 30, 17, 17, 30],
|
||||
'C' => [14, 17, 16, 16, 16, 17, 14],
|
||||
'D' => [30, 17, 17, 17, 17, 17, 30],
|
||||
'E' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'F' => [31, 16, 16, 30, 16, 16, 16],
|
||||
'G' => [14, 17, 16, 23, 17, 17, 15],
|
||||
'H' => [17, 17, 17, 31, 17, 17, 17],
|
||||
'I' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'J' => [7, 2, 2, 2, 2, 18, 12],
|
||||
'K' => [17, 18, 20, 24, 20, 18, 17],
|
||||
'L' => [16, 16, 16, 16, 16, 16, 31],
|
||||
'M' => [17, 27, 21, 21, 17, 17, 17],
|
||||
'N' => [17, 17, 25, 21, 19, 17, 17],
|
||||
'O' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'P' => [30, 17, 17, 30, 16, 16, 16],
|
||||
'Q' => [14, 17, 17, 17, 21, 18, 13],
|
||||
'R' => [30, 17, 17, 30, 20, 18, 17],
|
||||
'S' => [15, 16, 16, 14, 1, 1, 30],
|
||||
'T' => [31, 4, 4, 4, 4, 4, 4],
|
||||
'U' => [17, 17, 17, 17, 17, 17, 14],
|
||||
'V' => [17, 17, 17, 17, 17, 10, 4],
|
||||
'W' => [17, 17, 17, 21, 21, 21, 10],
|
||||
'X' => [17, 17, 10, 4, 10, 17, 17],
|
||||
'Y' => [17, 17, 10, 4, 4, 4, 4],
|
||||
'Z' => [31, 1, 2, 4, 8, 16, 31],
|
||||
'0' => [14, 17, 19, 21, 25, 17, 14],
|
||||
'1' => [4, 12, 4, 4, 4, 4, 14],
|
||||
'2' => [14, 17, 1, 2, 4, 8, 31],
|
||||
'3' => [31, 2, 4, 2, 1, 17, 14],
|
||||
'4' => [2, 6, 10, 18, 31, 2, 2],
|
||||
'5' => [31, 16, 30, 1, 1, 17, 14],
|
||||
'6' => [6, 8, 16, 30, 17, 17, 14],
|
||||
'7' => [31, 1, 2, 4, 8, 8, 8],
|
||||
'8' => [14, 17, 17, 14, 17, 17, 14],
|
||||
'9' => [14, 17, 17, 15, 1, 2, 12],
|
||||
' ' => [0, 0, 0, 0, 0, 0, 0],
|
||||
'.' => [0, 0, 0, 0, 0, 12, 12],
|
||||
',' => [0, 0, 0, 0, 12, 4, 8],
|
||||
':' => [0, 12, 12, 0, 12, 12, 0],
|
||||
';' => [0, 12, 12, 0, 12, 4, 8],
|
||||
'-' => [0, 0, 0, 31, 0, 0, 0],
|
||||
'—' => [0, 0, 0, 31, 0, 0, 0],
|
||||
'–' => [0, 0, 0, 31, 0, 0, 0],
|
||||
'\'' => [12, 4, 8, 0, 0, 0, 0],
|
||||
'’' => [12, 4, 8, 0, 0, 0, 0],
|
||||
'`' => [12, 4, 8, 0, 0, 0, 0],
|
||||
'"' => [10, 10, 10, 0, 0, 0, 0],
|
||||
'«' => [10, 10, 10, 0, 0, 0, 0],
|
||||
'»' => [10, 10, 10, 0, 0, 0, 0],
|
||||
'“' => [10, 10, 10, 0, 0, 0, 0],
|
||||
'”' => [10, 10, 10, 0, 0, 0, 0],
|
||||
'!' => [4, 4, 4, 4, 4, 0, 4],
|
||||
'?' => [14, 17, 1, 2, 4, 0, 4],
|
||||
'&' => [12, 18, 20, 8, 21, 18, 13],
|
||||
'/' => [0, 1, 2, 4, 8, 16, 0],
|
||||
'(' => [2, 4, 8, 8, 8, 4, 2],
|
||||
')' => [8, 4, 2, 2, 2, 4, 8],
|
||||
'[' => [14, 8, 8, 8, 8, 8, 14],
|
||||
']' => [14, 2, 2, 2, 2, 2, 14],
|
||||
'+' => [0, 4, 4, 31, 4, 4, 0],
|
||||
'#' => [10, 10, 31, 10, 31, 10, 10],
|
||||
'*' => [0, 4, 21, 14, 21, 4, 0],
|
||||
'_' => [0, 0, 0, 0, 0, 0, 31],
|
||||
'·' => [0, 0, 0, 4, 0, 0, 0],
|
||||
'•' => [0, 0, 0, 4, 0, 0, 0],
|
||||
'…' => [0, 0, 0, 0, 0, 0, 21],
|
||||
'%' => [24, 25, 2, 4, 8, 19, 3],
|
||||
'=' => [0, 0, 31, 0, 31, 0, 0],
|
||||
'@' => [14, 17, 1, 13, 21, 21, 14],
|
||||
'$' => [4, 15, 20, 14, 5, 30, 4],
|
||||
'А' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'В' => [30, 17, 17, 30, 17, 17, 30],
|
||||
'Е' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'К' => [17, 18, 20, 24, 20, 18, 17],
|
||||
'М' => [17, 27, 21, 21, 17, 17, 17],
|
||||
'Н' => [17, 17, 17, 31, 17, 17, 17],
|
||||
'О' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Р' => [30, 17, 17, 30, 16, 16, 16],
|
||||
'С' => [14, 17, 16, 16, 16, 17, 14],
|
||||
'Т' => [31, 4, 4, 4, 4, 4, 4],
|
||||
'Х' => [17, 17, 10, 4, 10, 17, 17],
|
||||
'З' => [31, 2, 4, 2, 1, 17, 14],
|
||||
'Ё' => [10, 0, 31, 16, 30, 16, 31],
|
||||
'Б' => [31, 16, 16, 30, 17, 17, 30],
|
||||
'Г' => [31, 16, 16, 16, 16, 16, 16],
|
||||
'Д' => [6, 10, 10, 10, 10, 31, 17],
|
||||
'Ж' => [21, 21, 14, 4, 14, 21, 21],
|
||||
'И' => [17, 17, 19, 21, 25, 17, 17],
|
||||
'Й' => [10, 4, 17, 19, 21, 25, 17],
|
||||
'Л' => [7, 9, 9, 9, 9, 9, 17],
|
||||
'П' => [31, 17, 17, 17, 17, 17, 17],
|
||||
'У' => [17, 17, 17, 15, 1, 17, 14],
|
||||
'Ф' => [4, 14, 21, 21, 21, 14, 4],
|
||||
'Ц' => [18, 18, 18, 18, 18, 31, 1],
|
||||
'Ч' => [17, 17, 17, 15, 1, 1, 1],
|
||||
'Ш' => [21, 21, 21, 21, 21, 21, 31],
|
||||
'Щ' => [21, 21, 21, 21, 21, 31, 1],
|
||||
'Ъ' => [24, 8, 8, 14, 9, 9, 14],
|
||||
'Ы' => [17, 17, 17, 25, 21, 21, 25],
|
||||
'Ь' => [16, 16, 16, 30, 17, 17, 30],
|
||||
'Э' => [14, 17, 1, 7, 1, 17, 14],
|
||||
'Ю' => [18, 21, 21, 29, 21, 21, 18],
|
||||
'Я' => [15, 17, 17, 15, 5, 9, 17],
|
||||
'І' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'Ї' => [10, 0, 14, 4, 4, 4, 14],
|
||||
'Є' => [14, 17, 16, 30, 16, 17, 14],
|
||||
'Ґ' => [1, 31, 16, 16, 16, 16, 16],
|
||||
'Ў' => [10, 4, 17, 15, 1, 17, 14],
|
||||
'À' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Á' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Â' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Ä' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Ã' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Å' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'Ç' => [14, 17, 16, 16, 16, 17, 14],
|
||||
'È' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'É' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'Ê' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'Ë' => [31, 16, 16, 30, 16, 16, 31],
|
||||
'Ì' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'Í' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'Î' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'Ï' => [14, 4, 4, 4, 4, 4, 14],
|
||||
'Ñ' => [17, 17, 25, 21, 19, 17, 17],
|
||||
'Ò' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Ó' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Ô' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Ö' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Õ' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Ø' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Ù' => [17, 17, 17, 17, 17, 17, 14],
|
||||
'Ú' => [17, 17, 17, 17, 17, 17, 14],
|
||||
'Û' => [17, 17, 17, 17, 17, 17, 14],
|
||||
'Ü' => [17, 17, 17, 17, 17, 17, 14],
|
||||
'Ý' => [17, 17, 10, 4, 4, 4, 4],
|
||||
'Ÿ' => [17, 17, 10, 4, 4, 4, 4],
|
||||
'Œ' => [14, 17, 17, 17, 17, 17, 14],
|
||||
'Æ' => [14, 17, 17, 31, 17, 17, 17],
|
||||
'ß' => [15, 16, 16, 14, 1, 1, 30],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user