Spotify for Fennec OS: native TV client

Rust + Slint on sf-ui's Liquid Glass, with the page engine of Netflex TV.
librespot plays (GStreamer on the TV) and makes the TV a Spotify Connect
device; the Web API (token from the session) feeds the pages.

- Sign-in with the phone: a pairing code / QR code (spotify.com/pair,
  OAuth device flow) or picking the TV in the Spotify app (zeroconf).
- Home, search, library, playlist / album / liked songs / podcast pages,
  artist pages, settings; the user's picture top right.
- Now playing: seek, shuffle, repeat, like, synced lyrics, queue.
- package.sh builds x86-64 and aarch64 (Raspberry Pi); the Gitea CI
  releases both on a tag.
- tools/mock_server.py and SPOTIFY_MOCK for work without an account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-11-03 17:23:34 +01:00
commit 06e054d4ae
34 changed files with 17083 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
# On a tag (v1.2.3): build the app and publish a release with the store
# assets: app.toml, the x86-64 package and the aarch64 one (Raspberry Pi,
# docs/store.md in Fennec OS). sf-ui and sf-pack come from the Fennec SDK (public).
#
# Runner hygiene (shared host, little disk): runs in the runner image that is
# already on the host (no image pull), uses no `uses:` actions (no action
# cache), and deletes everything it made at the end. The image is Ubuntu
# 24.04: its glibc is older than the TV's (Debian trixie), so the binary runs.
name: release
on:
push:
tags: ["v*"]
jobs:
release:
runs-on: build
container:
image: docker.gitea.com/runner-images:ubuntu-latest
env:
W: /tmp/fennec-spotify
CARGO_HOME: /tmp/fennec-spotify/cargo
RUSTUP_HOME: /tmp/fennec-spotify/rustup
CARGO_TARGET_DIR: /tmp/fennec-spotify/target
CARGO_INCREMENTAL: "0"
SDK_GIT: https://gitea.bluefox.support/fennec/sdk
SDK_TAG: v0.1.2
steps:
- name: Checkout
run: |
mkdir -p "$W"
git clone --depth 1 --branch "$GITHUB_REF_NAME" \
"${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" "$W/src"
v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$W/src/app.toml" | head -1)
[ "v$v" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME, but app.toml says $v" >&2; exit 1; }
- name: Toolchain
run: |
export DEBIAN_FRONTEND=noninteractive
# arm64 libraries for the Raspberry Pi build (package.sh --arm):
# Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only.
. /etc/os-release
dpkg --add-architecture arm64
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
[ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list
printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \
"$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources
apt-get update -qq
# Multiarch dev packages for both architectures; for arm64 only the
# GStreamer runtime libraries: its dev packages can't be installed for
# two architectures at once (package.sh --arm links the libraries).
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libglib2.0-dev"
apt-get install -y -qq --no-install-recommends build-essential pkg-config \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \
$libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) \
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64
rm -rf /var/lib/apt/lists/*
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu
"$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack
- name: Build
run: |
export PATH="$CARGO_HOME/bin:$PATH"
"$W/src/package.sh"
"$W/src/package.sh" --arm
- name: Release
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases"
id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
for f in "$W"/src/dist/*; do
curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null
done
- name: Clean up
if: always()
run: |
rm -rf "$W"
df -h / | tail -1

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
/target
/pkg
/dist
/dist-arm
/.cargo

55
AGENTS.md Normal file
View File

@@ -0,0 +1,55 @@
# Notes for AI agents working on Spotify for Fennec OS
Read first (Fennec SDK, https://gitea.bluefox.support/fennec/sdk):
- `docs/store-app-guide.md`: what a Fennec OS store app must be (manifest, sandbox, remote, packaging, release).
- `docs/sf-ui.md`: the UI kit. Liquid Glass model, components, focus, dev tools, pitfalls.
The page engine and the controller come from Netflex TV (`fennec/netflex`); keep them close to it.
## Layout
```
app.toml store manifest (id support.bluefox.spotify; permissions network, gpu, audio)
src/main.rs window, glass layer (lists every exported [GlassRect]), images, controller
src/spotify.rs librespot: session, Spotify Connect (Spirc), sign-in (zeroconf + pairing code), player; Cmd in, Event out
src/api.rs Spotify Web API (browsing, library, search, queue), token from the session; short GET cache, 429 retry
src/app.rs Controller: screen stack, keys, input/picker/toast, backdrop, sign-in screen, engine events, avatar
src/nowplaying.rs Most szól: playback state, controls, seek, lyrics, queue
src/page.rs the line-based page engine: lines (L) and chips (Ch) -> layout, focus, scroll, lazy images
src/screens/mod.rs sections of the top nav, cards, track rows, the track "+" menu, opening a card id
src/screens/home.rs Kezdőlap: recently played, playlists (+ liked), top artists/tracks, saved albums, new releases
src/screens/search.rs Keresés: embedded keyboard, songs, artists, albums, playlists, podcasts
src/screens/library.rs Könyvtár: tabs, grid, paging (artists by cursor)
src/screens/collection.rs playlist / album / liked songs / podcast: header, Lejátszás/Keverés/Mentés, track rows, paging
src/screens/artist.rs artist: header, popular tracks, albums, singles, appearances
src/screens/settings.rs Beállítások: account, Connect name, quality, normalisation, autoplay, look
src/config.rs config.toml: device id/name, bitrate, normalise, autoplay, glass
src/format.rs Hungarian texts: times, counts, dates
src/task.rs blocking work on a thread, result on the UI thread
ui/app.slint root: screen fades, one FocusScope -> Rust `key`, glass exports
ui/page.slint LinePage: draws the lines Rust lays out (nav, now playing capsule, avatar, keyboard)
ui/nowplaying.slint the now playing screen and its panel (lyrics / queue)
ui/signin.slint ConnectScreen (QR code + Spotify app), InputScreen, MessageScreen
ui/icons.slint SpIcon: shuffle, repeat, heart, lyrics, queue, devices (+ sf-ui's icons)
tools/mock_server.py stand-in Web API with made-up data (with SPOTIFY_MOCK=1: no librespot)
```
## Rules of this codebase
- **Rust owns state and focus.** Slint only draws. Every key goes to `Controller::key`, except while an on-screen keyboard has the focus.
- **Engine thread:** librespot runs on its own tokio runtime. Talk to it with `Engine::send(Cmd)`; its `Event`s reach the UI thread through `slint::invoke_from_event_loop`. Blocking calls (`Engine::token`, `Engine::lyrics`, every `Api` method) only off the UI thread (`task::spawn`, `Cx::spawn`).
- **Playback is Spirc's:** play a context (`Cmd::Context`) whenever possible, so next/previous, shuffle and the phone's view work. `Cx::play` also opens Most szól.
- **Short borrows:** never hold `state.borrow_mut()` while calling `images.load*`; a cached picture calls back at once.
- **Glass:** new glass elements need their `glass` listed in a root `out property <[GlassRect]>`, and that array added in `main.rs`. Nothing Slint draws may sit under a glass pane.
- **Slint names:** a property may not be called `focus` (a function) or `cover` (an ImageFit value).
- **Texts are Hungarian.**
- **Testing on the developer's PC:** never open windows on the primary monitor. Use `SPOTIFY_WINDOW_POS` to put the window on another monitor, or run headless.
## Check your change
```sh
cargo test
python3 tools/mock_server.py --port 7890 &
SPOTIFY_MOCK=1 SPOTIFY_API=http://127.0.0.1:7890/v1 SF_UI_SIZE=1600x900 \
SF_UI_KEYS="wait wait down enter wait wait" SF_UI_SNAPSHOT=/tmp/shot.png cargo run # then look at /tmp/shot.png
```

9207
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

46
Cargo.toml Normal file
View File

@@ -0,0 +1,46 @@
[package]
name = "spotify-tv"
description = "Spotify for Fennec OS: native TV client with Liquid Glass, Spotify Connect and librespot playback"
version = "0.1.0"
edition = "2024"
# sf-ui (and Slint) are GPL-3.0 on a TV box; librespot is MIT.
license = "GPL-3.0-only"
publish = false
[dependencies]
# The Fennec OS UI kit (Fennec SDK): Liquid Glass, TV components, images.
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.1" }
slint = "1.18"
anyhow = "1"
log = "0.4"
env_logger = "0.11"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.9"
ureq = { version = "3", features = ["json"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "signal"] }
futures-util = { version = "0.3", default-features = false }
# The pairing QR code on the sign-in screen.
qrcode = { version = "0.14", default-features = false }
# Spotify: session, Connect (Spirc), zeroconf sign-in, playback.
librespot-core = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-connect = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
librespot-discovery = { version = "0.8", default-features = false, features = ["with-libmdns"] }
librespot-metadata = { version = "0.8", default-features = false }
# Sound: GStreamer on the TV (PipeWire), rodio elsewhere (UI work on Windows).
[target.'cfg(target_os = "linux")'.dependencies]
librespot-playback = { version = "0.8", default-features = false, features = ["gstreamer-backend", "rustls-tls-webpki-roots"] }
[target.'cfg(not(target_os = "linux"))'.dependencies]
librespot-playback = { version = "0.8", default-features = false, features = ["rodio-backend", "rustls-tls-webpki-roots"] }
[build-dependencies]
slint-build = "1.18"
[profile.release]
lto = "thin"
strip = true
# Its own workspace (not part of any checkout around it).
[workspace]

49
README.md Normal file
View File

@@ -0,0 +1,49 @@
# Spotify for Fennec OS
Natív Spotify kliens Fennec OS-re (store app, `support.bluefox.spotify`). Spotify Premium fiók kell hozzá.
- **Felület:** Rust + Slint az sf-ui Liquid Glass-ával, ugyanazzal a lapmotorral, mint a Netflex TV.
- **Lejátszás:** [librespot](https://github.com/librespot-org/librespot) (Rust), GStreamerrel (PipeWire). A TV teljes értékű **Spotify Connect** eszköz: a telefonról is irányítható, és a lejátszás átvihető rá vagy róla.
- **Bejelentkezés a telefonnal**, kétféleképpen:
- **QR-kód / párosítókód:** a TV QR-kódot és rövid kódot mutat. A telefonon a `spotify.com/pair` oldalon kell bejelentkezni, a TV magától belép. Nem kell hozzá ugyanaz a hálózat.
- **A Spotify appból:** ugyanazon a Wi-Fin a TV megjelenik a telefon eszközlistájában (zeroconf). Kiválasztva bejelentkezik.
A belépés megmarad (`$HOME/.cache/spotify-tv`).
- **Képernyők:** Kezdőlap (legutóbb játszott, lejátszási listák a Kedvelt dalokkal, kedvenc előadók és dalok, elmentett albumok, új megjelenések), Keresés képernyő-billentyűzettel (dalok, előadók, albumok, listák, podcastok), Könyvtár (listák, albumok, előadók, podcastok), lejátszási lista / album / Kedvelt dalok / podcast oldal, előadó oldal, Beállítások. Jobb fent a bejelentkezett felhasználó képe.
- **Most szól:** nagy borító, tekerés, keverés, ismétlés (lista / szám), kedvelés, szinkronizált dalszöveg, lejátszási sor. A dalsorok „+” gombja: sorba tétel, kedvelés, album, előadó.
- **Beállítások:** kijelentkezés, a TV neve (Connect), hangminőség (96 / 160 / 320 kbit/s), hangerő-kiegyenlítés, automatikus lejátszás, megjelenés (üveg / matt).
Böngészéshez a Spotify Web API-t használja, a librespot munkamenetéből kapott tokennel. A Spotify szerint ez nem hivatalos kliens. Ha változtatnak a protokollon, a librespot frissítéséig leállhat.
## Fejlesztés
Az sf-ui a [Fennec SDK](https://gitea.bluefox.support/fennec/sdk)-ból jön, git-függőségként (tag). Ha az sf-ui-t is fejleszted mellette, tedd a `.cargo/config.toml` fájlba (ne commitold):
```toml
[patch."https://gitea.bluefox.support/fennec/sdk"]
sf-ui = { path = "../sdk/sf-ui" }
```
Fiók nélkül, kitalált adatokkal (mock):
```sh
python3 tools/mock_server.py --port 7890
SPOTIFY_MOCK=1 SPOTIFY_API=http://127.0.0.1:7890/v1 SPOTIFY_WINDOWED=1 cargo run
# SPOTIFY_MOCK=signin: a bejelentkező képernyő egy mintakóddal
```
- **Windowson** is fordul és fut (a hang ott rodio-val szól), a TV-n GStreamer.
- **Linuxon** (Debian trixie / WSL) kell még: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libfontconfig1-dev libxkbcommon-dev`.
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1600x900 SF_UI_KEYS="wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (az SDK `docs/sf-ui.md` 11. fejezete). `SPOTIFY_WINDOW_POS=x,y`: hol nyíljon az ablak (például egy másik monitoron).
## Kiadás
1. Emeld a `version` értékét az `app.toml`-ban és a `Cargo.toml`-ban.
2. `git tag v0.1.1 && git push --tags`.
3. A Gitea CI (`.gitea/workflows/release.yml`) megépíti x86-64-re és aarch64-re (Raspberry Pi), és release-t csinál a store-fájlokkal. Secret nem kell hozzá.
Helyben: `./package.sh`, illetve `./package.sh --arm` (kell hozzá az `sf-pack`, lásd a szkript fejlécét).
A TV-n: Store → Források → a repó címe.
## Licenc
GPL-3.0 (az sf-ui és a Slint miatt). A librespot MIT licencű.

20
app.toml Normal file
View File

@@ -0,0 +1,20 @@
# Fennec OS store app manifest (store-app-guide.md in the Fennec SDK).
id = "support.bluefox.spotify"
name = "Spotify"
# Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
version = "0.1.0"
kind = "exec"
category = "Zene"
description = "Zene és podcastok natívan, Spotify Connecttel: a telefonról is irányítható. Spotify Premium fiók kell hozzá."
author = "Bluefox"
license = "GPL-3.0-only"
homepage = "https://gitea.bluefox.support/fennec/spotify"
exec = ["bin/spotify-tv"]
icon = "icon.png"
accent = "#1ED760"
palette = ["#1ed760", "#0d5c2b", "#060a07"]
[sandbox]
# network: Spotify and Spotify Connect (zeroconf on the local network);
# gpu: the glass UI; audio: sound.
permissions = ["network", "gpu", "audio"]

7
build.rs Normal file
View File

@@ -0,0 +1,7 @@
fn main() {
// sf-ui's build script publishes where its Slint library is ("@sf-ui").
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
let config = slint_build::CompilerConfiguration::new()
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
slint_build::compile_with_config("ui/app.slint", config).expect("compiling ui/app.slint");
}

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

73
package.sh Executable file
View File

@@ -0,0 +1,73 @@
#!/usr/bin/env bash
# Builds the store release assets into dist/:
#
# ./package.sh app.toml and support.bluefox.spotify-<version>.tar.zst
# (x86-64; dist/ is emptied first)
# ./package.sh --arm adds support.bluefox.spotify-<version>-aarch64.tar.zst
# (Raspberry Pi, cross-compiled)
#
# Build on Debian trixie or older (the TV's glibc), with the GStreamer dev
# packages (libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev) and
# sf-pack from the Fennec SDK:
# cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.1 sf-pack
# --arm also needs gcc-aarch64-linux-gnu, the arm64 (multiarch) dev packages
# of fontconfig, freetype, xkbcommon and glib, and the arm64 GStreamer
# runtime libraries (libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64).
# Not necessarily the GStreamer dev packages: they can't be installed for two
# architectures at once, so the build links the runtime libraries directly.
set -euo pipefail
cd "$(dirname "$0")"
target="${CARGO_TARGET_DIR:-target}"
id=$(sed -n 's/^id *= *"\(.*\)".*/\1/p' app.toml | head -1)
version=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' app.toml | head -1)
bin=spotify-tv
# pack <binary> <out dir>: the package with this binary.
pack() {
rm -rf pkg
mkdir -p pkg/bin
cp app.toml icon.png pkg/
install -m755 "$1" pkg/bin/$bin
sf-pack build pkg "$2"
sf-pack verify "$2"
rm -rf pkg
}
if [ "${1:-}" != --arm ]; then
cargo build --release --locked
rm -rf dist
pack "$target/release/$bin" dist
else
t=aarch64-unknown-linux-gnu
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++
export AR_aarch64_unknown_linux_gnu=aarch64-linux-gnu-ar
export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/
export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig
rustup target list --installed | grep -qx "$t" || rustup target add "$t"
# GStreamer without pkg-config (system-deps): link the runtime libraries
# through a folder of unversioned names. librespot plays through
# appsrc -> audioconvert -> autoaudiosink: core, base, app, audio.
mkdir -p "$target"
gst="$(cd "$target" && pwd)/arm-gstreamer"
rm -rf "$gst" && mkdir -p "$gst"
# system-deps key (the pkg-config name) and the library it stands for.
for pair in GSTREAMER_1_0:gstreamer-1.0 GSTREAMER_BASE_1_0:gstbase-1.0 \
GSTREAMER_APP_1_0:gstapp-1.0 GSTREAMER_AUDIO_1_0:gstaudio-1.0; do
key=${pair%%:*} lib=${pair#*:}
so=/usr/lib/aarch64-linux-gnu/lib$lib.so.0
[ -e "$so" ] || { echo "missing $so (install the arm64 GStreamer runtime libraries)" >&2; exit 1; }
ln -s "$so" "$gst/lib$lib.so"
export "SYSTEM_DEPS_${key}_NO_PKG_CONFIG=1" "SYSTEM_DEPS_${key}_LIB=$lib" "SYSTEM_DEPS_${key}_SEARCH_NATIVE=$gst"
done
cargo build --release --locked --target "$t"
rm -rf dist-arm
pack "$target/$t/release/$bin" dist-arm
# Fennec OS on ARM looks for <id>-<version>-aarch64.tar.zst (docs/store.md).
mkdir -p dist
mv "dist-arm/$id-$version.tar.zst" "dist/$id-$version-aarch64.tar.zst"
[ -f dist/app.toml ] || mv dist-arm/app.toml dist/
rm -rf dist-arm
fi
ls -l dist

643
src/api.rs Normal file
View File

@@ -0,0 +1,643 @@
//! Spotify Web API (api.spotify.com/v1): browsing, the library, search, the
//! queue. The access token comes from the librespot session (spotify::Engine).
//!
//! Every answer is parsed leniently (missing fields default), since Spotify's
//! objects differ a bit between endpoints. GET answers are cached for a short
//! while: a TV jumps back and forth between the same pages, and Spotify
//! rate-limits busy clients (429 + Retry-After, honoured once).
use std::collections::HashMap;
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use crate::spotify::Engine;
pub const API: &str = "https://api.spotify.com/v1";
const CACHE_FOR: Duration = Duration::from_secs(90);
// ---------------------------------------------------------------------------- objects
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Image {
pub url: String,
pub width: Option<u32>,
}
/// The picture closest to `want` px wide (Spotify lists them largest first).
pub fn pick(images: &[Image], want: u32) -> String {
let mut best: Option<&Image> = None;
for i in images {
let w = i.width.unwrap_or(640);
best = match best {
None => Some(i),
Some(b) => {
let bw = b.width.unwrap_or(640);
// Prefer the smallest that is still big enough.
let better = if w >= want && bw >= want { w < bw } else { w > bw };
Some(if better { i } else { b })
}
};
}
best.map(|i| i.url.clone()).unwrap_or_default()
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Named {
pub id: String,
pub name: String,
pub uri: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Album {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub artists: Vec<Named>,
pub release_date: String,
pub total_tracks: u32,
pub album_type: String,
pub label: String,
pub tracks: Option<Paging<Track>>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Track {
pub id: String,
pub name: String,
pub uri: String,
/// "track" | "episode"
#[serde(rename = "type")]
pub kind: String,
pub duration_ms: u32,
pub explicit: bool,
pub artists: Vec<Named>,
pub album: Option<Album>,
pub track_number: u32,
pub is_playable: Option<bool>,
// episodes
pub images: Vec<Image>,
pub show: Option<Show>,
pub release_date: String,
pub description: String,
pub resume_point: Option<ResumePoint>,
}
impl Track {
pub fn artist_names(&self) -> String {
if let Some(s) = &self.show {
return s.name.clone();
}
self.artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", ")
}
pub fn image(&self, want: u32) -> String {
if !self.images.is_empty() {
return pick(&self.images, want);
}
self.album.as_ref().map(|a| pick(&a.images, want)).or_else(|| self.show.as_ref().map(|s| pick(&s.images, want))).unwrap_or_default()
}
pub fn playable(&self) -> bool {
self.is_playable != Some(false) && !self.uri.is_empty() && !self.uri.starts_with("spotify:local:")
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ResumePoint {
pub fully_played: bool,
pub resume_position_ms: u32,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Owner {
pub id: String,
pub display_name: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Total {
pub total: u32,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Playlist {
pub id: String,
pub name: String,
pub uri: String,
pub images: Option<Vec<Image>>,
pub description: String,
pub owner: Owner,
pub tracks: Option<Total>,
pub items: Option<Total>,
pub followers: Option<Total>,
}
impl Playlist {
pub fn image(&self, want: u32) -> String {
self.images.as_deref().map(|i| pick(i, want)).unwrap_or_default()
}
pub fn count(&self) -> u32 {
self.tracks.as_ref().or(self.items.as_ref()).map(|t| t.total).unwrap_or(0)
}
pub fn owner_name(&self) -> String {
self.owner.display_name.clone().unwrap_or_else(|| self.owner.id.clone())
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Artist {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub followers: Option<Total>,
pub genres: Vec<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Show {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub publisher: String,
pub description: String,
pub total_episodes: u32,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Paging<T> {
/// Search answers may hold nulls.
pub items: Vec<Option<T>>,
pub next: Option<String>,
pub total: u32,
pub offset: u32,
}
impl<T> Default for Paging<T> {
fn default() -> Self {
Paging { items: Vec::new(), next: None, total: 0, offset: 0 }
}
}
impl<T: Clone> Paging<T> {
pub fn list(&self) -> Vec<T> {
self.items.iter().flatten().cloned().collect()
}
pub fn more(&self) -> bool {
self.next.is_some()
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct User {
pub id: String,
pub display_name: Option<String>,
pub product: String,
pub country: String,
pub images: Vec<Image>,
}
impl User {
pub fn name(&self) -> String {
self.display_name.clone().filter(|n| !n.is_empty()).unwrap_or_else(|| self.id.clone())
}
}
#[derive(Debug, Clone, Deserialize)]
struct Saved<T> {
track: Option<T>,
album: Option<T>,
show: Option<T>,
episode: Option<T>,
/// Playlist entries: newer answers call it "item".
item: Option<T>,
}
impl<T> Saved<T> {
fn into_inner(self) -> Option<T> {
self.track.or(self.item).or(self.album).or(self.show).or(self.episode)
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct PlayContext {
pub uri: String,
#[serde(rename = "type")]
pub kind: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Played {
pub track: Track,
pub context: Option<PlayContext>,
}
#[derive(Debug, Clone, Default)]
pub struct SearchResult {
pub tracks: Vec<Track>,
pub artists: Vec<Artist>,
pub albums: Vec<Album>,
pub playlists: Vec<Playlist>,
pub shows: Vec<Show>,
}
// ---------------------------------------------------------------------------- errors
#[derive(Debug)]
pub struct ApiError {
pub status: u16,
pub message: String,
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.message, self.status)
}
}
impl std::error::Error for ApiError {}
pub fn status_of(e: &anyhow::Error) -> Option<u16> {
e.downcast_ref::<ApiError>().map(|a| a.status)
}
/// A short Hungarian message for the screen.
pub fn describe(e: &anyhow::Error) -> String {
if let Some(a) = e.downcast_ref::<ApiError>() {
return a.message.clone();
}
for cause in e.chain() {
if let Some(u) = cause.downcast_ref::<ureq::Error>() {
return match u {
ureq::Error::Timeout(_) => "A Spotify nem válaszolt időben.".into(),
ureq::Error::Io(_) | ureq::Error::ConnectionFailed | ureq::Error::HostNotFound => "A Spotify nem érhető el. Ellenőrizd a hálózatot.".into(),
other => format!("Hálózati hiba: {other}"),
};
}
}
format!("{e:#}")
}
pub fn enc(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
// ---------------------------------------------------------------------------- client
/// Cheap to clone; usable from any thread (blocking calls).
#[derive(Clone)]
pub struct Api {
base: String,
engine: Engine,
agent: ureq::Agent,
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
}
impl Api {
pub fn new(engine: Engine) -> Api {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.timeout_connect(Some(Duration::from_secs(8)))
.http_status_as_error(false)
.user_agent(concat!("FennecSpotifyTV/", env!("CARGO_PKG_VERSION")))
.build()
.into();
let base = std::env::var("SPOTIFY_API").unwrap_or_else(|_| API.to_string());
Api { base: base.trim_end_matches('/').to_string(), engine, agent, cache: Arc::default() }
}
/// Forgets cached answers (after a change to the library).
pub fn forget(&self, prefix: &str) {
let full = format!("{}{prefix}", self.base);
self.cache.lock().unwrap().retain(|k, _| !k.starts_with(&full));
}
fn url(&self, path: &str) -> String {
if path.starts_with("http") { path.to_string() } else { format!("{}{path}", self.base) }
}
fn call(&self, method: &str, path: &str, cache: bool) -> Result<String> {
let url = self.url(path);
if cache && method == "GET" {
if let Some((at, body)) = self.cache.lock().unwrap().get(&url) {
if at.elapsed() < CACHE_FOR {
return Ok(body.clone());
}
}
}
let mut tries = 0;
loop {
tries += 1;
let auth = format!("Bearer {}", self.engine.token()?);
let resp = match method {
"GET" => self.agent.get(&url).header("Authorization", &auth).header("Accept-Language", "hu").call(),
"POST" => self.agent.post(&url).header("Authorization", &auth).send_empty(),
"PUT" => self.agent.put(&url).header("Authorization", &auth).send_empty(),
_ => self.agent.delete(&url).header("Authorization", &auth).call(),
}
.with_context(|| format!("{method} {path}"))?;
let status = resp.status().as_u16();
let retry = resp.headers().get("retry-after").and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
let mut text = String::new();
resp.into_body().into_reader().take(16 << 20).read_to_string(&mut text)?;
if status == 429 && tries == 1 {
let wait = retry.unwrap_or(2).min(8);
log::warn!("{path}: rate limited, waiting {wait} s");
std::thread::sleep(Duration::from_secs(wait));
continue;
}
if status == 502 || status == 503 {
if tries < 3 {
std::thread::sleep(Duration::from_millis(600));
continue;
}
}
if !(200..300).contains(&status) {
let v: serde_json::Value = serde_json::from_str(&text).unwrap_or_default();
let detail = v["error"]["message"].as_str().unwrap_or("").to_string();
log::warn!("{method} {path}: {status} {detail}");
let message = match status {
401 => "A Spotify bejelentkezés lejárt".into(),
403 => "A Spotify ezt nem engedi".to_string(),
404 => "Nem található".into(),
429 => "A Spotify túl sok kérést kapott, próbáld újra kicsit később".into(),
s => format!("A Spotify hibát jelzett ({s})"),
};
return Err(ApiError { status, message }.into());
}
if cache && method == "GET" {
let mut c = self.cache.lock().unwrap();
if c.len() > 300 {
c.retain(|_, (at, _)| at.elapsed() < CACHE_FOR);
}
c.insert(url.clone(), (Instant::now(), text.clone()));
}
return Ok(text);
}
}
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let text = self.call("GET", path, true)?;
let text = if text.trim().is_empty() { "null" } else { text.as_str() };
serde_json::from_str(text).with_context(|| format!("GET {path}: unexpected answer"))
}
fn send(&self, method: &str, path: &str) -> Result<()> {
self.call(method, path, false).map(|_| ())
}
/// A page of saved things ({ items: [{ track | album | show | item }] }).
fn saved<T: DeserializeOwned + Clone>(&self, path: &str) -> Result<Paging<T>> {
let p: Paging<Saved<T>> = self.get(path)?;
Ok(Paging { items: p.items.into_iter().map(|s| s.and_then(Saved::into_inner)).collect(), next: p.next, total: p.total, offset: p.offset })
}
// ---- account ----
pub fn me(&self) -> Result<User> {
self.get("/me")
}
// ---- home ----
pub fn recently_played(&self) -> Result<Vec<Played>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
items: Vec<Played>,
}
Ok(self.get::<R>("/me/player/recently-played?limit=50")?.items)
}
pub fn top_artists(&self) -> Result<Vec<Artist>> {
Ok(self.get::<Paging<Artist>>("/me/top/artists?limit=20&time_range=short_term")?.list())
}
pub fn top_tracks(&self) -> Result<Vec<Track>> {
Ok(self.get::<Paging<Track>>("/me/top/tracks?limit=20&time_range=short_term")?.list())
}
pub fn new_releases(&self) -> Result<Vec<Album>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
albums: Paging<Album>,
}
Ok(self.get::<R>("/browse/new-releases?limit=20")?.albums.list())
}
// ---- library ----
pub fn my_playlists(&self, offset: u32) -> Result<Paging<Playlist>> {
self.get(&format!("/me/playlists?limit=50&offset={offset}"))
}
pub fn liked(&self, offset: u32) -> Result<Paging<Track>> {
self.saved(&format!("/me/tracks?limit=50&offset={offset}"))
}
pub fn saved_albums(&self, offset: u32) -> Result<Paging<Album>> {
self.saved(&format!("/me/albums?limit=50&offset={offset}"))
}
pub fn saved_shows(&self, offset: u32) -> Result<Paging<Show>> {
self.saved(&format!("/me/shows?limit=50&offset={offset}"))
}
/// Followed artists (cursor paging: `after` is the last artist's id).
pub fn followed_artists(&self, after: &str) -> Result<(Vec<Artist>, Option<String>)> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct Cursors {
after: Option<String>,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct P {
items: Vec<Artist>,
cursors: Cursors,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
artists: P,
}
let q = if after.is_empty() { String::new() } else { format!("&after={}", enc(after)) };
let r: R = self.get(&format!("/me/following?type=artist&limit=50{q}"))?;
Ok((r.artists.items, r.artists.cursors.after))
}
pub fn liked_contains(&self, ids: &[String]) -> Result<Vec<bool>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let mut out = Vec::new();
for chunk in ids.chunks(50) {
let v: Vec<bool> = self.get(&format!("/me/tracks/contains?ids={}", chunk.join(",")))?;
out.extend(v);
}
Ok(out)
}
pub fn set_liked(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/tracks");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/tracks?ids={id}"))
}
pub fn album_saved(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/albums/contains?ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_album_saved(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/albums");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/albums?ids={id}"))
}
pub fn show_saved(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/shows/contains?ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_show_saved(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/shows");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/shows?ids={id}"))
}
pub fn following_artist(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/following/contains?type=artist&ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_following_artist(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/following");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/following?type=artist&ids={id}"))
}
pub fn following_playlist(&self, id: &str, user: &str) -> Result<bool> {
let r = self.get::<Vec<bool>>(&format!("/playlists/{id}/followers/contains?ids={}", enc(user)));
Ok(r?.first().copied().unwrap_or(false))
}
pub fn set_following_playlist(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/playlists");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/playlists/{id}/followers"))
}
// ---- pages ----
pub fn playlist(&self, id: &str) -> Result<Playlist> {
self.get(&format!("/playlists/{id}?fields=id,name,uri,images,description,owner(id,display_name),followers(total),tracks(total)"))
}
pub fn playlist_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
let path = format!("/playlists/{id}/tracks?limit=100&offset={offset}&additional_types=track,episode");
match self.saved(&path) {
// Newer API versions moved the list to /items.
Err(e) if matches!(status_of(&e), Some(403 | 404 | 410)) => self.saved(&format!("/playlists/{id}/items?limit=100&offset={offset}&additional_types=track,episode")),
r => r,
}
}
pub fn album(&self, id: &str) -> Result<Album> {
self.get(&format!("/albums/{id}"))
}
pub fn album_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
self.get(&format!("/albums/{id}/tracks?limit=50&offset={offset}"))
}
pub fn artist(&self, id: &str) -> Result<Artist> {
self.get(&format!("/artists/{id}"))
}
pub fn artist_top(&self, id: &str, market: &str) -> Result<Vec<Track>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
tracks: Vec<Track>,
}
let m = if market.is_empty() { "from_token".to_string() } else { market.to_string() };
Ok(self.get::<R>(&format!("/artists/{id}/top-tracks?market={m}"))?.tracks)
}
/// `groups`: "album" | "single" | "appears_on" | "compilation", comma separated.
pub fn artist_albums(&self, id: &str, groups: &str) -> Result<Vec<Album>> {
Ok(self.get::<Paging<Album>>(&format!("/artists/{id}/albums?include_groups={groups}&limit=30"))?.list())
}
pub fn show(&self, id: &str) -> Result<Show> {
self.get(&format!("/shows/{id}"))
}
pub fn show_episodes(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
self.get(&format!("/shows/{id}/episodes?limit=50&offset={offset}"))
}
// ---- search ----
pub fn search(&self, q: &str) -> Result<SearchResult> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
tracks: Paging<Track>,
artists: Paging<Artist>,
albums: Paging<Album>,
playlists: Paging<Playlist>,
shows: Paging<Show>,
}
let r: R = self.get(&format!("/search?q={}&type=track,artist,album,playlist,show&limit=10", enc(q)))?;
Ok(SearchResult { tracks: r.tracks.list(), artists: r.artists.list(), albums: r.albums.list(), playlists: r.playlists.list(), shows: r.shows.list() })
}
// ---- player ----
/// What comes next on the active device.
pub fn queue(&self) -> Result<Vec<Track>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
queue: Vec<Track>,
}
let text = self.call("GET", "/me/player/queue", false)?;
Ok(serde_json::from_str::<R>(&text).unwrap_or_default().queue)
}
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
self.send("POST", &format!("/me/player/queue?uri={}", enc(uri)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn picks_the_right_picture() {
let imgs = vec![
Image { url: "640".into(), width: Some(640) },
Image { url: "300".into(), width: Some(300) },
Image { url: "64".into(), width: Some(64) },
];
assert_eq!(pick(&imgs, 250), "300");
assert_eq!(pick(&imgs, 400), "640");
assert_eq!(pick(&imgs, 1000), "640");
assert_eq!(pick(&imgs, 10), "64");
assert_eq!(pick(&[], 10), "");
}
#[test]
fn parses_saved_and_null_items() {
let p: Paging<Saved<Track>> = serde_json::from_str(r#"{"items":[{"track":{"id":"a","name":"A","uri":"spotify:track:a","type":"track"}},null,{"item":{"id":"b","type":"episode"}}],"total":3,"next":null}"#).unwrap();
let list: Vec<Track> = p.items.into_iter().flatten().filter_map(Saved::into_inner).collect();
assert_eq!(list.len(), 2);
assert_eq!(list[1].kind, "episode");
let s: Paging<Playlist> = serde_json::from_str(r#"{"items":[null,{"id":"p","name":"P","images":null,"owner":{"id":"u"}}]}"#).unwrap();
assert_eq!(s.list().len(), 1);
assert_eq!(s.list()[0].owner_name(), "u");
}
#[test]
fn encodes_queries() {
assert_eq!(enc("Dűne ä&b"), "D%C5%B1ne%20%C3%A4%26b");
}
}

1052
src/app.rs Normal file

File diff suppressed because it is too large Load Diff

123
src/config.rs Normal file
View File

@@ -0,0 +1,123 @@
//! What this TV remembers: its Connect identity and the playback settings.
//! `$HOME/.config/spotify-tv/config.toml` (on the TV, $HOME is the app's own
//! data folder inside the sandbox). The Spotify credentials live apart, in
//! `$HOME/.cache/spotify-tv/credentials.json` (librespot's cache).
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
pub const DEFAULT_NAME: &str = "Fennec TV";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// Spotify Connect device id (stays the same, so phones remember the TV).
#[serde(default)]
pub device_id: String,
/// The name phones show.
#[serde(default = "default_name")]
pub device_name: String,
/// 96 | 160 | 320 kbit/s.
#[serde(default = "default_bitrate")]
pub bitrate: u32,
/// Same loudness for every track.
#[serde(default = "yes")]
pub normalise: bool,
/// Similar tracks after the end of an album or playlist.
#[serde(default = "yes")]
pub autoplay: bool,
/// "auto" | "full" | "light" | "off" (Material)
#[serde(default = "auto")]
pub glass: String,
}
fn default_name() -> String {
DEFAULT_NAME.into()
}
fn default_bitrate() -> u32 {
320
}
fn yes() -> bool {
true
}
fn auto() -> String {
"auto".into()
}
impl Default for Config {
fn default() -> Self {
Config { device_id: String::new(), device_name: default_name(), bitrate: default_bitrate(), normalise: true, autoplay: true, glass: auto() }
}
}
pub fn home() -> PathBuf {
std::env::var_os("HOME").or_else(|| std::env::var_os("APPDATA")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
}
fn path() -> PathBuf {
home().join(".config").join("spotify-tv").join("config.toml")
}
/// 40 hex digits, random enough for a device id.
fn new_device_id() -> String {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
while out.len() < 40 {
let mut h = RandomState::new().build_hasher();
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
h.write_u32(std::process::id());
out.push_str(&format!("{:016x}", h.finish()));
}
out.truncate(40);
out
}
impl Config {
pub fn load() -> Config {
let mut c: Config = std::fs::read_to_string(path()).ok().and_then(|t| toml::from_str(&t).ok()).unwrap_or_default();
if c.device_id.len() != 40 || !c.device_id.chars().all(|ch| ch.is_ascii_hexdigit()) {
c.device_id = new_device_id();
c.save();
}
if c.device_name.trim().is_empty() {
c.device_name = default_name();
}
c
}
pub fn save(&self) {
let p = path();
let result = (|| -> anyhow::Result<()> {
std::fs::create_dir_all(p.parent().unwrap())?;
let tmp = p.with_extension("tmp");
std::fs::write(&tmp, toml::to_string(self)?)?;
std::fs::rename(&tmp, &p)?;
Ok(())
})();
if let Err(e) = result {
log::warn!("saving {}: {e:#}", p.display());
}
}
}
/// Applies the glass look. "auto": sf-ui measures the GPU and picks full,
/// light or the matte Material style; "off" (shown as "Matt") is Material.
pub fn apply_look(glass: &sf_ui::Glass, look: &str) {
match look {
"full" => glass.set_quality(sf_ui::Quality::Full),
"light" => glass.set_quality(sf_ui::Quality::Light),
"off" => glass.set_quality(sf_ui::Quality::Material),
_ => glass.set_auto_quality(),
}
}
#[cfg(test)]
mod tests {
#[test]
fn device_ids_are_hex() {
let id = super::new_device_id();
assert_eq!(id.len(), 40);
assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
}
}

104
src/format.rs Normal file
View File

@@ -0,0 +1,104 @@
//! Hungarian texts: times, counts, dates.
/// 214000 -> "3:34", 3725000 -> "1:02:05".
pub fn clock(ms: u32) -> String {
let s = ms / 1000;
let (h, m, s) = (s / 3600, (s / 60) % 60, s % 60);
if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
}
/// A list's length: "1 óra 12 perc", "48 perc".
pub fn total(ms: u64) -> String {
let min = (ms / 60_000) as u32;
match (min / 60, min % 60) {
(0, m) => format!("{m} perc"),
(h, 0) => format!("{h} óra"),
(h, m) => format!("{h} óra {m} perc"),
}
}
/// 1234567 -> "1 234 567".
pub fn thousands(n: u32) -> String {
let s = n.to_string();
let mut out = String::new();
for (i, ch) in s.chars().enumerate() {
if i > 0 && (s.len() - i) % 3 == 0 {
out.push('\u{a0}');
}
out.push(ch);
}
out
}
/// Followers: "12 345 követő", "1,2 millió követő".
pub fn followers(n: u32) -> String {
if n >= 1_000_000 {
let m = n as f64 / 1_000_000.0;
let t = if m >= 100.0 { format!("{m:.0}") } else { format!("{m:.1}").replace('.', ",") };
format!("{} millió követő", t.trim_end_matches(",0"))
} else {
format!("{} követő", thousands(n))
}
}
/// "2023-05-12" -> "2023".
pub fn year(date: &str) -> String {
date.split('-').next().unwrap_or("").to_string()
}
/// "2023-05-12" -> "2023. máj. 12."
pub fn date(d: &str) -> String {
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."];
let p: Vec<&str> = d.split('-').collect();
match p.as_slice() {
[y, m, day] => match m.parse::<usize>().ok().and_then(|m| MONTHS.get(m.wrapping_sub(1))) {
Some(mn) => format!("{y}. {mn} {}.", day.trim_start_matches('0')),
None => d.to_string(),
},
[y, ..] => y.to_string(),
_ => d.to_string(),
}
}
/// Album types as Spotify's Hungarian UI calls them.
pub fn album_type(t: &str) -> &'static str {
match t {
"single" => "Kislemez",
"compilation" => "Válogatás",
"ep" => "EP",
_ => "Album",
}
}
/// Strips the HTML Spotify puts into playlist descriptions.
pub fn plain(html: &str) -> String {
let mut out = String::new();
let mut tag = false;
for ch in html.chars() {
match ch {
'<' => tag = true,
'>' => tag = false,
c if !tag => out.push(c),
_ => {}
}
}
out.replace("&amp;", "&").replace("&#x27;", "'").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats() {
assert_eq!(clock(214_000), "3:34");
assert_eq!(clock(3_725_000), "1:02:05");
assert_eq!(total(4_320_000), "1 óra 12 perc");
assert_eq!(total(2_880_000), "48 perc");
assert_eq!(thousands(1234567), "1\u{a0}234\u{a0}567");
assert_eq!(followers(1_200_000), "1,2 millió követő");
assert_eq!(followers(2_000_000), "2 millió követő");
assert_eq!(date("2023-05-02"), "2023. máj. 2.");
assert_eq!(plain("Hits <a href=\"x\">here</a> &amp; more"), "Hits here & more");
}
}

58
src/main.rs Normal file
View File

@@ -0,0 +1,58 @@
//! Spotify for Fennec OS: a native TV client.
//!
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine
//! and controller come from Netflex TV.
//! - Spotify: librespot (src/spotify.rs) for the session, Spotify Connect,
//! the zeroconf sign-in and playback; the Web API (src/api.rs) for
//! browsing.
mod api;
mod app;
mod config;
mod format;
mod nowplaying;
mod page;
mod screens;
mod spotify;
mod task;
use slint::{ComponentHandle, Model};
slint::include_modules!();
sf_ui::glue!(App);
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info,librespot=info,libmdns=warn")).init();
sf_ui::init()?;
let ui = App::new()?;
ui.sf_ui_setup();
if std::env::var_os("SF_UI_SIZE").is_none() && std::env::var_os("SPOTIFY_WINDOWED").is_none() {
ui.window().set_fullscreen(true);
}
// Development: where the window opens ("x,y", physical px), e.g. on a
// second monitor.
if let Some((x, y)) = std::env::var("SPOTIFY_WINDOW_POS").ok().and_then(|v| v.split_once(',').and_then(|(x, y)| Some((x.trim().parse().ok()?, y.trim().parse().ok()?)))) {
ui.window().set_position(slint::PhysicalPosition::new(x, y));
}
let glass = sf_ui::Glass::install(&ui, |ui, p| {
p.extend(ui.get_glass_signin().iter());
p.extend(ui.get_glass_page().iter());
p.extend(ui.get_glass_page_keyboard().iter());
p.extend(ui.get_glass_np().iter());
p.extend(ui.get_glass_input().iter());
p.extend(ui.get_glass_input_keyboard().iter());
p.extend(ui.get_glass_select().iter());
p.extend(ui.get_glass_toast().iter());
})?;
glass.set_palette(sf_ui::Palette::from_hex(app::PALETTE));
let images = sf_ui::images::Images::new(256 << 20);
let app = app::Controller::new(&ui, glass, images);
ui.run()?;
app.shutdown();
// Background threads (image loader, audio, network) need no goodbye.
std::process::exit(0)
}

524
src/nowplaying.rs Normal file
View File

@@ -0,0 +1,524 @@
//! Most szól: the big cover, the title, the progress, the controls (shuffle,
//! previous, play/pause, next, repeat, like, lyrics, queue), synced lyrics
//! and the queue. Also keeps the playback state that the engine reports
//! (pages show it in the "now playing" capsule of the nav).
//!
//! Keys: left/right between the buttons, OK presses one, up goes to the
//! progress bar (left/right seek there), Back returns to the pages. Space
//! (play/pause on a keyboard) works everywhere.
use std::rc::Rc;
use std::time::{Duration, Instant};
use slint::{Model, ModelRc, VecModel};
use crate::api;
use crate::app::{Action, Controller, Look};
use crate::spotify::{Cmd, Event, Track};
use crate::{QueueItem, format, task};
/// The buttons, left to right.
const BUTTONS: [&str; 8] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics", "queue"];
const PLAY: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Panel {
#[default]
None,
Lyrics,
Queue,
}
#[derive(Default)]
pub struct NowPlaying {
pub track: Option<Track>,
pub playing: bool,
pub loading: bool,
pos_ms: u32,
since: Option<Instant>,
pub shuffle: bool,
pub repeat: (bool, bool),
liked: Option<bool>,
/// (track id, lines, synced); empty lines = none.
lyrics: Option<(String, Vec<(u32, String)>, bool)>,
lyrics_loading: bool,
queue: Vec<api::Track>,
panel: Panel,
focus: usize,
/// 0: the buttons, 1: the progress bar.
area: u8,
/// Another device that plays now (its name).
elsewhere: String,
}
impl NowPlaying {
pub fn position(&self) -> u32 {
let p = match (self.playing, self.since) {
(true, Some(at)) => self.pos_ms + at.elapsed().as_millis() as u32,
_ => self.pos_ms,
};
match &self.track {
Some(t) if t.duration_ms > 0 => p.min(t.duration_ms),
_ => p,
}
}
fn set_pos(&mut self, ms: u32) {
self.pos_ms = ms;
self.since = Some(Instant::now());
}
}
pub fn on_event(c: &Controller, ev: Event) {
let mut new_track = false;
{
let mut st = c.state.borrow_mut();
let np = &mut st.np;
match ev {
Event::Track(t) => {
new_track = np.track.as_ref().map(|o| &o.uri) != Some(&t.uri);
if new_track {
np.liked = None;
np.set_pos(0);
}
np.track = Some(t);
np.elsewhere.clear();
}
Event::Loading => np.loading = true,
Event::Playing(p) => {
np.playing = true;
np.loading = false;
np.elsewhere.clear();
np.set_pos(p);
}
Event::Paused(p) => {
np.playing = false;
np.loading = false;
np.set_pos(p);
}
Event::Seeked(p) => np.set_pos(p),
Event::Stopped => {
let p = np.position();
np.playing = false;
np.loading = false;
np.set_pos(p);
}
Event::Unavailable => {
drop(st);
c.toast("Ez a szám most nem játszható le.", true);
return;
}
Event::Shuffle(on) => np.shuffle = on,
Event::Repeat(ctx, track) => np.repeat = (ctx, track),
Event::Active(true) => {
let open = st.screen == "page" && st.np.track.is_some();
drop(st);
if open {
self::open(c);
}
return;
}
Event::Active(false) => {
let p = np.position();
np.playing = false;
np.set_pos(p);
}
Event::Client(name) => {
if !name.is_empty() {
np.elsewhere = name;
}
}
Event::Status(_) | Event::Pair(_) => {}
}
}
if new_track {
track_changed(c);
}
sync(c);
c.track_changed();
}
/// A new track: its cover behind the screen, its like state, lyrics, queue.
fn track_changed(c: &Controller) {
let (track, panel) = {
let st = c.state.borrow();
(st.np.track.clone(), st.np.panel)
};
let Some(t) = track else { return };
if c.state.borrow().screen == "nowplaying" {
c.backdrop(&t.cover, Look::Soft, &format!("np:{}", t.uri));
}
load_cover(c, &t);
if !t.episode && !t.id.is_empty() {
let api = c.api();
let c2 = c.clone();
let id = t.id.clone();
task::spawn(
move || api.liked_contains(std::slice::from_ref(&id)).map(|v| v.first().copied().unwrap_or(false)),
move |r| {
if let Ok(liked) = r {
let mut st = c2.state.borrow_mut();
if st.np.track.as_ref().is_some_and(|x| x.id == t.id) {
st.np.liked = Some(liked);
}
drop(st);
sync(&c2);
}
},
);
}
match panel {
Panel::Lyrics => load_lyrics(c),
Panel::Queue => load_queue(c),
Panel::None => {}
}
}
fn load_cover(c: &Controller, t: &Track) {
let Some(ui) = c.ui() else { return };
ui.set_np_cover(Default::default());
if t.cover.is_empty() {
return;
}
let px = c.px();
let w = c.ui.clone();
let uri = t.uri.clone();
let c2 = c.clone();
c.images.load(&t.cover, ((600.0 * px) as u32, (600.0 * px) as u32), move |img| {
if c2.state.borrow().np.track.as_ref().is_some_and(|x| x.uri == uri) {
if let Some(ui) = w.upgrade() {
ui.set_np_cover(img);
}
}
});
}
fn load_lyrics(c: &Controller) {
let id = {
let mut st = c.state.borrow_mut();
let Some(t) = st.np.track.clone() else { return };
if t.episode || st.np.lyrics.as_ref().is_some_and(|l| l.0 == t.id) || st.np.lyrics_loading {
return;
}
st.np.lyrics_loading = true;
t.id
};
sync(c);
let engine = c.engine.clone();
let c2 = c.clone();
let id2 = id.clone();
task::spawn(
move || engine.lyrics(&id2),
move |r| {
{
let mut st = c2.state.borrow_mut();
st.np.lyrics_loading = false;
let (lines, synced) = r.unwrap_or_else(|e| {
log::info!("lyrics: {e:#}");
(Vec::new(), false)
});
st.np.lyrics = Some((id, lines, synced));
}
// The track may have changed meanwhile.
let again = {
let st = c2.state.borrow();
st.np.panel == Panel::Lyrics && st.np.track.as_ref().is_some_and(|t| st.np.lyrics.as_ref().is_none_or(|l| l.0 != t.id))
};
if again {
load_lyrics(&c2);
}
sync(&c2);
},
);
}
fn load_queue(c: &Controller) {
let api = c.api();
let c2 = c.clone();
task::spawn(
move || api.queue(),
move |r| {
match r {
Ok(q) => c2.state.borrow_mut().np.queue = q,
Err(e) => log::info!("queue: {e:#}"),
}
sync_queue(&c2);
},
);
}
fn sync_queue(c: &Controller) {
let Some(ui) = c.ui() else { return };
let queue = c.state.borrow().np.queue.clone();
let model = Rc::new(VecModel::from(
queue
.iter()
.take(30)
.map(|t| QueueItem { title: t.name.clone().into(), artist: t.artist_names().into(), image: Default::default() })
.collect::<Vec<_>>(),
));
ui.set_np_queue(ModelRc::from(model.clone()));
let px = c.px();
for (i, t) in queue.iter().take(12).enumerate() {
let url = t.image(64);
if url.is_empty() {
continue;
}
let m = model.clone();
c.images.load(&url, ((64.0 * px) as u32, (64.0 * px) as u32), move |img| {
if let Some(mut row) = m.row_data(i) {
row.image = img;
m.set_row_data(i, row);
}
});
}
}
/// Shows the screen.
pub fn open(c: &Controller) {
{
let mut st = c.state.borrow_mut();
if st.screen == "nowplaying" {
return;
}
st.np.area = 0;
st.np.focus = PLAY;
}
let track = c.state.borrow().np.track.clone();
match &track {
Some(t) => c.backdrop(&t.cover, Look::Soft, &format!("np:{}", t.uri)),
None => c.clear_backdrop(),
}
c.show("nowplaying");
sync(c);
let panel = c.state.borrow().np.panel;
match panel {
Panel::Lyrics => load_lyrics(c),
Panel::Queue => load_queue(c),
Panel::None => {}
}
let k = c.clone();
c.np_timer.start(slint::TimerMode::Repeated, Duration::from_millis(250), move || {
if k.state.borrow().screen == "nowplaying" {
sync_time(&k);
} else {
k.np_timer.stop();
}
});
}
fn close(c: &Controller) {
c.np_timer.stop();
c.back_to_pages();
}
pub fn key(c: &Controller, a: Action, repeat: bool) {
enum Then {
Sync,
Press(usize),
Seek(i64),
Close,
Toggle,
Nothing,
}
let then = {
let mut st = c.state.borrow_mut();
let np = &mut st.np;
match (np.area, a) {
(_, Action::PlayPause) => Then::Toggle,
(_, Action::Back) if np.area == 1 => {
np.area = 0;
Then::Sync
}
(_, Action::Back) => Then::Close,
(0, Action::Left) => {
np.focus = np.focus.saturating_sub(1);
Then::Sync
}
(0, Action::Right) => {
np.focus = (np.focus + 1).min(BUTTONS.len() - 1);
Then::Sync
}
(0, Action::Up) if np.track.as_ref().is_some_and(|t| t.duration_ms > 0) => {
np.area = 1;
Then::Sync
}
(0, Action::Ok) => Then::Press(np.focus),
(1, Action::Left) => Then::Seek(if repeat { -30_000 } else { -10_000 }),
(1, Action::Right) => Then::Seek(if repeat { 30_000 } else { 10_000 }),
(1, Action::Down) | (1, Action::Ok) => {
np.area = 0;
Then::Sync
}
_ => Then::Nothing,
}
};
match then {
Then::Nothing => {}
Then::Sync => sync(c),
Then::Close => close(c),
Then::Toggle => c.engine.send(Cmd::PlayPause),
Then::Seek(d) => {
let target = {
let mut st = c.state.borrow_mut();
let dur = st.np.track.as_ref().map(|t| t.duration_ms).unwrap_or(0);
let t = (st.np.position() as i64 + d).clamp(0, dur.saturating_sub(1000) as i64) as u32;
st.np.set_pos(t);
t
};
c.engine.send(Cmd::Seek(target));
sync_time(c);
}
Then::Press(i) => press(c, BUTTONS[i]),
}
}
fn press(c: &Controller, button: &str) {
let (shuffle, repeat, liked, track, panel) = {
let st = c.state.borrow();
(st.np.shuffle, st.np.repeat, st.np.liked, st.np.track.clone(), st.np.panel)
};
match button {
"play" => c.engine.send(if c.state.borrow().np.playing { Cmd::Pause } else { Cmd::Play }),
"prev" => c.engine.send(Cmd::Prev),
"next" => c.engine.send(Cmd::Next),
"shuffle" => {
c.state.borrow_mut().np.shuffle = !shuffle;
c.engine.send(Cmd::Shuffle(!shuffle));
c.toast(if shuffle { "Keverés kikapcsolva" } else { "Keverés bekapcsolva" }, false);
}
"repeat" => {
// off -> the list -> this track -> off
let next = match repeat {
(false, false) => (true, false),
(true, false) => (true, true),
_ => (false, false),
};
c.state.borrow_mut().np.repeat = next;
c.engine.send(Cmd::Repeat(next.0, next.1));
c.toast(
match next {
(true, false) => "Ismétlés: a lista",
(true, true) => "Ismétlés: ez a szám",
_ => "Ismétlés kikapcsolva",
},
false,
);
}
"like" => {
let Some(t) = track.filter(|t| !t.episode && !t.id.is_empty()) else { return };
let on = !liked.unwrap_or(false);
let api = c.api();
let c2 = c.clone();
let id = t.id.clone();
task::spawn(
move || api.set_liked(&id, on),
move |r| match r {
Ok(()) => {
c2.state.borrow_mut().np.liked = Some(on);
c2.toast(if on { "Hozzáadva a Kedvelt dalokhoz" } else { "Eltávolítva a Kedvelt dalok közül" }, false);
sync(&c2);
}
Err(e) => c2.toast(&api::describe(&e), true),
},
);
}
"lyrics" => {
let next = if panel == Panel::Lyrics { Panel::None } else { Panel::Lyrics };
c.state.borrow_mut().np.panel = next;
if next == Panel::Lyrics {
load_lyrics(c);
}
}
"queue" => {
let next = if panel == Panel::Queue { Panel::None } else { Panel::Queue };
c.state.borrow_mut().np.panel = next;
if next == Panel::Queue {
load_queue(c);
}
}
_ => {}
}
sync(c);
}
/// Everything but the time to Slint.
pub fn sync(c: &Controller) {
let Some(ui) = c.ui() else { return };
{
let st = c.state.borrow();
let np = &st.np;
match &np.track {
Some(t) => {
ui.set_np_title(t.name.clone().into());
ui.set_np_artist(t.artist_names().into());
ui.set_np_album(if t.episode { "Podcast".into() } else { t.album.clone().into() });
ui.set_np_explicit(t.explicit);
ui.set_np_episode(t.episode);
}
None => {
ui.set_np_title("Most nem szól semmi".into());
ui.set_np_artist("Indíts el egy számot, vagy válaszd ki ezt a TV-t a telefonod Spotify appjában.".into());
ui.set_np_album("".into());
}
}
ui.set_np_playing(np.playing);
ui.set_np_loading(np.loading);
ui.set_np_shuffle(np.shuffle);
ui.set_np_repeat(match np.repeat {
(_, true) => 2,
(true, false) => 1,
_ => 0,
});
ui.set_np_liked(match np.liked {
Some(true) => 1,
Some(false) => 0,
None => -1,
});
ui.set_np_focus(np.focus as i32);
ui.set_np_area(np.area as i32);
ui.set_np_panel(match np.panel {
Panel::None => 0,
Panel::Lyrics => 1,
Panel::Queue => 2,
});
let device = if !np.elsewhere.is_empty() && !np.playing { format!("Irányítja: {}", np.elsewhere) } else { format!("Lejátszás itt: {}", st.cfg.device_name) };
ui.set_np_device(device.into());
// Lyrics.
let (lines, note) = match (&np.lyrics, &np.track) {
(_, Some(t)) if t.episode => (Vec::new(), "Podcastokhoz nincs dalszöveg."),
(Some((id, lines, _)), Some(t)) if *id == t.id && !lines.is_empty() => (lines.iter().map(|l| l.1.clone().into()).collect(), ""),
(Some((id, _, _)), Some(t)) if *id == t.id => (Vec::new(), "Ehhez a számhoz nincs dalszöveg."),
_ if np.lyrics_loading => (Vec::new(), "Dalszöveg betöltése…"),
_ => (Vec::new(), ""),
};
let n = lines.len();
if ui.get_np_lyrics().row_count() != n || n == 0 {
ui.set_np_lyrics(ModelRc::new(VecModel::from(lines)));
}
ui.set_np_lyrics_note(note.into());
if np.panel == Panel::Queue && np.queue.is_empty() {
ui.set_np_queue_note("A lejátszási sor üres.".into());
} else {
ui.set_np_queue_note("".into());
}
}
sync_time(c);
}
/// The progress and the current lyrics line.
fn sync_time(c: &Controller) {
let Some(ui) = c.ui() else { return };
let st = c.state.borrow();
let np = &st.np;
let pos = np.position();
let dur = np.track.as_ref().map(|t| t.duration_ms).unwrap_or(0);
ui.set_np_progress(if dur > 0 { pos as f32 / dur as f32 } else { 0.0 });
ui.set_np_time(format::clock(pos).into());
ui.set_np_duration(if dur > 0 { format::clock(dur).into() } else { "".into() });
let line = match (&np.lyrics, &np.track) {
(Some((id, lines, true)), Some(t)) if *id == t.id => lines.iter().rposition(|l| l.0 <= pos + 300).map(|i| i as i32).unwrap_or(-1),
_ => -1,
};
ui.set_np_lyric_line(line);
ui.set_np_lyrics_synced(matches!(&np.lyrics, Some((_, _, true))));
}

1020
src/page.rs Normal file

File diff suppressed because it is too large Load Diff

146
src/screens/artist.rs Normal file
View File

@@ -0,0 +1,146 @@
//! An artist: photo, followers, Lejátszás / Keverés / Követés, the popular
//! tracks, then albums, singles and appearances.
use std::any::Any;
use crate::api::{self, Album, Artist, Track};
use crate::app::{Cx, Look, Screen};
use crate::format;
use crate::page::{Ch, Frame, Kind, L, Spec};
use crate::screens::{self, Load, album_card, row_index, track_line};
use crate::spotify::Cmd;
#[derive(Default)]
struct Data {
artist: Artist,
top: Vec<Track>,
albums: Vec<Album>,
singles: Vec<Album>,
appears: Vec<Album>,
}
pub struct ArtistPage {
id: String,
data: Load<Data>,
following: Option<bool>,
started: bool,
}
impl ArtistPage {
pub fn new(id: &str) -> ArtistPage {
ArtistPage { id: id.into(), data: Load::Loading, following: None, started: false }
}
fn load(&mut self, cx: &Cx) {
let api = cx.api();
let id = self.id.clone();
let market = cx.user().country;
cx.spawn::<ArtistPage, _>(
move || -> anyhow::Result<(Data, Option<bool>)> {
let artist = api.artist(&id)?;
let (top, albums, singles, appears, following) = std::thread::scope(|s| {
let top = s.spawn(|| api.artist_top(&id, &market).unwrap_or_default());
let albums = s.spawn(|| api.artist_albums(&id, "album").unwrap_or_default());
let singles = s.spawn(|| api.artist_albums(&id, "single").unwrap_or_default());
let appears = s.spawn(|| api.artist_albums(&id, "appears_on,compilation").unwrap_or_default());
let following = s.spawn(|| api.following_artist(&id).ok());
(top.join().unwrap_or_default(), albums.join().unwrap_or_default(), singles.join().unwrap_or_default(), appears.join().unwrap_or_default(), following.join().ok().flatten())
});
Ok((Data { artist, top, albums, singles, appears }, following))
},
|s, cx, r| match r {
Ok((d, following)) => {
s.following = following;
let img = api::pick(&d.artist.images, 960);
cx.backdrop(&img, Look::Sharp, &format!("ar:{}", s.id));
s.data = Load::Ready(d);
}
Err(e) => s.data = Load::Failed(api::describe(&e)),
},
);
}
}
impl Screen for ArtistPage {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame::default();
let Some(d) = self.data.ready() else {
return Spec { lines: vec![self.data.status("status").unwrap()], frame };
};
let a = &d.artist;
let mut hero = L::new("hero", Kind::Hero).cover(api::pick(&a.images, 400), true);
hero.style = "ELŐADÓ".into();
hero.title = a.name.clone();
hero.subtitle = a.followers.as_ref().map(|f| format::followers(f.total)).unwrap_or_default();
hero.meta = a.genres.iter().take(4).cloned().collect::<Vec<_>>().join(" · ");
let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverés").icon("shuffle")];
if let Some(f) = self.following {
chips.push(if f { Ch::new("follow", "Követed").icon("check").active(true) } else { Ch::new("follow", "Követés").icon("plus") });
}
hero.chips = chips;
let mut lines = vec![hero];
let playing = cx.playing_uri();
if !d.top.is_empty() {
lines.push(L::heading("top-h", "Népszerű"));
for (i, t) in d.top.iter().take(10).enumerate() {
lines.push(track_line(format!("trk#{i}"), t, None, true, &playing));
}
}
for (id, title, list) in [("albums", "Albumok", &d.albums), ("singles", "Kislemezek és EP-k", &d.singles), ("appears", "Közreműködések", &d.appears)] {
if !list.is_empty() {
lines.push(L::cards(id, title, "square", list.iter().map(album_card).collect()).captions());
}
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
let Some(d) = self.data.ready() else { return };
let uri = d.artist.uri.clone();
if line == "hero" {
match item {
"play" | "shuffle" => cx.play(Cmd::Context { uri, start: None, shuffle: item == "shuffle" }),
"follow" => {
let Some(on) = self.following.map(|f| !f) else { return };
let api = cx.api();
let id = self.id.clone();
cx.call::<ArtistPage>("follow", move || api.set_following_artist(&id, on), move |s, cx, ok| {
if ok {
s.following = Some(on);
cx.toast(if on { "Követed" } else { "Már nem követed" });
}
});
}
_ => {}
}
return;
}
if line.starts_with("trk#") {
let Some(i) = row_index(line) else { return };
let top: Vec<Track> = d.top.iter().take(10).cloned().collect();
if item == "more" {
if let Some(t) = top.get(i) {
screens::track_menu(cx, t);
}
} else {
screens::play_from(cx, &uri, &top, i);
}
return;
}
screens::open_card(cx, item);
}
fn shown(&mut self, cx: &Cx) {
if let Some(d) = self.data.ready() {
cx.backdrop(&api::pick(&d.artist.images, 960), Look::Sharp, &format!("ar:{}", self.id));
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

343
src/screens/collection.rs Normal file
View File

@@ -0,0 +1,343 @@
//! A list of tracks with a header: a playlist, an album, the liked songs or a
//! podcast's episodes. Lejátszás / Keverés / Mentés, then the rows; long
//! lists load page by page while the focus moves down.
use std::any::Any;
use crate::api::{self, Api, Paging, Track};
use crate::app::{Cx, Look, Screen};
use crate::format;
use crate::page::{Ch, Frame, Kind, L, Spec};
use crate::screens::{self, Load, row_index, track_line};
use crate::spotify::Cmd;
#[derive(Debug, Clone, PartialEq, Eq)]
enum What {
Playlist(String),
Album(String),
Liked,
Show(String),
}
#[derive(Debug, Clone, Default)]
struct Head {
label: String,
title: String,
subtitle: String,
meta: String,
text: String,
cover: String,
uri: String,
/// Your own playlist (no follow button).
own: bool,
}
pub struct Collection {
what: What,
head: Load<Head>,
tracks: Vec<Track>,
next: Option<u32>,
loading_more: bool,
/// Saved / followed (None: unknown or not applicable).
saved: Option<bool>,
started: bool,
}
impl Collection {
fn new(what: What) -> Collection {
Collection { what, head: Load::Loading, tracks: Vec::new(), next: Some(0), loading_more: false, saved: None, started: false }
}
pub fn playlist(id: &str) -> Collection {
Collection::new(What::Playlist(id.into()))
}
pub fn album(id: &str) -> Collection {
Collection::new(What::Album(id.into()))
}
pub fn liked() -> Collection {
Collection::new(What::Liked)
}
pub fn show(id: &str) -> Collection {
Collection::new(What::Show(id.into()))
}
/// What Spotify plays when this page plays.
fn context(&self, cx: &Cx) -> String {
match &self.what {
What::Liked => {
let user = cx.user().id;
if user.is_empty() { String::new() } else { format!("spotify:user:{user}:collection") }
}
_ => self.head.ready().map(|h| h.uri.clone()).unwrap_or_default(),
}
}
fn load(&mut self, cx: &Cx) {
let api = cx.api();
let what = self.what.clone();
let me = cx.user().id;
cx.spawn::<Collection, _>(
move || -> anyhow::Result<(Head, Paging<Track>, Option<bool>)> {
Ok(match &what {
What::Playlist(id) => {
let p = api.playlist(id)?;
let tracks = api.playlist_tracks(id, 0)?;
let own = p.owner.id == me;
let saved = if own || me.is_empty() { None } else { api.following_playlist(id, &me).ok() };
let mut meta = vec![format!("{} dal", p.count())];
if let Some(f) = p.followers.as_ref().filter(|f| f.total > 0) {
meta.push(format::followers(f.total).replace("követő", "kedvelés"));
}
let head = Head {
label: "LEJÁTSZÁSI LISTA".into(),
title: p.name.clone(),
subtitle: p.owner_name(),
meta: meta.join(" · "),
text: format::plain(&p.description),
cover: p.image(400),
uri: p.uri.clone(),
own,
};
(head, tracks, saved)
}
What::Album(id) => {
let a = api.album(id)?;
let mut tracks = a.tracks.clone().unwrap_or_default();
// Album tracks come without the album: add it (art, menus).
let bare = api::Album { tracks: None, ..a.clone() };
for t in tracks.items.iter_mut().flatten() {
t.album = Some(bare.clone());
}
let saved = api.album_saved(id).ok();
let artists = a.artists.iter().map(|x| x.name.as_str()).collect::<Vec<_>>().join(", ");
let length: u64 = tracks.items.iter().flatten().map(|t| t.duration_ms as u64).sum();
let mut meta = vec![format::year(&a.release_date), format!("{} dal", a.total_tracks)];
if !tracks.more() {
meta.push(format::total(length));
}
let head = Head {
label: format::album_type(&a.album_type).to_uppercase(),
title: a.name.clone(),
subtitle: artists,
meta: meta.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · "),
text: if a.label.is_empty() { String::new() } else { format!("Kiadó: {}", a.label) },
cover: api::pick(&a.images, 400),
uri: a.uri.clone(),
own: false,
};
(head, tracks, saved)
}
What::Liked => {
let tracks = api.liked(0)?;
let head = Head {
label: "LEJÁTSZÁSI LISTA".into(),
title: "Kedvelt dalok".into(),
subtitle: String::new(),
meta: format!("{} dal", tracks.total),
text: "A dalok, amiket a szívvel jelöltél meg.".into(),
cover: String::new(),
uri: String::new(),
own: true,
};
(head, tracks, None)
}
What::Show(id) => {
let s = api.show(id)?;
let mut tracks = api.show_episodes(id, 0)?;
let bare = api::Show { ..s.clone() };
for t in tracks.items.iter_mut().flatten() {
t.show = Some(bare.clone());
t.kind = "episode".into();
}
let saved = api.show_saved(id).ok();
let head = Head {
label: "PODCAST".into(),
title: s.name.clone(),
subtitle: s.publisher.clone(),
meta: format!("{} epizód", s.total_episodes),
text: format::plain(&s.description),
cover: api::pick(&s.images, 400),
uri: s.uri.clone(),
own: false,
};
(head, tracks, saved)
}
})
},
|s, cx, r| match r {
Ok((head, tracks, saved)) => {
s.next = tracks.more().then_some(tracks.offset + tracks.items.len() as u32);
s.tracks = tracks.list();
s.saved = saved;
let cover = head.cover.clone();
s.head = Load::Ready(head);
cx.backdrop(&cover, Look::Soft, &format!("col:{:?}", s.what));
}
Err(e) => s.head = Load::Failed(api::describe(&e)),
},
);
}
fn load_more(&mut self, cx: &Cx) {
let Some(offset) = self.next.filter(|_| !self.loading_more) else { return };
self.loading_more = true;
let api = cx.api();
let what = self.what.clone();
let album = self.tracks.first().and_then(|t| t.album.clone());
let show = self.tracks.first().and_then(|t| t.show.clone());
cx.spawn::<Collection, _>(
move || fetch_page(&api, &what, offset),
move |s, cx, r| {
s.loading_more = false;
match r {
Ok(mut p) => {
s.next = p.more().then_some(p.offset + p.items.len() as u32);
for t in p.items.iter_mut().flatten() {
if t.album.is_none() {
t.album = album.clone();
}
if what_is_show(&s.what) {
t.show = show.clone();
t.kind = "episode".into();
}
}
s.tracks.extend(p.list());
}
Err(e) => {
s.next = None;
cx.error("more", &e);
}
}
},
);
}
fn toggle_saved(&mut self, cx: &Cx) {
let Some(on) = self.saved.map(|s| !s) else { return };
let api = cx.api();
let what = self.what.clone();
cx.call::<Collection>(
"save",
move || match &what {
What::Playlist(id) => api.set_following_playlist(id, on),
What::Album(id) => api.set_album_saved(id, on),
What::Show(id) => api.set_show_saved(id, on),
What::Liked => Ok(()),
},
move |s, cx, ok| {
if ok {
s.saved = Some(on);
cx.toast(if on { "Hozzáadva a könyvtáradhoz" } else { "Eltávolítva a könyvtáradból" });
}
},
);
}
}
fn what_is_show(w: &What) -> bool {
matches!(w, What::Show(_))
}
fn fetch_page(api: &Api, what: &What, offset: u32) -> anyhow::Result<Paging<Track>> {
match what {
What::Playlist(id) => api.playlist_tracks(id, offset),
What::Album(id) => api.album_tracks(id, offset),
What::Liked => api.liked(offset),
What::Show(id) => api.show_episodes(id, offset),
}
}
impl Screen for Collection {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame::default();
let Some(h) = self.head.ready() else {
let lines = vec![self.head.status("status").unwrap()];
return Spec { lines, frame };
};
let mut hero = L::new("hero", Kind::Hero).cover(h.cover.clone(), false);
hero.style = h.label.clone();
hero.title = h.title.clone();
hero.subtitle = h.subtitle.clone();
hero.meta = h.meta.clone();
hero.text = h.text.clone();
if h.cover.is_empty() && self.what == What::Liked {
hero.icon = "liked".into();
}
let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary")];
if !matches!(self.what, What::Show(_)) {
chips.push(Ch::new("shuffle", "Keverés").icon("shuffle"));
}
if let Some(saved) = self.saved.filter(|_| !h.own) {
chips.push(if saved { Ch::new("save", "A könyvtáradban").icon("check").active(true) } else { Ch::new("save", "Mentés").icon("plus") });
}
hero.chips = chips;
let mut lines = vec![hero];
if self.tracks.is_empty() {
lines.push(L::notice("empty", "info", "Ez a lista üres", ""));
}
let playing = cx.playing_uri();
let numbered = matches!(self.what, What::Album(_));
let with_album = matches!(self.what, What::Playlist(_) | What::Liked);
for (i, t) in self.tracks.iter().enumerate() {
let n = if numbered { Some(t.track_number.max(i as u32 + 1)) } else { None };
lines.push(track_line(format!("trk#{i}"), t, n, with_album, &playing));
}
if self.next.is_some() {
lines.push(L::text("more", "További dalok betöltése…", "caption"));
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "hero" {
let context = self.context(cx);
match item {
"play" | "shuffle" => {
let shuffle = item == "shuffle";
if context.is_empty() {
let uris: Vec<String> = self.tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect();
if !uris.is_empty() {
cx.play(Cmd::Tracks { uris, start: 0 });
}
} else {
cx.play(Cmd::Context { uri: context, start: None, shuffle });
}
}
"save" => self.toggle_saved(cx),
_ => {}
}
return;
}
let Some(i) = row_index(line) else { return };
match item {
"more" => {
if let Some(t) = self.tracks.get(i) {
screens::track_menu(cx, t);
}
}
_ => {
let context = self.context(cx);
screens::play_from(cx, &context, &self.tracks, i);
}
}
}
fn more(&mut self, cx: &Cx, list: &str) {
if list == "trk" {
self.load_more(cx);
}
}
fn shown(&mut self, cx: &Cx) {
if let Some(h) = self.head.ready() {
cx.backdrop(&h.cover, Look::Soft, &format!("col:{:?}", self.what));
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

154
src/screens/home.rs Normal file
View File

@@ -0,0 +1,154 @@
//! Kezdőlap: rows: recently played, your playlists (with the
//! liked songs first), your top artists and tracks, saved albums, new
//! releases. Every row loads on its own; a failing one just stays away.
use std::any::Any;
use crate::api::{Album, Artist, Playlist, Played, Track};
use crate::app::{Cx, Look, Screen};
use crate::page::{Frame, L, Spec};
use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, track_card};
#[derive(Default)]
struct Data {
recent: Option<Vec<Played>>,
playlists: Option<Vec<Playlist>>,
liked_total: Option<u32>,
top_artists: Option<Vec<Artist>>,
top_tracks: Option<Vec<Track>>,
albums: Option<Vec<Album>>,
releases: Option<Vec<Album>>,
errors: Vec<String>,
}
pub struct Home {
data: Data,
loading: bool,
started: bool,
}
impl Home {
pub fn new() -> Home {
Home { data: Data::default(), loading: true, started: false }
}
fn load(&mut self, cx: &Cx) {
self.loading = true;
let api = cx.api();
cx.spawn::<Home, _>(
move || {
std::thread::scope(|s| {
let recent = s.spawn(|| api.recently_played());
let playlists = s.spawn(|| api.my_playlists(0));
let liked = s.spawn(|| api.liked(0));
let artists = s.spawn(|| api.top_artists());
let tracks = s.spawn(|| api.top_tracks());
let albums = s.spawn(|| api.saved_albums(0));
let releases = s.spawn(|| api.new_releases());
let mut d = Data::default();
let e = &mut d.errors;
let recent = keep(recent.join(), e);
let playlists = keep(playlists.join(), e).map(|p| p.list());
let liked_total = keep(liked.join(), e).map(|p| p.total);
let top_artists = keep(artists.join(), e);
let top_tracks = keep(tracks.join(), e);
let albums = keep(albums.join(), e).map(|p| p.list());
let releases = keep(releases.join(), e);
Data { recent, playlists, liked_total, top_artists, top_tracks, albums, releases, ..d }
})
},
|s, cx, d| {
s.data = d;
s.loading = false;
// The first picture of the page tints the background.
let first = s.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default();
cx.backdrop(&first, Look::Soft, "home");
},
);
}
}
/// A row's result: the data, or its error noted.
fn keep<T>(r: std::thread::Result<anyhow::Result<T>>, errors: &mut Vec<String>) -> Option<T> {
match r {
Ok(Ok(t)) => Some(t),
Ok(Err(e)) => {
log::warn!("home: {e:#}");
errors.push(crate::api::describe(&e));
None
}
Err(_) => None,
}
}
/// Recently played tracks, each once (newest first).
fn recent_cards(items: &[Played]) -> Vec<crate::page::C> {
let mut seen = std::collections::HashSet::new();
items
.iter()
.filter(|p| seen.insert(p.track.uri.clone()))
.take(20)
.map(|p| track_card(&p.track, p.context.as_ref().map(|c| c.uri.as_str()).unwrap_or("")))
.collect()
}
impl Screen for Home {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame { nav: Some(0), ..Frame::default() };
let mut lines = Vec::new();
if self.loading {
lines.push(L::text("loading", "Betöltés…", "caption"));
return Spec { lines, frame };
}
let d = &self.data;
if let Some(r) = d.recent.as_ref().filter(|r| !r.is_empty()) {
lines.push(L::cards("recent", "Legutóbb játszott", "square", recent_cards(r)).captions());
}
let mut pl = vec![liked_card(d.liked_total)];
pl.extend(d.playlists.iter().flatten().map(playlist_card));
lines.push(L::cards("playlists", "Lejátszási listáid", "square", pl).captions());
if let Some(a) = d.top_artists.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("artists", "Kedvenc előadóid", "round", a.iter().map(artist_card).collect()).captions());
}
if let Some(t) = d.top_tracks.as_ref().filter(|t| !t.is_empty()) {
lines.push(L::cards("top", "Mostanában sokat hallgatod", "square", t.iter().map(|t| track_card(t, "")).collect()).captions());
}
if let Some(a) = d.albums.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("albums", "Elmentett albumaid", "square", a.iter().map(album_card).collect()).captions());
}
if let Some(a) = d.releases.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("releases", "Új megjelenések", "square", a.iter().map(album_card).collect()).captions());
}
if d.recent.is_none() && d.playlists.is_none() && d.top_artists.is_none() {
let why = d.errors.first().cloned().unwrap_or_default();
lines.push(L::notice("error", "bad", "Nem sikerült betölteni a kezdőlapot", why));
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "top" {
// Top tracks play as a list, from the chosen one.
if let Some(t) = &self.data.top_tracks {
let i = t.iter().position(|x| item == format!("t:{}|", x.uri)).unwrap_or(0);
screens::play_from(cx, "", t, i);
return;
}
}
screens::open_card(cx, item);
}
fn shown(&mut self, cx: &Cx) {
let first = self.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default();
cx.backdrop(&first, Look::Soft, "home");
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

151
src/screens/library.rs Normal file
View File

@@ -0,0 +1,151 @@
//! Könyvtár: playlists (the liked songs first), albums, artists, podcasts,
//! one at a time, as a grid. More loads while the focus moves down.
use std::any::Any;
use crate::api::{Album, Artist, Playlist, Show};
use crate::app::{Cx, Screen};
use crate::page::{C, Ch, Frame, GRID, L, Spec, grid_lines};
use crate::screens::{self, Load, album_card, artist_card, liked_card, playlist_card, show_card};
const TABS: [(&str, &str); 4] = [("playlists", "Lejátszási listák"), ("albums", "Albumok"), ("artists", "Előadók"), ("shows", "Podcastok")];
enum Items {
Playlists(Vec<Playlist>, Option<u32>),
Albums(Vec<Album>),
Artists(Vec<Artist>),
Shows(Vec<Show>),
}
pub struct Library {
tab: usize,
items: Load<Items>,
/// Next page: an offset, or the last artist's id (cursor).
next: Option<String>,
loading_more: bool,
started: bool,
}
impl Library {
pub fn new() -> Library {
Library { tab: 0, items: Load::Loading, next: None, loading_more: false, started: false }
}
fn load(&mut self, cx: &Cx, more: bool) {
if more && (self.loading_more || self.next.is_none()) {
return;
}
let next = if more { self.next.clone().unwrap_or_default() } else { String::new() };
if more {
self.loading_more = true;
} else {
self.items = Load::Loading;
self.next = None;
}
let api = cx.api();
let tab = self.tab;
cx.spawn::<Library, _>(
move || -> anyhow::Result<(Items, Option<String>)> {
let offset: u32 = next.parse().unwrap_or(0);
Ok(match tab {
0 => {
let p = api.my_playlists(offset)?;
let liked = if offset == 0 { api.liked(0).ok().map(|p| p.total) } else { None };
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Playlists(p.list(), liked), n)
}
1 => {
let p = api.saved_albums(offset)?;
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Albums(p.list()), n)
}
2 => {
let (a, after) = api.followed_artists(&next)?;
(Items::Artists(a), after)
}
_ => {
let p = api.saved_shows(offset)?;
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Shows(p.list()), n)
}
})
},
move |s, cx, r| {
if s.tab != tab {
return;
}
s.loading_more = false;
match r {
Ok((items, n)) => {
s.next = n;
match (s.items.ready_mut(), items) {
(Some(Items::Playlists(a, _)), Items::Playlists(b, _)) if more => a.extend(b),
(Some(Items::Albums(a)), Items::Albums(b)) if more => a.extend(b),
(Some(Items::Artists(a)), Items::Artists(b)) if more => a.extend(b),
(Some(Items::Shows(a)), Items::Shows(b)) if more => a.extend(b),
(_, items) => s.items = Load::Ready(items),
}
}
Err(e) if more => {
s.next = None;
cx.error("library", &e);
}
Err(e) => s.items = Load::Failed(crate::api::describe(&e)),
}
},
);
}
}
impl Screen for Library {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx, false);
}
let tabs = TABS.iter().enumerate().map(|(i, (id, t))| Ch::new(*id, *t).active(i == self.tab)).collect();
let mut lines = vec![L::page_title("title", "Könyvtár", ""), L::chips("tabs", "", tabs)];
if let Some(st) = self.items.status("status") {
lines.push(st);
} else {
let (cards, style, empty): (Vec<C>, &str, &str) = match self.items.ready().unwrap() {
Items::Playlists(p, liked) => {
let mut c = vec![liked_card(*liked)];
c.extend(p.iter().map(playlist_card));
(c, "square", "")
}
Items::Albums(a) => (a.iter().map(album_card).collect(), "square", "Még nincs elmentett albumod."),
Items::Artists(a) => (a.iter().map(artist_card).collect(), "round", "Még nem követsz előadót."),
Items::Shows(s) => (s.iter().map(show_card).collect(), "square", "Még nem követsz podcastot."),
};
if cards.is_empty() {
lines.push(L::notice("empty", "info", empty, "A telefonos Spotify appban mentett dolgok itt is megjelennek."));
}
lines.extend(grid_lines("grid", "", style, cards, GRID));
}
Spec { lines, frame: Frame { nav: Some(2), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "tabs" {
if let Some(i) = TABS.iter().position(|t| t.0 == item) {
if i != self.tab {
self.tab = i;
self.load(cx, false);
}
}
return;
}
screens::open_card(cx, item);
}
fn more(&mut self, cx: &Cx, list: &str) {
if list == "grid" {
self.load(cx, true);
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

283
src/screens/mod.rs Normal file
View File

@@ -0,0 +1,283 @@
//! The browsing screens. Each one describes its page as lines (src/page.rs)
//! and reacts to OK; see app::Screen.
//!
//! Card ids say what a card opens: "al:<id>" album, "pl:<id>" playlist,
//! "ar:<id>" artist, "sh:<id>" podcast, "liked" the liked songs,
//! "t:<track uri>|<context uri>" plays a track (in its context, if any).
pub mod artist;
pub mod collection;
pub mod home;
pub mod library;
pub mod search;
pub mod settings;
use crate::api::{self, Album, Artist, Playlist, Show, Track};
use crate::app::{Controller, Cx, Screen};
use crate::format;
use crate::page::{C, CARD, L};
use crate::spotify::{Cmd, Start};
use crate::task;
/// The screen of a top navigation section.
pub fn section(n: usize) -> Box<dyn Screen> {
match n {
1 => Box::new(search::Search::new()),
2 => Box::new(library::Library::new()),
3 => Box::new(settings::Settings::new()),
_ => Box::new(home::Home::new()),
}
}
/// Data that loads.
#[derive(Debug, Clone, Default)]
pub enum Load<T> {
#[default]
Loading,
Ready(T),
Failed(String),
}
impl<T> Load<T> {
pub fn ready(&self) -> Option<&T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn ready_mut(&mut self) -> Option<&mut T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn from(r: anyhow::Result<T>) -> Load<T> {
match r {
Ok(t) => Load::Ready(t),
Err(e) => Load::Failed(api::describe(&e)),
}
}
/// The loading / error line, or None when ready.
pub fn status(&self, id: &str) -> Option<L> {
match self {
Load::Loading => Some(L::text(id, "Betöltés…", "caption")),
Load::Failed(e) => Some(L::notice(id, "bad", "Nem sikerült betölteni", e.clone())),
Load::Ready(_) => None,
}
}
}
/// Picture size asked for cards (design px; Spotify's 300 px images fit).
const CARD_IMG: u32 = CARD as u32 + 60;
pub fn album_card(a: &Album) -> C {
let mut c = C::new(format!("al:{}", a.id), a.name.clone(), api::pick(&a.images, CARD_IMG));
c.caption = a.name.clone();
let artists = a.artists.iter().map(|x| x.name.as_str()).collect::<Vec<_>>().join(", ");
let y = format::year(&a.release_date);
c.detail = [y, artists].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
c
}
pub fn playlist_card(p: &Playlist) -> C {
let mut c = C::new(format!("pl:{}", p.id), p.name.clone(), p.image(CARD_IMG));
c.caption = p.name.clone();
c.detail = format!("Lejátszási lista · {}", p.owner_name());
c
}
pub fn artist_card(a: &Artist) -> C {
let mut c = C::new(format!("ar:{}", a.id), a.name.clone(), api::pick(&a.images, CARD_IMG));
c.caption = a.name.clone();
c.detail = "Előadó".into();
c
}
pub fn show_card(s: &Show) -> C {
let mut c = C::new(format!("sh:{}", s.id), s.name.clone(), api::pick(&s.images, CARD_IMG));
c.caption = s.name.clone();
c.detail = if s.publisher.is_empty() { "Podcast".into() } else { s.publisher.clone() };
c
}
/// A track as a card (album art): plays it, in `context` if given.
pub fn track_card(t: &Track, context: &str) -> C {
let mut c = C::new(format!("t:{}|{context}", t.uri), t.name.clone(), t.image(CARD_IMG));
c.caption = t.name.clone();
c.detail = t.artist_names();
c
}
pub fn liked_card(total: Option<u32>) -> C {
let mut c = C::new("liked", "Kedvelt dalok", "");
c.caption = "Kedvelt dalok".into();
c.mark = "liked";
c.detail = match total {
Some(n) => format!("Lejátszási lista · {n} dal"),
None => "Lejátszási lista".into(),
};
c
}
/// A track row. `number`: the album's track number, else the art shows.
pub fn track_line(id: String, t: &Track, number: Option<u32>, with_album: bool, playing: &str) -> L {
let meta = if t.kind == "episode" {
let mut p = vec![format::date(&t.release_date)];
if let Some(r) = &t.resume_point {
if r.fully_played {
p.push("Meghallgatva".into());
} else if r.resume_position_ms > 0 {
p.push(format!("Még {}", format::clock(t.duration_ms.saturating_sub(r.resume_position_ms))));
}
}
p.join(" · ")
} else {
let mut m = t.artist_names();
if with_album {
if let Some(a) = &t.album {
m = format!("{m} · {}", a.name);
}
}
if t.explicit {
m = format!("E · {m}");
}
m
};
let mut l = L::track(id, t.name.clone(), meta, format::clock(t.duration_ms));
match number {
Some(n) => l.note = n.to_string(),
None => l.image = t.image(64),
}
if !playing.is_empty() && t.uri == playing {
l.tone = "playing".into();
}
if !t.playable() {
l.tone = "dim".into();
}
l
}
/// The index in a "<list>#<i>" line id.
pub fn row_index(line: &str) -> Option<usize> {
line.rsplit_once('#')?.1.parse().ok()
}
/// Plays `t` from a list: in `context` if given, else the list's tracks.
pub fn play_from(cx: &Cx, context: &str, tracks: &[Track], i: usize) {
let Some(t) = tracks.get(i) else { return };
if !t.playable() {
cx.toast("Ez a szám nem játszható le.");
return;
}
let shuffle = cx.c.state.borrow().np.shuffle;
if context.is_empty() {
let uris: Vec<String> = tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect();
let start = uris.iter().position(|u| *u == t.uri).unwrap_or(0) as u32;
cx.play(Cmd::Tracks { uris, start });
} else {
cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(t.uri.clone())), shuffle });
}
}
/// Opens the page of a card id (see the module docs); true if it was one.
pub fn open_card(cx: &Cx, key: &str) -> bool {
if key == "liked" {
cx.push(Box::new(collection::Collection::liked()));
} else if let Some(id) = key.strip_prefix("al:") {
cx.push(Box::new(collection::Collection::album(id)));
} else if let Some(id) = key.strip_prefix("pl:") {
cx.push(Box::new(collection::Collection::playlist(id)));
} else if let Some(id) = key.strip_prefix("sh:") {
cx.push(Box::new(collection::Collection::show(id)));
} else if let Some(id) = key.strip_prefix("ar:") {
cx.push(Box::new(artist::ArtistPage::new(id)));
} else if let Some(rest) = key.strip_prefix("t:") {
let (uri, context) = rest.split_once('|').unwrap_or((rest, ""));
let shuffle = cx.c.state.borrow().np.shuffle;
if context.is_empty() {
cx.play(Cmd::Tracks { uris: vec![uri.to_string()], start: 0 });
} else {
cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(uri.to_string())), shuffle });
}
} else {
return false;
}
true
}
/// The "+" of a track row: queue, like, album, artist.
pub fn track_menu(cx: &Cx, t: &Track) {
let c = cx.c.clone();
let t = t.clone();
let api = cx.api();
let id = t.id.clone();
let episode = t.kind == "episode";
task::spawn(
move || if episode || id.is_empty() { None } else { api.liked_contains(&[id]).ok().and_then(|v| v.first().copied()) },
move |liked| open_track_menu(&c, t, liked),
);
}
fn open_track_menu(c: &Controller, t: Track, liked: Option<bool>) {
let mut items: Vec<(String, String, bool)> = vec![("Hozzáadás a lejátszási sorhoz".into(), String::new(), false)];
let mut actions: Vec<&str> = vec!["queue"];
if let Some(l) = liked {
items.push((if l { "Eltávolítás a Kedvelt dalok közül" } else { "Hozzáadás a Kedvelt dalokhoz" }.into(), String::new(), false));
actions.push(if l { "unlike" } else { "like" });
}
if let Some(a) = t.album.as_ref().filter(|a| !a.id.is_empty()) {
items.push(("Album megnyitása".into(), a.name.clone(), false));
actions.push("album");
}
for a in t.artists.iter().filter(|a| !a.id.is_empty()).take(3) {
items.push(("Előadó megnyitása".into(), a.name.clone(), false));
actions.push("artist");
}
if let Some(s) = t.show.as_ref().filter(|s| !s.id.is_empty()) {
items.push(("Podcast megnyitása".into(), s.name.clone(), false));
actions.push("show");
}
let title = t.name.clone();
c.open_select(
&title,
items,
Box::new(move |c: &Controller, i: usize| {
let api = c.api();
let c2 = c.clone();
match actions.get(i).copied() {
Some("queue") => {
let uri = t.uri.clone();
task::spawn(
move || api.add_to_queue(&uri),
move |r| match r {
Ok(()) => c2.toast("Hozzáadva a lejátszási sorhoz", false),
Err(e) if api::status_of(&e) == Some(404) => c2.toast("Előbb indíts el valamit, utána lehet a sorba tenni.", true),
Err(e) => c2.toast(&api::describe(&e), true),
},
);
}
Some(a @ ("like" | "unlike")) => {
let on = a == "like";
let id = t.id.clone();
task::spawn(
move || api.set_liked(&id, on),
move |r| match r {
Ok(()) => c2.toast(if on { "Hozzáadva a Kedvelt dalokhoz" } else { "Eltávolítva a Kedvelt dalok közül" }, false),
Err(e) => c2.toast(&api::describe(&e), true),
},
);
}
Some("album") => c.push_screen(Box::new(collection::Collection::album(&t.album.as_ref().unwrap().id))),
Some("artist") => {
// Which artist: the n-th artist entry of the menu.
let first = actions.iter().position(|a| *a == "artist").unwrap_or(i);
if let Some(a) = t.artists.iter().filter(|a| !a.id.is_empty()).nth(i - first) {
c.push_screen(Box::new(artist::ArtistPage::new(&a.id)));
}
}
Some("show") => c.push_screen(Box::new(collection::Collection::show(&t.show.as_ref().unwrap().id))),
_ => {}
}
}),
);
}

101
src/screens/search.rs Normal file
View File

@@ -0,0 +1,101 @@
//! Keresés: the on-screen keyboard, then songs (rows), artists, albums,
//! playlists and podcasts (cards).
use std::any::Any;
use crate::api::SearchResult;
use crate::app::{Cx, Screen};
use crate::page::{Frame, Kind, L, Spec};
use crate::screens::{self, Load, album_card, artist_card, playlist_card, row_index, show_card, track_line};
pub struct Search {
searched: String,
result: Option<Load<SearchResult>>,
}
impl Search {
pub fn new() -> Search {
Search { searched: String::new(), result: None }
}
}
impl Screen for Search {
fn spec(&mut self, cx: &Cx) -> Spec {
let mut lines = vec![L::page_title("title", "Mit hallgatnál?", "Dalok, előadók, albumok, lejátszási listák és podcastok."), L::new("kb", Kind::Keyboard)];
match &self.result {
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "Két betű elég.")),
Some(Load::Loading) => lines.push(L::text("loading", "Keresés…", "caption")),
Some(Load::Failed(e)) => lines.push(L::notice("error", "bad", "Nem sikerült keresni", e.clone())),
Some(Load::Ready(r)) if r.tracks.is_empty() && r.artists.is_empty() && r.albums.is_empty() && r.playlists.is_empty() && r.shows.is_empty() => {
lines.push(L::notice("none", "info", "Erre nincs találat", "Próbáld másképp írni."))
}
Some(Load::Ready(r)) => {
let playing = cx.playing_uri();
if !r.tracks.is_empty() {
lines.push(L::heading("songs", "Dalok"));
for (i, t) in r.tracks.iter().take(6).enumerate() {
lines.push(track_line(format!("trk#{i}"), t, None, true, &playing));
}
}
if !r.artists.is_empty() {
lines.push(L::cards("artists", "Előadók", "round", r.artists.iter().map(artist_card).collect()).captions());
}
if !r.albums.is_empty() {
lines.push(L::cards("albums", "Albumok", "square", r.albums.iter().map(album_card).collect()).captions());
}
if !r.playlists.is_empty() {
lines.push(L::cards("playlists", "Lejátszási listák", "square", r.playlists.iter().map(playlist_card).collect()).captions());
}
if !r.shows.is_empty() {
lines.push(L::cards("shows", "Podcastok", "square", r.shows.iter().map(show_card).collect()).captions());
}
}
}
Spec { lines, frame: Frame { nav: Some(1), keyboard: Some("Előadó, dal vagy podcast".into()), ..Frame::default() } }
}
fn query(&mut self, cx: &Cx, text: &str, _submit: bool) {
let q = text.trim().to_string();
if q.chars().count() < 2 {
self.result = None;
self.searched.clear();
cx.refresh();
return;
}
if q == self.searched {
return;
}
self.searched = q.clone();
self.result = Some(Load::Loading);
let api = cx.api();
cx.spawn::<Search, _>(move || (api.search(&q), q), |s, _cx, (r, q)| {
if s.searched == q {
s.result = Some(Load::from(r));
}
});
cx.refresh();
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line.starts_with("trk#") {
let Some(Load::Ready(r)) = &self.result else { return };
let Some(i) = row_index(line) else { return };
let tracks: Vec<_> = r.tracks.iter().take(6).cloned().collect();
if item == "more" {
if let Some(t) = tracks.get(i) {
screens::track_menu(cx, t);
}
} else if let Some(t) = tracks.get(i) {
// A found song plays in its album.
let context = t.album.as_ref().map(|a| a.uri.clone()).unwrap_or_default();
screens::play_from(cx, &context, &tracks, i);
}
return;
}
screens::open_card(cx, item);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

96
src/screens/settings.rs Normal file
View File

@@ -0,0 +1,96 @@
//! Beállítások: the account (sign out), the Connect name, sound quality,
//! loudness normalisation, autoplay, the look.
use std::any::Any;
use crate::app::{Cx, Input, Screen};
use crate::page::{Ch, Frame, L, Spec};
pub struct Settings;
impl Settings {
pub fn new() -> Settings {
Settings
}
}
const RESTART: &str = "Az app következő indításakor lép életbe.";
impl Screen for Settings {
fn spec(&mut self, cx: &Cx) -> Spec {
let cfg = cx.cfg();
let user = cx.user();
let mut lines = vec![L::page_title("title", "Beállítások", "")];
lines.push(L::heading("acc-h", "Fiók"));
let plan = match user.product.as_str() {
"premium" => "Premium",
"" => "",
_ => "Ingyenes fiók: a lejátszáshoz Premium kell",
};
let meta = [plan.to_string(), user.country.clone()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
let name = if user.name().is_empty() { "Spotify fiók".to_string() } else { user.name() };
lines.push(L::item("account", name, meta, "Kijelentkezés után a TV újra a telefonról kér bejelentkezést.", vec![Ch::new("signout", "Kijelentkezés").tone("danger")]));
lines.push(L::heading("dev-h", "Spotify Connect"));
lines.push(L::chips("name", "", vec![Ch::field("name", &cfg.device_name, "A TV neve", "tv")]));
lines.push(L::text("name-note", format!("A telefon ezen a néven mutatja a TV-t. {RESTART}"), "caption"));
lines.push(L::heading("play-h", "Lejátszás"));
let q = |id: &str, t: &str, v: u32| Ch::new(id, t).active(cfg.bitrate == v);
lines.push(L::chips("quality", "HANGMINŐSÉG", vec![q("96", "Alacsony · 96 kbit/s", 96), q("160", "Normál · 160 kbit/s", 160), q("320", "Nagyon magas · 320 kbit/s", 320)]));
lines.push(L::chips("normalise", "HANGERŐ-KIEGYENLÍTÉS", vec![Ch::new("on", "Be").active(cfg.normalise), Ch::new("off", "Ki").active(!cfg.normalise)]));
lines.push(L::chips("autoplay", "AUTOMATIKUS LEJÁTSZÁS A LISTA VÉGÉN", vec![Ch::new("on", "Be").active(cfg.autoplay), Ch::new("off", "Ki").active(!cfg.autoplay)]));
lines.push(L::text("play-note", RESTART, "caption"));
lines.push(L::heading("look-h", "Megjelenés"));
let g = |id: &str, t: &str| Ch::new(id, t).active(cfg.glass == id);
lines.push(L::chips("glass", "", vec![g("auto", "Automatikus"), g("full", "Teljes üveg"), g("light", "Könnyű üveg"), g("off", "Matt")]));
lines.push(L::text("look-note", "Automatikus: a TV a grafikus chip ereje szerint választ.", "caption"));
lines.push(L::text("about", format!("Spotify for Fennec OS {} · librespot", env!("CARGO_PKG_VERSION")), "caption"));
Spec { lines, frame: Frame { nav: Some(3), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
match line {
"account" => cx.select::<Settings>(
"Kijelentkezel?",
vec![("Kijelentkezés".into(), String::new(), false), ("Mégse".into(), String::new(), true)],
|_, cx, i| {
if i == 0 {
cx.c.sign_out();
}
},
),
"name" => {
let cur = cx.cfg().device_name;
cx.input::<Settings>(
Input { title: "A TV neve".into(), subtitle: "Ezen a néven látod a telefon Spotify appjában".into(), placeholder: "Fennec TV".into(), value: cur, submit: "Mentés".into(), min: 1 },
|_, cx, text| {
let t = text.trim().to_string();
if !t.is_empty() {
cx.set_cfg(|c| c.device_name = t);
cx.toast(RESTART);
}
},
);
}
"quality" => {
if let Ok(v) = item.parse() {
cx.set_cfg(|c| c.bitrate = v);
}
}
"normalise" => cx.set_cfg(|c| c.normalise = item == "on"),
"autoplay" => cx.set_cfg(|c| c.autoplay = item == "on"),
"glass" => {
cx.set_cfg(|c| c.glass = item.to_string());
crate::config::apply_look(&cx.c.glass, item);
}
_ => {}
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

690
src/spotify.rs Normal file
View File

@@ -0,0 +1,690 @@
//! The Spotify side: a librespot session with Spotify Connect (Spirc), the
//! zeroconf sign-in and the player. It runs on its own tokio runtime; the UI
//! sends `Cmd`s and gets `Event`s on the UI thread.
//!
//! Sign-in, two ways at once (whichever comes first):
//! - Spotify Connect: the TV announces itself on the local network
//! (zeroconf). The Spotify app on a phone lists it among its devices;
//! picking it hands over the credentials.
//! - Pairing code (OAuth device flow, like Spotify's own TV apps): the TV
//! shows a QR code and a short code; the phone signs in at
//! spotify.com/pair, the TV polls for the token.
//!
//! The credentials are kept in `$HOME/.cache/spotify-tv` for the next start.
//! A Premium account is needed (librespot plays nothing else).
//!
//! Playback goes through Spirc, so the TV is a full Connect device: the phone
//! can control it, and playback can move between the TV and other devices.
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures_util::StreamExt;
use librespot_connect::{ConnectConfig, LoadContextOptions, LoadRequest, LoadRequestOptions, Options, PlayingTrack, Spirc};
use librespot_core::authentication::Credentials;
use librespot_core::cache::Cache;
use librespot_core::config::{DeviceType, SessionConfig};
use librespot_core::{Session, SpotifyId};
use librespot_metadata::audio::{AudioItem, UniqueFields};
use librespot_playback::audio_backend;
use librespot_playback::config::{AudioFormat, Bitrate, PlayerConfig};
use librespot_playback::mixer::{self, MixerConfig};
use librespot_playback::player::{Player, PlayerEvent};
use tokio::sync::mpsc;
use crate::config::Config;
/// Scopes of the Web API token (browsing, library, queue).
const SCOPES: &str = "user-read-private,user-read-email,playlist-read-private,playlist-read-collaborative,playlist-modify-private,playlist-modify-public,user-library-read,user-library-modify,user-follow-read,user-follow-modify,user-top-read,user-read-recently-played,user-read-playback-state,user-modify-playback-state,user-read-currently-playing,streaming";
/// The track (or episode) that plays.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Track {
pub uri: String,
/// Base62 id.
pub id: String,
pub name: String,
pub artists: Vec<(String, String)>,
pub album: String,
pub cover: String,
pub duration_ms: u32,
pub episode: bool,
pub explicit: bool,
}
impl Track {
pub fn artist_names(&self) -> String {
self.artists.iter().map(|a| a.1.as_str()).collect::<Vec<_>>().join(", ")
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
/// No credentials: waiting for a phone (device name).
SignIn(String),
Connecting,
/// Signed in (user name).
Ready(String),
Failed(String),
}
/// A pairing code for spotify.com/pair.
#[derive(Debug, Clone, PartialEq)]
pub struct Pair {
pub code: String,
/// Opens the pairing page with the code filled in (the QR code).
pub url: String,
}
#[derive(Debug, Clone)]
pub enum Event {
Status(Status),
/// A new pairing code (None: none could be had, e.g. no network).
Pair(Option<Pair>),
Track(Track),
Loading,
Playing(u32),
Paused(u32),
Seeked(u32),
Stopped,
Unavailable,
Shuffle(bool),
Repeat(bool, bool),
/// This TV became (or stopped being) the active Connect device.
Active(bool),
/// Another device (its name) took over the playback.
Client(String),
}
pub enum Cmd {
/// Plays `context` (an album, playlist, artist, show, "spotify:user:<u>:collection"),
/// from track `start` (a uri) or index, optionally shuffled.
Context { uri: String, start: Option<Start>, shuffle: bool },
/// Plays a list of track uris from index `start`.
Tracks { uris: Vec<String>, start: u32 },
PlayPause,
Play,
Pause,
Next,
Prev,
Seek(u32),
Shuffle(bool),
/// (context, track)
Repeat(bool, bool),
SignOut,
/// The app closes: leave Spotify Connect cleanly.
Quit,
}
#[derive(Debug, Clone)]
pub enum Start {
Uri(String),
}
/// Cheap to clone; usable from any thread.
#[derive(Clone)]
pub struct Engine {
rt: Arc<tokio::runtime::Runtime>,
cmd: mpsc::UnboundedSender<Cmd>,
session: Arc<Mutex<Option<Session>>>,
/// Mock mode (UI work without an account): no librespot at all.
mock: bool,
/// Set when the engine's loop has ended (after `Cmd::Quit`).
stopped: Arc<std::sync::atomic::AtomicBool>,
}
fn cache_dir() -> PathBuf {
crate::config::home().join(".cache").join("spotify-tv")
}
impl Engine {
/// Starts the engine; `events` is called on a runtime thread.
pub fn start(cfg: &Config, events: impl Fn(Event) + Send + Sync + 'static) -> Engine {
let rt = Arc::new(tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().thread_name("spotify").build().expect("tokio runtime"));
let (tx, rx) = mpsc::unbounded_channel();
let session = Arc::new(Mutex::new(None));
let mock = std::env::var_os("SPOTIFY_MOCK").is_some();
let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false));
let engine = Engine { rt: rt.clone(), cmd: tx, session: session.clone(), mock, stopped: stopped.clone() };
let events: Arc<dyn Fn(Event) + Send + Sync> = Arc::new(events);
let cfg = cfg.clone();
rt.spawn(async move {
if mock {
mock_loop(rx, events).await;
} else {
run(cfg, rx, session, events).await;
}
stopped.store(true, std::sync::atomic::Ordering::SeqCst);
});
// The TV closes background apps with SIGTERM: leave like Back does.
#[cfg(unix)]
rt.spawn(async {
if let Ok(mut term) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
term.recv().await;
log::info!("SIGTERM");
let _ = slint::invoke_from_event_loop(|| {
let _ = slint::quit_event_loop();
});
}
});
engine
}
/// Leaves Spotify Connect (the phone sees the TV go), waiting at most
/// `limit` for it.
pub fn shutdown(&self, limit: Duration) {
self.send(Cmd::Quit);
let start = std::time::Instant::now();
while !self.stopped.load(std::sync::atomic::Ordering::SeqCst) && start.elapsed() < limit {
std::thread::sleep(Duration::from_millis(20));
}
}
pub fn send(&self, c: Cmd) {
let _ = self.cmd.send(c);
}
fn session(&self) -> anyhow::Result<Session> {
self.session.lock().unwrap().clone().filter(|s| !s.is_invalid()).ok_or_else(|| anyhow::anyhow!("Nincs kapcsolat a Spotifyjal"))
}
/// A Web API access token (blocking; call it off the UI thread).
pub fn token(&self) -> anyhow::Result<String> {
if self.mock {
return Ok("mock".into());
}
let s = self.session()?;
let t = self.rt.block_on(async move { tokio::time::timeout(Duration::from_secs(15), s.token_provider().get_token(SCOPES)).await });
match t {
Ok(Ok(t)) => Ok(t.access_token),
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
Err(_) => Err(anyhow::anyhow!("A Spotify nem válaszolt")),
}
}
/// Lyrics of a track: (start ms, line), and whether they are synced.
pub fn lyrics(&self, track_id: &str) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
if self.mock {
let lines = ["Ez itt egy dal szövege", "A második sor jön utána", "Aztán a refrén, hangosan", "És még egyszer, halkabban", "", "Vége a versszaknak"];
return Ok((lines.iter().enumerate().map(|(i, l)| (i as u32 * 4000, l.to_string())).collect(), true));
}
let s = self.session()?;
let id = SpotifyId::from_base62(track_id).map_err(|e| anyhow::anyhow!("{e}"))?;
let body = self.rt.block_on(async move { s.spclient().get_lyrics(&id).await }).map_err(|e| anyhow::anyhow!("{e}"))?;
parse_lyrics(&body)
}
}
/// Spotify's color-lyrics JSON -> lines.
pub fn parse_lyrics(body: &[u8]) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
let v: serde_json::Value = serde_json::from_slice(body)?;
let l = &v["lyrics"];
let synced = l["syncType"].as_str() == Some("LINE_SYNCED");
let lines = l["lines"]
.as_array()
.map(|a| {
a.iter()
.map(|x| {
let t = x["startTimeMs"].as_str().and_then(|s| s.parse().ok()).or_else(|| x["startTimeMs"].as_u64().map(|v| v as u32)).unwrap_or(0);
let w = x["words"].as_str().unwrap_or("").replace('♪', "").trim().to_string();
(t, w)
})
.collect()
})
.unwrap_or_default();
Ok((lines, synced))
}
fn track_of(item: &AudioItem) -> Track {
let id = item.track_id.to_id().unwrap_or_default();
let cover = item.covers.iter().max_by_key(|c| c.width).map(|c| c.url.clone()).unwrap_or_default();
let (artists, album, episode) = match &item.unique_fields {
UniqueFields::Track { artists, album, .. } => (
artists.0.iter().map(|a| (a.id.to_id().unwrap_or_default(), a.name.clone())).collect(),
album.clone(),
false,
),
UniqueFields::Episode { show_name, .. } => (vec![(String::new(), show_name.clone())], show_name.clone(), true),
UniqueFields::Local { artists, album, .. } => (artists.iter().map(|a| (String::new(), a.clone())).collect(), album.clone().unwrap_or_default(), false),
};
Track { uri: item.uri.clone(), id, name: item.name.clone(), artists, album, cover, duration_ms: item.duration_ms, episode, explicit: item.is_explicit }
}
fn bitrate(b: u32) -> Bitrate {
match b {
96 => Bitrate::Bitrate96,
320 => Bitrate::Bitrate320,
_ => Bitrate::Bitrate160,
}
}
fn load_request(c: Cmd) -> Option<LoadRequest> {
match c {
Cmd::Context { uri, start, shuffle } => {
let options = LoadRequestOptions {
start_playing: true,
seek_to: 0,
context_options: Some(LoadContextOptions::Options(Options { shuffle, repeat: false, repeat_track: false })),
playing_track: start.map(|Start::Uri(u)| PlayingTrack::Uri(u)),
};
Some(LoadRequest::from_context_uri(uri, options))
}
Cmd::Tracks { uris, start } => {
let options = LoadRequestOptions { start_playing: true, seek_to: 0, context_options: None, playing_track: Some(PlayingTrack::Index(start)) };
Some(LoadRequest::from_tracks(uris, options))
}
_ => None,
}
}
async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mutex<Option<Session>>>, events: Arc<dyn Fn(Event) + Send + Sync>) {
let dir = cache_dir();
let cache = match Cache::new(Some(dir.clone()), Some(dir.clone()), Some(dir.join("audio")), Some(512 << 20)) {
Ok(c) => Some(c),
Err(e) => {
log::warn!("cache: {e}");
None
}
};
let mut session_config = SessionConfig::default();
session_config.device_id = cfg.device_id.clone();
session_config.autoplay = Some(cfg.autoplay);
let connect_config = ConnectConfig {
name: cfg.device_name.clone(),
device_type: DeviceType::Tv,
is_group: false,
// The TV sets the loudness; Spotify plays at full scale.
initial_volume: u16::MAX,
disable_volume: false,
volume_steps: 64,
};
let player_config = PlayerConfig { bitrate: bitrate(cfg.bitrate), normalisation: cfg.normalise, gapless: true, ..PlayerConfig::default() };
let mixer = match mixer::find(None).map(|m| m(MixerConfig::default())) {
Some(Ok(m)) => m,
_ => {
events(Event::Status(Status::Failed("A hangkeverő nem indult el".into())));
return;
}
};
#[cfg(target_os = "linux")]
let backend = audio_backend::find(Some("gstreamer".into()));
#[cfg(not(target_os = "linux"))]
let backend = audio_backend::find(None);
let Some(backend) = backend else {
events(Event::Status(Status::Failed("Nincs hangkimenet".into())));
return;
};
let mut session = Session::new(session_config.clone(), cache.clone());
let player = Player::new(player_config, session.clone(), mixer.get_soft_volume(), move || backend(None, AudioFormat::default()));
*shared.lock().unwrap() = Some(session.clone());
// Player events -> UI.
{
let mut ch = player.get_player_event_channel();
let events = events.clone();
tokio::spawn(async move {
while let Some(ev) = ch.recv().await {
if let Some(e) = player_event(ev) {
events(e);
}
}
});
}
// Zeroconf: the phone signs in (or switches the account).
let mut discovery = match librespot_discovery::Discovery::builder(session_config.device_id.clone(), session_config.client_id.clone())
.name(cfg.device_name.clone())
.device_type(DeviceType::Tv)
.launch()
{
Ok(d) => Some(d),
Err(e) => {
log::warn!("discovery: {e}");
None
}
};
// Pairing codes: run while signed out.
let (pair_tx, mut pair_rx) = mpsc::unbounded_channel::<Credentials>();
let mut pairing: Option<tokio::task::JoinHandle<()>> = None;
let start_pairing = |pairing: &mut Option<tokio::task::JoinHandle<()>>| {
if pairing.as_ref().is_none_or(|p| p.is_finished()) {
*pairing = Some(tokio::spawn(pair_loop(session_config.client_id.clone(), events.clone(), pair_tx.clone())));
}
};
let mut credentials: Option<Credentials> = cache.as_ref().and_then(Cache::credentials);
let mut connecting = credentials.is_some();
if connecting {
events(Event::Status(Status::Connecting));
} else {
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
start_pairing(&mut pairing);
}
let mut spirc: Option<Spirc> = None;
let mut spirc_task: Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>> = None;
let mut failures = 0u32;
// Commands that came before Spirc was up (a load right after sign-in).
let mut waiting: Vec<Cmd> = Vec::new();
loop {
tokio::select! {
creds = async { match discovery.as_mut() { Some(d) => d.next().await, None => std::future::pending().await } } => {
let Some(creds) = creds else {
log::warn!("discovery stopped");
discovery = None;
continue;
};
log::info!("signed in from the network");
if let Some(p) = pairing.take() { p.abort(); }
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
if !session.is_invalid() { session.shutdown(); }
credentials = Some(creds);
failures = 0;
connecting = true;
events(Event::Status(Status::Connecting));
}
creds = pair_rx.recv() => {
let Some(creds) = creds else { continue };
log::info!("signed in with a pairing code");
pairing = None;
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
if !session.is_invalid() { session.shutdown(); }
credentials = Some(creds);
failures = 0;
connecting = true;
events(Event::Status(Status::Connecting));
}
_ = async {}, if connecting => {
connecting = false;
if session.is_invalid() {
session = Session::new(session_config.clone(), cache.clone());
player.set_session(session.clone());
*shared.lock().unwrap() = Some(session.clone());
}
let creds = credentials.clone().unwrap_or_default();
match Spirc::new(connect_config.clone(), session.clone(), creds, player.clone(), mixer.clone()).await {
Ok((s, task)) => {
for c in waiting.drain(..) { apply(&s, c); }
spirc = Some(s);
spirc_task = Some(Box::pin(task));
*shared.lock().unwrap() = Some(session.clone());
events(Event::Status(Status::Ready(session.username())));
}
Err(e) => {
log::warn!("connect: {e}");
let msg = e.to_string();
// Bad credentials: sign in again from the phone.
if msg.contains("BadCredentials") || msg.contains("PremiumAccountRequired") || msg.contains("Login failed") {
if let Some(c) = &cache { let _ = std::fs::remove_file(cache_dir().join("credentials.json")); let _ = c; }
credentials = None;
let text = if msg.contains("Premium") { "Ehhez Spotify Premium előfizetés kell." } else { "A bejelentkezés lejárt." };
events(Event::Status(Status::Failed(format!("{text} Jelentkezz be újra a telefonról."))));
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
start_pairing(&mut pairing);
} else {
failures += 1;
events(Event::Status(Status::Failed(format!("Nem sikerült csatlakozni a Spotifyhoz: {msg}"))));
let delay = Duration::from_secs((2u64 << failures.min(5)).min(60));
tokio::time::sleep(delay).await;
connecting = credentials.is_some();
if connecting { events(Event::Status(Status::Connecting)); }
}
}
}
}
_ = async { if let Some(t) = spirc_task.as_mut() { t.await } else { std::future::pending().await } } => {
// Spirc ended: the connection broke. Reconnect.
log::warn!("connect ended, reconnecting");
spirc_task = None;
spirc = None;
if credentials.is_some() {
failures += 1;
tokio::time::sleep(Duration::from_secs((1u64 << failures.min(5)).min(30))).await;
connecting = true;
events(Event::Status(Status::Connecting));
}
}
cmd = rx.recv() => {
let Some(cmd) = cmd else { break };
if matches!(cmd, Cmd::Quit) { break; }
if matches!(cmd, Cmd::SignOut) {
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
player.stop();
if !session.is_invalid() { session.shutdown(); }
let _ = std::fs::remove_file(cache_dir().join("credentials.json"));
credentials = None;
events(Event::Stopped);
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
start_pairing(&mut pairing);
continue;
}
match &spirc {
Some(s) => { failures = 0; apply(s, cmd) }
None => waiting.push(cmd),
}
}
}
}
if let Some(s) = spirc.take() {
let _ = s.shutdown();
}
if let Some(t) = spirc_task.take() {
let _ = tokio::time::timeout(Duration::from_secs(2), t).await;
}
if let Some(p) = pairing {
p.abort();
}
if let Some(d) = discovery {
d.shutdown().await;
}
}
// ---------------------------------------------------------------------------- pairing
const ACCOUNTS: &str = "https://accounts.spotify.com";
/// The scopes librespot asks for when signing in with a token.
const PAIR_SCOPES: &str = "app-remote-control playlist-modify playlist-modify-private playlist-modify-public playlist-read playlist-read-collaborative playlist-read-private streaming ugc-image-upload user-follow-modify user-follow-read user-library-modify user-library-read user-modify user-modify-playback-state user-modify-private user-personalized user-read-currently-playing user-read-email user-read-play-history user-read-playback-position user-read-playback-state user-read-private user-read-recently-played user-top-read";
struct DeviceCode {
device_code: String,
pair: Pair,
interval: u64,
expires: u64,
}
enum Poll {
Pending,
SlowDown,
Token(String),
/// Expired or refused: a new code is needed.
Over,
}
fn form(pairs: &[(&str, &str)]) -> String {
pairs.iter().map(|(k, v)| format!("{k}={}", crate::api::enc(v))).collect::<Vec<_>>().join("&")
}
fn post_form(path: &str, body: String) -> anyhow::Result<(u16, serde_json::Value)> {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into();
let resp = agent.post(&format!("{ACCOUNTS}{path}")).header("Content-Type", "application/x-www-form-urlencoded").send(body)?;
let status = resp.status().as_u16();
let text = resp.into_body().read_to_string()?;
Ok((status, serde_json::from_str(&text).unwrap_or_default()))
}
fn request_code(client_id: &str) -> anyhow::Result<DeviceCode> {
let (status, v) = post_form("/oauth2/device/authorize", form(&[("client_id", client_id), ("scope", PAIR_SCOPES)]))?;
let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
if status != 200 || s("device_code").is_empty() {
anyhow::bail!("pairing code: {status} {v}");
}
let url = if s("verification_uri_complete").is_empty() { s("verification_uri") } else { s("verification_uri_complete") };
Ok(DeviceCode {
device_code: s("device_code"),
pair: Pair { code: s("user_code"), url },
interval: v["interval"].as_u64().unwrap_or(5).max(2),
expires: v["expires_in"].as_u64().unwrap_or(600),
})
}
fn poll_token(client_id: &str, device_code: &str) -> anyhow::Result<Poll> {
let (status, v) = post_form("/api/token", form(&[("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), ("device_code", device_code), ("client_id", client_id)]))?;
if status == 200 {
if let Some(t) = v["access_token"].as_str() {
return Ok(Poll::Token(t.to_string()));
}
}
Ok(match v["error"].as_str().unwrap_or("") {
"authorization_pending" => Poll::Pending,
"slow_down" => Poll::SlowDown,
_ => Poll::Over,
})
}
/// Shows pairing codes (a new one when one expires) until the phone signs in.
async fn pair_loop(client_id: String, events: Arc<dyn Fn(Event) + Send + Sync>, done: mpsc::UnboundedSender<Credentials>) {
loop {
let cid = client_id.clone();
let code = match tokio::task::spawn_blocking(move || request_code(&cid)).await {
Ok(Ok(c)) => c,
other => {
if let Ok(Err(e)) = other {
log::warn!("{e:#}");
}
events(Event::Pair(None));
tokio::time::sleep(Duration::from_secs(15)).await;
continue;
}
};
events(Event::Pair(Some(code.pair.clone())));
let deadline = std::time::Instant::now() + Duration::from_secs(code.expires.saturating_sub(10));
let mut interval = code.interval;
while std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_secs(interval)).await;
let (cid, dc) = (client_id.clone(), code.device_code.clone());
match tokio::task::spawn_blocking(move || poll_token(&cid, &dc)).await {
Ok(Ok(Poll::Token(t))) => {
let _ = done.send(Credentials::with_access_token(t));
return;
}
Ok(Ok(Poll::SlowDown)) => interval += 5,
Ok(Ok(Poll::Over)) => break,
Ok(Ok(Poll::Pending)) => {}
// Network trouble: keep the code, try again.
Ok(Err(e)) => log::info!("pairing poll: {e:#}"),
Err(_) => {}
}
}
}
}
fn apply(s: &Spirc, c: Cmd) {
let r = match c {
Cmd::Context { .. } | Cmd::Tracks { .. } => {
let req = load_request(c).unwrap();
// The TV takes the playback over (it may be on the phone).
let _ = s.activate();
s.load(req)
}
Cmd::PlayPause => s.play_pause(),
Cmd::Play => s.activate().and_then(|_| s.play()),
Cmd::Pause => s.pause(),
Cmd::Next => s.next(),
Cmd::Prev => s.prev(),
Cmd::Seek(ms) => s.set_position_ms(ms),
Cmd::Shuffle(on) => s.shuffle(on),
Cmd::Repeat(ctx, track) => s.repeat(ctx).and_then(|_| s.repeat_track(track)),
Cmd::SignOut | Cmd::Quit => Ok(()),
};
if let Err(e) = r {
log::warn!("command: {e}");
}
}
fn player_event(ev: PlayerEvent) -> Option<Event> {
Some(match ev {
PlayerEvent::TrackChanged { audio_item } => Event::Track(track_of(&audio_item)),
PlayerEvent::Loading { .. } => Event::Loading,
PlayerEvent::Playing { position_ms, .. } => Event::Playing(position_ms),
PlayerEvent::Paused { position_ms, .. } => Event::Paused(position_ms),
PlayerEvent::Seeked { position_ms, .. } | PlayerEvent::PositionCorrection { position_ms, .. } => Event::Seeked(position_ms),
PlayerEvent::Stopped { .. } => Event::Stopped,
PlayerEvent::Unavailable { .. } => Event::Unavailable,
PlayerEvent::ShuffleChanged { shuffle } => Event::Shuffle(shuffle),
PlayerEvent::RepeatChanged { context, track } => Event::Repeat(context, track),
PlayerEvent::SessionConnected { .. } => Event::Active(true),
PlayerEvent::SessionDisconnected { .. } => Event::Active(false),
PlayerEvent::SessionClientChanged { client_name, .. } => Event::Client(client_name),
_ => return None,
})
}
/// Mock mode: signed in at once; "plays" a made-up track for every load.
async fn mock_loop(mut rx: mpsc::UnboundedReceiver<Cmd>, events: Arc<dyn Fn(Event) + Send + Sync>) {
tokio::time::sleep(Duration::from_millis(300)).await;
if std::env::var("SPOTIFY_MOCK").as_deref() == Ok("signin") {
events(Event::Status(Status::SignIn("Fennec TV".into())));
events(Event::Pair(Some(Pair { code: "5HWPC6".into(), url: "https://spotify.com/pair?code=5HWPC6".into() })));
std::future::pending::<()>().await;
}
events(Event::Status(Status::Ready("demo".into())));
let mut playing = false;
let mut n = 0u32;
let track = |n: u32| Track {
uri: format!("spotify:track:mock{n}"),
id: format!("mock{n}"),
name: ["Hajnali fények", "Nyári éjszaka", "Városi zaj", "Csend a víz felett"][n as usize % 4].into(),
artists: vec![("mockartist".into(), "Demó Előadó".into())],
album: "Demó album".into(),
cover: format!("https://picsum.photos/seed/cover{}/640/640", n % 4),
duration_ms: 214_000,
episode: false,
explicit: false,
};
while let Some(c) = rx.recv().await {
match c {
Cmd::Context { .. } | Cmd::Tracks { .. } => {
n += 1;
events(Event::Active(true));
events(Event::Track(track(n)));
events(Event::Playing(0));
playing = true;
}
Cmd::PlayPause => {
playing = !playing;
events(if playing { Event::Playing(30_000) } else { Event::Paused(30_000) });
}
Cmd::Play => events(Event::Playing(30_000)),
Cmd::Pause => events(Event::Paused(30_000)),
Cmd::Next | Cmd::Prev => {
n += 1;
events(Event::Track(track(n)));
events(Event::Playing(0));
}
Cmd::Seek(ms) => events(Event::Seeked(ms)),
Cmd::Shuffle(on) => events(Event::Shuffle(on)),
Cmd::Repeat(c, t) => events(Event::Repeat(c, t)),
Cmd::SignOut => events(Event::Status(Status::SignIn("Fennec TV".into()))),
Cmd::Quit => break,
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn parses_lyrics() {
let body = br#"{"lyrics":{"syncType":"LINE_SYNCED","lines":[{"startTimeMs":"1200","words":"Hello"},{"startTimeMs":"5300","words":""}]},"colors":{}}"#;
let (lines, synced) = super::parse_lyrics(body).unwrap();
assert!(synced);
assert_eq!(lines, vec![(1200, "Hello".to_string()), (5300, String::new())]);
}
}

40
src/task.rs Normal file
View File

@@ -0,0 +1,40 @@
//! Blocking work (HTTP calls) on a thread, its result back on the UI thread.
//!
//! `done` runs on the Slint event loop, so it may touch the UI and `Rc`
//! state; it is kept in a thread-local table while the work runs.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
type Done = Box<dyn FnOnce(Box<dyn std::any::Any + Send>)>;
thread_local! {
static WAITING: RefCell<HashMap<u64, Done>> = RefCell::new(HashMap::new());
}
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Runs `work` on a new thread; `done(result)` runs on the UI thread. Call it
/// from the UI thread.
pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(T) + 'static) {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
WAITING.with(|w| {
w.borrow_mut().insert(
id,
Box::new(move |any: Box<dyn std::any::Any + Send>| {
if let Ok(v) = any.downcast::<T>() {
done(*v);
}
}),
)
});
std::thread::spawn(move || {
let result: Box<dyn std::any::Any + Send> = Box::new(work());
let _ = slint::invoke_from_event_loop(move || {
if let Some(done) = WAITING.with(|w| w.borrow_mut().remove(&id)) {
done(result);
}
});
});
}

171
tools/mock_server.py Executable file
View File

@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Stand-in for the Spotify Web API (api.spotify.com/v1), for UI work and
screenshots without an account. Made-up data, pictures from picsum.photos.
python3 tools/mock_server.py --port 7890
SPOTIFY_MOCK=1 SPOTIFY_API=http://127.0.0.1:7890/v1 cargo run
SPOTIFY_MOCK=1 also replaces librespot (signed in at once, fake playback);
SPOTIFY_MOCK=signin shows the sign-in screen with a sample code.
"""
import argparse
import json
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
def img(seed, size=640):
return [{"url": f"https://picsum.photos/seed/{seed}/{size}/{size}", "width": size, "height": size},
{"url": f"https://picsum.photos/seed/{seed}/300/300", "width": 300, "height": 300}]
ARTISTS = ["Napfény Zenekar", "Éjféli Kék", "Hold Utca", "Kristóf Vass", "Lili és a Fények", "Déli Szél",
"Városi Zaj", "Mira", "Tisza Trió", "Galaxis", "Neon Hajnal", "Bori"]
WORDS = ["Hajnali", "Nyári", "Csendes", "Fényes", "Messzi", "Kék", "Arany", "Éjszakai", "Vad", "Puha", "Régi", "Új"]
NOUNS = ["fények", "utca", "tenger", "város", "dal", "álom", "szél", "eső", "tánc", "csillagok", "part", "hajó"]
def artist(i):
return {"id": f"ar{i}", "name": ARTISTS[i % len(ARTISTS)], "uri": f"spotify:artist:ar{i}", "type": "artist",
"images": img(f"artist{i}"), "followers": {"total": 12345 * (i + 3) * 17}, "genres": ["magyar pop", "indie"]}
def album(i):
return {"id": f"al{i}", "name": f"{WORDS[i % 12]} {NOUNS[(i * 5) % 12]}", "uri": f"spotify:album:al{i}",
"images": img(f"album{i}"), "artists": [{"id": f"ar{i % 12}", "name": ARTISTS[i % 12], "uri": f"spotify:artist:ar{i % 12}"}],
"release_date": f"{2010 + i % 15}-0{1 + i % 9}-1{i % 9}", "total_tracks": 10, "album_type": "album" if i % 3 else "single",
"label": "Fennec Records"}
def track(i, with_album=True):
a = album(i // 10)
t = {"id": f"tr{i}", "name": f"{WORDS[(i * 7) % 12]} {NOUNS[(i * 3) % 12]}", "uri": f"spotify:track:tr{i}", "type": "track",
"duration_ms": 150000 + (i * 7919) % 120000, "explicit": i % 7 == 0, "track_number": i % 10 + 1,
"artists": [{"id": f"ar{i % 12}", "name": ARTISTS[i % 12], "uri": f"spotify:artist:ar{i % 12}"}]}
if with_album:
t["album"] = a
return t
def playlist(i):
names = ["Reggeli kávé", "Edzés", "Esti nyugalom", "Road trip", "Fókusz", "Buli", "Magyar slágerek", "Discover Weekly",
"Release Radar", "Chill", "Gitáros", "Retro 80s"]
return {"id": f"pl{i}", "name": names[i % len(names)], "uri": f"spotify:playlist:pl{i}", "images": img(f"pl{i}"),
"description": "Válogatás <a href=\"x\">a legjobbakból</a> &amp; még több.", "owner": {"id": "demo" if i < 4 else "spotify",
"display_name": "Demó" if i < 4 else "Spotify"}, "tracks": {"total": 40}, "followers": {"total": 1200 * (i + 1)}}
def show(i):
names = ["Tudomány percek", "Zene és ember", "Esti mese", "Tech hírek", "Futás közben"]
return {"id": f"sh{i}", "name": names[i % 5], "uri": f"spotify:show:sh{i}", "images": img(f"show{i}"),
"publisher": "Fennec Podcast", "description": "Heti beszélgetések.", "total_episodes": 30}
def episode(i):
return {"id": f"ep{i}", "name": f"{i + 1}. rész: {WORDS[i % 12]} {NOUNS[i % 12]}", "uri": f"spotify:episode:ep{i}",
"type": "episode", "duration_ms": 1800000 + i * 60000, "release_date": f"2026-10-{1 + i % 28:02d}",
"images": img(f"ep{i}"), "description": "Egy epizód.", "resume_point": {"fully_played": i % 4 == 1, "resume_position_ms": 600000 if i % 4 == 2 else 0}}
def page(items, offset, limit, total, url):
nxt = f"{url}?offset={offset + limit}&limit={limit}" if offset + limit < total else None
return {"items": items, "offset": offset, "limit": limit, "total": total, "next": nxt}
class H(BaseHTTPRequestHandler):
def send_json(self, obj, code=200):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass
def do_PUT(self):
self.send_response(204)
self.end_headers()
do_DELETE = do_PUT
do_POST = do_PUT
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
p = u.path.removeprefix("/v1")
off, lim = int(q.get("offset", 0)), int(q.get("limit", 20))
if p == "/me":
return self.send_json({"id": "demo", "display_name": "Demó Felhasználó", "product": "premium", "country": "HU", "images": img("me", 300)})
if p == "/me/player/recently-played":
return self.send_json({"items": [{"track": track(i * 3), "context": {"uri": f"spotify:album:al{i * 3 // 10}", "type": "album"}} for i in range(20)]})
if p == "/me/top/artists":
return self.send_json(page([artist(i) for i in range(12)], 0, 20, 12, p))
if p == "/me/top/tracks":
return self.send_json(page([track(i * 5) for i in range(15)], 0, 20, 15, p))
if p == "/browse/new-releases":
return self.send_json({"albums": page([album(i + 20) for i in range(15)], 0, 20, 15, p)})
if p == "/me/playlists":
return self.send_json(page([playlist(i) for i in range(off, min(off + 50, 12))], off, 50, 12, p))
if p == "/me/tracks":
total = 230
return self.send_json(page([{"track": track(i)} for i in range(off, min(off + lim, total))], off, lim, total, p))
if p == "/me/albums":
return self.send_json(page([{"album": album(i)} for i in range(off, min(off + 50, 18))], off, 50, 18, p))
if p == "/me/shows":
return self.send_json(page([{"show": show(i)} for i in range(5)], 0, 50, 5, p))
if p == "/me/following":
return self.send_json({"artists": {"items": [artist(i) for i in range(12)], "cursors": {"after": None}}})
if p.endswith("/contains"):
ids = q.get("ids", "x").split(",")
return self.send_json([i.endswith("1") for i in ids])
if m := re.fullmatch(r"/playlists/(\w+)", p):
return self.send_json(playlist(int(m[1][2:])))
if m := re.fullmatch(r"/playlists/(\w+)/(tracks|items)", p):
total = 140
return self.send_json(page([{"track": track(i * 2 + 1)} for i in range(off, min(off + lim, total))], off, lim, total, p))
if m := re.fullmatch(r"/albums/(\w+)", p):
n = int(m[1][2:])
a = album(n)
a["tracks"] = page([track(n * 10 + i, False) for i in range(10)], 0, 50, 10, p)
return self.send_json(a)
if m := re.fullmatch(r"/albums/(\w+)/tracks", p):
return self.send_json(page([], off, lim, 10, p))
if m := re.fullmatch(r"/artists/(\w+)", p):
return self.send_json(artist(int(m[1][2:])))
if m := re.fullmatch(r"/artists/(\w+)/top-tracks", p):
n = int(m[1][2:])
return self.send_json({"tracks": [track(n + 12 * i) for i in range(10)]})
if m := re.fullmatch(r"/artists/(\w+)/albums", p):
n = int(m[1][2:])
return self.send_json(page([album(n + 12 * i) for i in range(6)], 0, 30, 6, p))
if m := re.fullmatch(r"/shows/(\w+)", p):
return self.send_json(show(int(m[1][2:])))
if m := re.fullmatch(r"/shows/(\w+)/episodes", p):
return self.send_json(page([episode(i) for i in range(off, min(off + 50, 30))], off, 50, 30, p))
if p == "/search":
return self.send_json({
"tracks": page([track(i * 11) for i in range(10)], 0, 10, 10, p),
"artists": page([artist(i) for i in range(6)], 0, 10, 6, p),
"albums": page([album(i) for i in range(8)], 0, 10, 8, p),
"playlists": page([None] + [playlist(i) for i in range(6)], 0, 10, 7, p),
"shows": page([show(i) for i in range(3)], 0, 10, 3, p),
})
if p == "/me/player/queue":
return self.send_json({"currently_playing": track(1), "queue": [track(i + 40) for i in range(12)]})
self.send_json({"error": {"status": 404, "message": "not found"}}, 404)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=7890)
a = ap.parse_args()
print(f"mock Spotify Web API on http://127.0.0.1:{a.port}/v1")
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
if __name__ == "__main__":
main()

195
ui/app.slint Normal file
View File

@@ -0,0 +1,195 @@
// Spotify for Fennec OS: the root window.
//
// Screens: "message" (start-up, errors), "signin" (QR code / Spotify app),
// "page" (every browsing screen: a LinePage built by src/page.rs),
// "nowplaying". Over them: the text input, the picker, the toast.
//
// Rust owns state and focus: every key goes to the `key` callback, except
// while a keyboard has the focus (the input overlay, the search keyboard).
import { TvWindow, Tv, SfText, GlassRect, MenuItem } from "@sf-ui/sf-ui.slint";
import { Line, Chip, Card, Check, QueueItem } from "types.slint";
import { LinePage } from "page.slint";
import { NowPlayingScreen } from "nowplaying.slint";
import { ConnectScreen, InputScreen, MessageScreen } from "signin.slint";
import { SelectOverlay, Toast } from "overlays.slint";
export { Tv, SfText, MenuItem, Line, Chip, Card, Check, QueueItem }
export component App inherits TvWindow {
title: "Spotify";
forward-focus: keys;
// "message", "signin", "page", "nowplaying"
in property <string> screen: "message";
// The key text (Slint's Key codes) and whether it repeats; true = handled.
callback key(string, bool) -> bool;
out property <float> message-t: self.screen == "message" ? 1 : 0;
animate message-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> signin-t: self.screen == "signin" ? 1 : 0;
animate signin-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> page-t: self.screen == "page" ? 1 : 0;
animate page-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> np-t: self.screen == "nowplaying" ? 1 : 0;
animate np-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> input-t: self.input-open ? 1 : 0;
animate input-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> select-t: self.select-open ? 1 : 0;
animate select-t { duration: 300ms; easing: cubic-bezier(0.3, 1.18, 0.4, 1); }
// Whatever an overlay would cover goes away first.
property <float> under: max(0, 1 - 1.6 * max(self.input-t, self.select-t));
// The outgoing screen goes first, the incoming one follows.
function vis(t: float) -> float {
clamp(t * 2 - 1, 0, 1)
}
keys := FocusScope {
key-pressed(event) => {
if root.input-open {
return input.key(event);
}
if root.screen == "page" && root.page-kb-focused && !root.select-open {
return page.kb-key(event);
}
if root.key(event.text, event.repeat) {
return accept;
}
reject
}
}
// ---- message ----
in property <bool> message-busy <=> message.busy;
in property <string> message-title <=> message.title;
in property <string> message-text <=> message.text;
message := MessageScreen {
alpha: root.vis(root.message-t);
visible: self.alpha > 0.001;
}
// ---- sign-in ----
in property <string> signin-device <=> signin.device;
in property <string> signin-code <=> signin.code;
in property <image> signin-qr <=> signin.qr;
in property <bool> signin-busy <=> signin.busy;
in property <string> signin-error <=> signin.error;
signin := ConnectScreen {
alpha: root.vis(root.signin-t);
visible: self.alpha > 0.001;
}
// ---- page ----
in property <[Line]> page-lines <=> page.lines;
in property <int> page-focus <=> page.focus-line;
in property <float> page-scroll <=> page.scroll;
in property <bool> page-show-nav <=> page.show-nav;
in property <[string]> page-nav-items <=> page.nav-items;
in property <int> page-nav-index <=> page.nav-index;
in property <bool> page-nav-focused <=> page.nav-focused;
in property <string> page-np-title <=> page.np-title;
in property <string> page-np-artist <=> page.np-artist;
in property <bool> page-np-playing <=> page.np-playing;
in property <bool> page-np-focused <=> page.np-focused;
in property <image> page-user-image <=> page.user-image;
in property <string> page-user-initial <=> page.user-initial;
in property <float> page-kb-y <=> page.kb-y;
in property <bool> page-kb-focused <=> page.kb-focused;
in property <string> page-kb-placeholder <=> page.kb-placeholder;
in-out property <string> page-query <=> page.query;
callback search-submitted(string);
callback search-changed(string);
changed page-query => {
root.search-changed(self.page-query);
}
callback search-exit-down();
callback search-exit-up();
callback search-cancelled();
public function page-kb-reset() {
page.kb-reset();
}
page := LinePage {
alpha: root.vis(root.page-t) * root.under;
visible: root.page-t > 0.001;
search-submitted(t) => { root.search-submitted(t); }
search-exit-down => { root.search-exit-down(); }
search-exit-up => { root.search-exit-up(); }
search-cancelled => { root.search-cancelled(); }
}
// ---- now playing ----
in property <string> np-title <=> np.title;
in property <string> np-artist <=> np.artist;
in property <string> np-album <=> np.album;
in property <image> np-cover <=> np.art;
in property <bool> np-explicit <=> np.explicit;
in property <bool> np-episode <=> np.episode;
in property <bool> np-playing <=> np.playing;
in property <bool> np-loading <=> np.loading;
in property <float> np-progress <=> np.progress;
in property <string> np-time <=> np.time;
in property <string> np-duration <=> np.duration;
in property <bool> np-shuffle <=> np.shuffle;
in property <int> np-repeat <=> np.repeat;
in property <int> np-liked <=> np.liked;
in property <int> np-focus <=> np.button;
in property <int> np-area <=> np.area;
in property <int> np-panel <=> np.panel;
in property <[string]> np-lyrics <=> np.lyrics;
in property <int> np-lyric-line <=> np.lyric-line;
in property <bool> np-lyrics-synced <=> np.lyrics-synced;
in property <string> np-lyrics-note <=> np.lyrics-note;
in property <[QueueItem]> np-queue <=> np.queue;
in property <string> np-queue-note <=> np.queue-note;
in property <string> np-device <=> np.device;
np := NowPlayingScreen {
alpha: root.vis(root.np-t) * root.under;
visible: root.np-t > 0.001;
}
// ---- text input ----
in property <bool> input-open;
in property <string> input-title <=> input.title;
in property <string> input-subtitle <=> input.subtitle;
in property <string> input-placeholder <=> input.placeholder;
in property <string> input-submit-label <=> input.submit-label;
in property <int> input-min-length <=> input.min-length;
in-out property <string> input-text <=> input.text;
in-out property <string> input-error <=> input.error;
callback input-submitted(string);
callback input-cancelled();
public function input-reset() {
input.reset();
}
input := InputScreen {
alpha: root.vis(root.input-t);
visible: root.input-t > 0.001;
submitted(t) => { root.input-submitted(t); }
cancelled => { root.input-cancelled(); }
}
// ---- picker ----
in property <bool> select-open;
in property <string> select-title <=> select.title;
in property <[MenuItem]> select-items <=> select.items;
in property <int> select-focus <=> select.focus-index;
select := SelectOverlay {
alpha: root.select-t;
visible: root.select-t > 0.001;
}
// ---- toast ----
in property <string> toast-text <=> toast.text;
in property <bool> toast-bad <=> toast.bad;
toast := Toast { }
// ---- glass, in drawing order (listed by src/main.rs) ----
out property <[GlassRect]> glass-signin: signin.glass;
out property <[GlassRect]> glass-page: page.glass;
out property <[GlassRect]> glass-page-keyboard: page.glass-keyboard;
out property <[GlassRect]> glass-np: np.glass;
out property <[GlassRect]> glass-input: input.glass;
out property <[GlassRect]> glass-input-keyboard: input.glass-keyboard;
out property <[GlassRect]> glass-select: select.glass;
out property <[GlassRect]> glass-toast: toast.glass;
}

37
ui/icons.slint Normal file
View File

@@ -0,0 +1,37 @@
// Icons sf-ui does not have (shuffle, repeat, heart, lyrics, queue), drawn
// the same way: strokes on a 32 grid. Any other name goes to sf-ui's Icon.
import { Tv, Icon } from "@sf-ui/sf-ui.slint";
export component SpIcon inherits Rectangle {
in property <string> name;
in property <color> ink: Tv.text;
in property <length> size: 32 * Tv.u;
width: self.size;
height: self.size;
property <bool> own: self.name == "shuffle" || self.name == "repeat" || self.name == "repeat-one" || self.name == "heart"
|| self.name == "heart-filled" || self.name == "lyrics" || self.name == "queue" || self.name == "devices";
property <bool> filled: self.name == "heart-filled";
if !root.own: Icon {
name: root.name;
ink: root.ink;
size: root.size;
}
if root.own: Path {
width: 100%;
height: 100%;
viewbox-width: 32;
viewbox-height: 32;
stroke: root.ink;
stroke-width: root.size * 2.4 / 32;
fill: root.filled ? root.ink : transparent;
commands: root.name == "shuffle" ? "M 4 9 L 9 9 C 15 9 17 23 23 23 L 28 23 M 24.5 19.5 L 28 23 L 24.5 26.5 M 4 23 L 9 23 C 11.5 23 13 21 14.5 18 M 17.5 14 C 19 11 20.5 9 23 9 L 28 9 M 24.5 5.5 L 28 9 L 24.5 12.5"
: root.name == "repeat" ? "M 6 16 L 6 12.5 C 6 10 7.5 8.5 10 8.5 L 26 8.5 M 22.5 5 L 26 8.5 L 22.5 12 M 26 16 L 26 19.5 C 26 22 24.5 23.5 22 23.5 L 6 23.5 M 9.5 27 L 6 23.5 L 9.5 20"
: root.name == "repeat-one" ? "M 6 16 L 6 12.5 C 6 10 7.5 8.5 10 8.5 L 26 8.5 M 22.5 5 L 26 8.5 L 22.5 12 M 26 16 L 26 19.5 C 26 22 24.5 23.5 22 23.5 L 6 23.5 M 9.5 27 L 6 23.5 L 9.5 20 M 14.5 14 L 16.5 12.8 L 16.5 19.5"
: root.name == "heart" || root.name == "heart-filled" ? "M 16 26.5 L 6.2 16.8 C 3.2 13.8 3.6 9 7.4 7.4 C 10.4 6.1 13.8 7.3 16 10.2 C 18.2 7.3 21.6 6.1 24.6 7.4 C 28.4 9 28.8 13.8 25.8 16.8 Z"
: root.name == "lyrics" ? "M 16 4 C 18.5 4 20.5 6 20.5 8.5 L 20.5 15 C 20.5 17.5 18.5 19.5 16 19.5 C 13.5 19.5 11.5 17.5 11.5 15 L 11.5 8.5 C 11.5 6 13.5 4 16 4 Z M 7.5 14.5 C 7.5 19.5 11.3 23.5 16 23.5 C 20.7 23.5 24.5 19.5 24.5 14.5 M 16 23.5 L 16 28 M 11 28 L 21 28"
: root.name == "queue" ? "M 5 8 L 22 8 M 5 14 L 22 14 M 5 20 L 13 20 M 18 18.5 L 18 27.5 L 26 23 Z"
: root.name == "devices" ? "M 4 7 L 22 7 L 22 20 L 4 20 Z M 9 25 L 17 25 M 25 11 L 29 11 L 29 26 L 25 26 Z"
: "";
}
}

405
ui/nowplaying.slint Normal file
View File

@@ -0,0 +1,405 @@
// Most szól: the cover, the title, the progress and the controls. With the
// lyrics or the queue open, the cover and the texts move to the left and a
// glass panel holds the lyrics / the queue on the right.
//
// Rust owns the focus: `button` is the focused button (0..7), `area` 1 means
// the progress bar (left/right seek there).
import { Tv, GlassRect, GlassPane, Spinner, Caption } from "@sf-ui/sf-ui.slint";
import { QueueItem } from "types.slint";
import { SpIcon } from "icons.slint";
import { Accent, Equalizer } from "page.slint";
// A round glass control. `on`: a toggle that is on (green icon and dot).
component NpButton inherits Rectangle {
in property <string> icon;
in property <bool> focused;
in property <bool> on;
in property <bool> primary;
in property <float> alpha: 1;
in property <length> size: 80 * Tv.u;
out property <float> f: self.focused ? 1 : 0;
animate f { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <float> s: 1 + 0.08 * self.f;
width: self.size;
height: self.size;
SpIcon {
name: root.icon;
size: root.size * (root.primary ? 0.46 : 0.42);
ink: root.focused ? Tv.ink : root.primary ? #121317 : root.on ? Accent.green : Tv.text;
opacity: root.alpha;
}
if root.on: Rectangle {
x: (parent.width - self.width) / 2;
y: parent.height - 14 * Tv.u;
width: 7 * Tv.u;
height: 7 * Tv.u;
border-radius: self.width / 2;
background: root.focused ? Tv.ink : Accent.green;
opacity: root.alpha;
}
out property <GlassRect> glass: {
x: self.absolute-position.x - self.width * (self.s - 1) / 2,
y: self.absolute-position.y - self.height * (self.s - 1) / 2,
w: self.width * self.s,
h: self.height * self.s,
r: self.height * self.s / 2,
focus: self.f,
alpha: self.alpha,
blur: 1.4,
glow: self.primary ? Accent.green : #ffffff,
tint: self.primary ? (self.focused ? #ffffff.with-alpha(0.9) : Accent.green.with-alpha(0.92)) : #ffffff.with-alpha(0.06 + 0.82 * self.f),
group: 0,
};
}
export component NowPlayingScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> title;
in property <string> artist;
in property <string> album;
in property <image> art;
in property <bool> explicit;
in property <bool> episode;
in property <bool> playing;
in property <bool> loading;
in property <float> progress;
in property <string> time;
in property <string> duration;
in property <bool> shuffle;
// 0 off, 1 the list, 2 this track
in property <int> repeat;
// -1 unknown, 0 no, 1 yes
in property <int> liked: -1;
in property <int> button: 2;
in property <int> area;
// 0 none, 1 lyrics, 2 queue
in property <int> panel;
in property <[string]> lyrics;
in property <int> lyric-line: -1;
in property <bool> lyrics-synced;
in property <string> lyrics-note;
in property <[QueueItem]> queue;
in property <string> queue-note;
in property <string> device;
// 0: the big layout, 1: side by side with the panel.
out property <float> t: self.panel != 0 ? 1 : 0;
animate t { duration: 520ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
pure function mix(a: float, b: float) -> length {
(a + (b - a) * root.t) * Tv.u
}
// ---- cover ----
property <length> cover-size: root.mix(600, 360);
Rectangle {
x: root.mix(170, 120);
y: root.mix(190, 120);
width: root.cover-size;
height: root.cover-size;
opacity: root.alpha;
Rectangle {
border-radius: 20 * Tv.u;
background: #1b1d24;
drop-shadow-blur: 60 * Tv.u;
drop-shadow-offset-y: 24 * Tv.u;
drop-shadow-color: #000000b0;
}
Rectangle {
border-radius: 20 * Tv.u;
clip: true;
Image {
width: 100%;
height: 100%;
source: root.art;
image-fit: cover;
}
if root.loading: Rectangle {
background: #00000080;
Spinner { size: 72 * Tv.u; }
}
}
}
// ---- texts ----
property <length> tx: root.mix(870, 120);
property <length> tw: root.mix(900, 620);
property <length> ty: root.mix(220, 520);
HorizontalLayout {
x: root.tx;
y: root.ty;
width: root.tw;
height: 36 * Tv.u;
spacing: 12 * Tv.u;
alignment: start;
opacity: root.alpha;
Equalizer {
y: (parent.height - self.height) / 2;
size: 22 * Tv.u;
moving: root.playing;
}
Text {
vertical-alignment: center;
text: root.device;
font-size: 22 * Tv.u;
font-weight: 600;
color: Accent.green;
overflow: elide;
}
}
title-text := Text {
x: root.tx;
y: root.ty + root.mix(52, 44);
width: root.tw;
height: min(self.preferred-height, root.mix(170, 64));
vertical-alignment: top;
text: root.title;
font-size: root.panel != 0 ? 40 * Tv.u : (root.title.character-count > 30 ? 52 : 68) * Tv.u;
font-weight: 700;
letter-spacing: -1.5 * Tv.u;
color: Tv.text;
wrap: root.panel != 0 ? no-wrap : word-wrap;
overflow: elide;
opacity: root.alpha;
}
HorizontalLayout {
x: root.tx;
y: title-text.y + title-text.height + 10 * Tv.u;
width: root.tw;
height: 44 * Tv.u;
spacing: 12 * Tv.u;
alignment: start;
opacity: root.alpha;
if root.explicit: Rectangle {
y: (parent.height - self.height) / 2;
width: 28 * Tv.u;
height: 28 * Tv.u;
border-radius: 5 * Tv.u;
background: #ffffffb0;
Text {
text: "E";
font-size: 18 * Tv.u;
font-weight: 700;
color: #121317;
}
}
Text {
vertical-alignment: center;
text: root.artist;
font-size: root.mix(34, 28);
font-weight: 600;
color: Tv.text-secondary;
overflow: elide;
}
}
Text {
x: root.tx;
y: title-text.y + title-text.height + 58 * Tv.u;
width: root.tw;
text: root.album;
font-size: 24 * Tv.u;
color: Tv.text-tertiary;
overflow: elide;
opacity: root.alpha;
}
// ---- progress ----
property <length> py: root.ty + root.mix(400, 236);
property <float> pf: root.area == 1 ? 1 : 0;
animate pf { duration: 200ms; easing: ease-out; }
property <length> rail-h: (8 + 6 * self.pf) * Tv.u;
rail := Rectangle {
x: root.tx;
y: root.py - root.rail-h / 2;
width: root.tw;
height: root.rail-h;
opacity: root.alpha;
Rectangle {
x: 0;
width: parent.width * clamp(root.progress, 0, 1);
border-radius: parent.height / 2;
background: root.pf > 0.5 ? Accent.green : #ffffff;
}
if root.area == 1: Rectangle {
x: parent.width * clamp(root.progress, 0, 1) - self.width / 2;
y: (parent.height - self.height) / 2;
width: 28 * Tv.u;
height: 28 * Tv.u;
border-radius: self.width / 2;
background: #ffffff;
drop-shadow-blur: 10 * Tv.u;
drop-shadow-color: #00000080;
}
}
Text {
x: root.tx;
y: root.py + 22 * Tv.u;
text: root.time;
font-size: 22 * Tv.u;
font-weight: 600;
color: Tv.text-secondary;
opacity: root.alpha;
}
Text {
x: root.tx;
y: root.py + 22 * Tv.u;
width: root.tw;
horizontal-alignment: right;
text: root.area == 1 ? "◀ ▶ tekerés" : root.duration;
font-size: 22 * Tv.u;
font-weight: 600;
color: root.area == 1 ? Accent.green : Tv.text-secondary;
opacity: root.alpha;
}
// ---- buttons ----
property <length> bs: root.mix(80, 64);
property <length> gap: root.mix(22, 12);
controls := HorizontalLayout {
x: root.tx;
y: root.py + root.mix(90, 76);
height: root.bs * 1.25;
spacing: root.gap;
alignment: start;
b0 := NpButton { y: (parent.height - self.height) / 2; icon: "shuffle"; size: root.bs; on: root.shuffle; focused: root.area == 0 && root.button == 0; alpha: root.alpha * (root.episode ? 0.4 : 1); }
b1 := NpButton { y: (parent.height - self.height) / 2; icon: "previous"; size: root.bs; focused: root.area == 0 && root.button == 1; alpha: root.alpha; }
b2 := NpButton { y: (parent.height - self.height) / 2; icon: root.playing ? "pause" : "play"; size: root.bs * 1.25; primary: true; focused: root.area == 0 && root.button == 2; alpha: root.alpha; }
b3 := NpButton { y: (parent.height - self.height) / 2; icon: "next"; size: root.bs; focused: root.area == 0 && root.button == 3; alpha: root.alpha; }
b4 := NpButton { y: (parent.height - self.height) / 2; icon: root.repeat == 2 ? "repeat-one" : "repeat"; size: root.bs; on: root.repeat > 0; focused: root.area == 0 && root.button == 4; alpha: root.alpha; }
Rectangle { width: root.mix(24, 6); }
b5 := NpButton { y: (parent.height - self.height) / 2; icon: root.liked == 1 ? "heart-filled" : "heart"; size: root.bs; on: root.liked == 1; focused: root.area == 0 && root.button == 5; alpha: root.alpha * (root.liked < 0 ? 0.4 : 1); }
b6 := NpButton { y: (parent.height - self.height) / 2; icon: "lyrics"; size: root.bs; on: root.panel == 1; focused: root.area == 0 && root.button == 6; alpha: root.alpha; }
b7 := NpButton { y: (parent.height - self.height) / 2; icon: "queue"; size: root.bs; on: root.panel == 2; focused: root.area == 0 && root.button == 7; alpha: root.alpha; }
}
property <[string]> hints: ["Keverés", "Előző", root.playing ? "Szünet" : "Lejátszás", "Következő", "Ismétlés", "Kedvelés", "Dalszöveg", "Lejátszási sor"];
Caption {
x: root.tx;
y: controls.y + controls.height + 18 * Tv.u;
width: root.tw;
text: root.area == 0 ? root.hints[root.button] : "";
opacity: root.alpha;
}
// ---- the panel: lyrics or the queue ----
property <float> pa: root.alpha * clamp(root.t * 1.6 - 0.6, 0, 1);
panel-pane := GlassPane {
x: 820 * Tv.u;
y: 90 * Tv.u;
width: 1000 * Tv.u;
height: 900 * Tv.u;
radius: 48 * Tv.u;
frost: 3.2;
tint: Tv.smoke.with-alpha(0.38);
alpha: root.panel != 0 ? root.pa : 0;
visible: root.t > 0.01;
// lyrics
if root.panel == 1: Rectangle {
clip: true;
opacity: root.pa;
property <length> line-h: 76 * Tv.u;
property <length> offset: root.lyrics-synced && root.lyric-line >= 0 ? self.height * 0.38 - root.lyric-line * self.line-h : 56 * Tv.u;
animate offset { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
for l[i] in root.lyrics: Text {
x: 64 * Tv.u;
y: parent.offset + i * parent.line-h;
width: parent.width - 128 * Tv.u;
height: parent.line-h;
vertical-alignment: center;
text: l == "" ? "♪" : l;
font-size: 38 * Tv.u;
font-weight: 700;
color: !root.lyrics-synced ? Tv.text : i == root.lyric-line ? Tv.text : i < root.lyric-line ? #ffffff66 : #ffffff8c;
overflow: elide;
animate color { duration: 300ms; }
}
if root.lyrics-note != "": Text {
x: 64 * Tv.u;
width: parent.width - 128 * Tv.u;
horizontal-alignment: center;
text: root.lyrics-note;
font-size: 30 * Tv.u;
font-weight: 600;
color: Tv.text-secondary;
wrap: word-wrap;
}
}
// queue
if root.panel == 2: Rectangle {
clip: true;
opacity: root.pa;
Text {
x: 56 * Tv.u;
y: 44 * Tv.u;
text: "Következik";
font-size: 38 * Tv.u;
font-weight: 700;
color: Tv.text;
}
for q[i] in root.queue: Rectangle {
x: 56 * Tv.u;
y: (120 + i * 84) * Tv.u;
width: parent.width - 112 * Tv.u;
height: 72 * Tv.u;
Rectangle {
x: 0;
width: 64 * Tv.u;
height: 64 * Tv.u;
y: 4 * Tv.u;
border-radius: 8 * Tv.u;
clip: true;
background: #1b1d24;
Image {
width: 100%;
height: 100%;
source: q.image;
image-fit: cover;
}
}
Text {
x: 88 * Tv.u;
y: 6 * Tv.u;
width: parent.width - 88 * Tv.u;
text: q.title;
font-size: 26 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
Text {
x: 88 * Tv.u;
y: 40 * Tv.u;
width: parent.width - 88 * Tv.u;
text: q.artist;
font-size: 21 * Tv.u;
color: Tv.text-tertiary;
overflow: elide;
}
}
if root.queue-note != "": Text {
x: 56 * Tv.u;
y: 130 * Tv.u;
text: root.queue-note;
font-size: 26 * Tv.u;
color: Tv.text-secondary;
}
}
}
out property <[GlassRect]> glass: [
{
x: rail.absolute-position.x,
y: rail.absolute-position.y,
w: rail.width,
h: rail.height,
r: rail.height / 2,
focus: root.pf,
alpha: root.alpha,
blur: 1.2,
glow: Accent.green,
tint: #ffffff.with-alpha(0.14 + 0.1 * root.pf),
group: 0,
},
b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, b6.glass, b7.glass,
panel-pane.glass,
];
}

66
ui/overlays.slint Normal file
View File

@@ -0,0 +1,66 @@
// Overlays over any page: a picker (Select) and a toast. The page under them
// fades out first (Nothing-under-glass): app.slint dims it while one is open.
import { Tv, GlassRect, GlassPane, GlassMenu, MenuItem, Icon } from "@sf-ui/sf-ui.slint";
// A list to choose from, centred.
export component SelectOverlay inherits Rectangle {
in property <float> alpha;
in property <string> title;
in property <[MenuItem]> items;
in property <int> focus-index;
menu := GlassMenu {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
width: 640 * Tv.u;
title: root.title;
items: root.items;
focused-index: root.focus-index;
alpha: root.alpha;
accent: #1ed760;
visible-rows: 9;
}
out property <[GlassRect]> glass: menu.glass;
}
// A short message at the bottom ("Elmentve", errors).
export component Toast inherits Rectangle {
in property <string> text;
in property <bool> bad;
out property <float> t: self.text != "" ? 1 : 0;
animate t { duration: 300ms; easing: cubic-bezier(0.3, 1.18, 0.4, 1); }
pane := GlassPane {
x: (root.width - self.width) / 2;
y: root.height - (64 + 96 * root.t) * Tv.u;
width: min(1400 * Tv.u, label.preferred-width + 140 * Tv.u);
height: 80 * Tv.u;
radius: self.height / 2;
frost: 2.4;
tint: Tv.smoke.with-alpha(0.5);
glow: root.bad ? Tv.danger : #ffffff;
lit: 0.3;
alpha: root.t;
HorizontalLayout {
padding-left: 36 * Tv.u;
padding-right: 36 * Tv.u;
spacing: 14 * Tv.u;
alignment: center;
opacity: root.t;
Icon {
y: (parent.height - self.height) / 2;
name: root.bad ? "warning" : "check";
size: 30 * Tv.u;
ink: root.bad ? Tv.danger-ink : Tv.ok-ink;
}
label := Text {
vertical-alignment: center;
text: root.text;
font-size: 25 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
}
}
out property <[GlassRect]> glass: [pane.glass];
}

804
ui/page.slint Normal file
View File

@@ -0,0 +1,804 @@
// The page renderer (from Netflex TV): every browsing screen is a list of
// Lines built by Rust (src/page.rs), which also owns the focus and the
// scroll position. This file draws them and their glass:
// - the top navigation capsule and, right of it, "now playing",
// - hero buttons (glass at rest),
// - one focus pill that glides to the focused chip on any other line
// (on a track row it covers the whole row),
// - the search keyboard's pane.
// Everything else (cards, texts, unfocused chips) is plain Slint over the
// backdrop, so nothing Slint draws sits under glass.
import { Tv, GlassRect, GlassPane, Keyboard, Spinner, Display, Headline, Title, SectionTitle, Body, Item, Label, Caption } from "@sf-ui/sf-ui.slint";
import { Line, Chip, Card, Check } from "types.slint";
import { SpIcon } from "icons.slint";
export global Accent {
out property <color> green: #1ed760;
out property <color> deep: #1db954;
}
// The liked songs' picture: a heart on Spotify's violet gradient.
component LikedArt inherits Rectangle {
in property <length> icon-size: 72 * Tv.u;
background: @linear-gradient(135deg, #450af5 0%, #8e8ee5 100%);
SpIcon {
name: "heart-filled";
size: root.icon-size;
ink: #ffffff;
}
}
// An album, playlist, show (square) or artist (round) card.
component SpCard inherits Rectangle {
in property <Card> card;
in property <bool> focused;
in property <bool> round;
in property <length> art-h;
in property <bool> captions;
out property <float> f: self.focused ? 1 : 0;
animate f { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <length> r: self.round ? root.art-h / 2 : 14 * Tv.u;
art := Rectangle {
y: 0;
height: root.art-h;
transform-scale: 1 + 0.08 * root.f;
Rectangle {
border-radius: root.r;
background: #1b1d24;
drop-shadow-blur: (14 + 22 * root.f) * Tv.u;
drop-shadow-offset-y: (8 + 12 * root.f) * Tv.u;
drop-shadow-color: #00000090;
}
Rectangle {
border-radius: root.r;
clip: true;
if root.card.mark == "liked": LikedArt { }
if root.card.image.width == 0 && root.card.mark != "liked": Text {
x: 20 * Tv.u;
width: parent.width - 40 * Tv.u;
horizontal-alignment: center;
vertical-alignment: center;
text: root.card.title;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text-tertiary;
wrap: word-wrap;
}
Image {
width: 100%;
height: 100%;
source: root.card.image;
image-fit: cover;
}
Rectangle {
background: #000000;
opacity: 0.2 * (1 - root.f);
}
}
if root.card.current: Rectangle {
border-radius: root.r;
border-width: 4 * Tv.u;
border-color: Accent.green;
}
}
if root.captions: Text {
x: 0;
y: root.art-h + 18 * Tv.u;
width: root.width;
horizontal-alignment: root.round ? center : left;
text: root.card.caption;
font-size: 24 * Tv.u;
font-weight: 600;
color: root.focused ? Tv.text : #ffffffd0;
overflow: elide;
}
if root.captions: Text {
x: 0;
y: root.art-h + 52 * Tv.u;
width: root.width;
horizontal-alignment: root.round ? center : left;
text: root.card.detail;
font-size: 20 * Tv.u;
color: Tv.text-tertiary;
overflow: elide;
}
}
// A chip drawn by Slint. Focused chips get the page's glass pill underneath,
// hero chips are glass all the time: neither draws a background then.
component SpChip inherits Rectangle {
in property <Chip> chip;
in property <bool> focused;
in property <bool> on-glass;
property <bool> plain: root.focused || root.on-glass;
property <color> ink: root.focused && root.chip.tone != "primary" ? Tv.ink
: root.chip.tone == "danger" ? Tv.danger-ink
: root.chip.active || root.on-glass || root.chip.tone == "primary" ? Tv.text
: #ffffffd0;
x: root.chip.x * Tv.u;
y: root.chip.y * Tv.u;
width: root.chip.w * Tv.u;
height: root.chip.h * Tv.u;
opacity: root.chip.enabled ? 1 : 0.42;
Rectangle {
visible: !root.plain;
border-radius: root.chip.tone == "field" ? 22 * Tv.u : self.height / 2;
background: root.chip.tone == "field" ? #ffffff10
: root.chip.tone == "primary" ? #1ed76080
: root.chip.active ? #ffffff2c
: #ffffff12;
border-width: root.chip.tone == "field" ? 1.5 * Tv.u : 0;
border-color: #ffffff38;
}
HorizontalLayout {
padding-left: root.chip.tone == "field" ? 28 * Tv.u : root.chip.text == "" ? (root.height - 30 * Tv.u) / 2 : (root.chip.icon == "" ? 26 : 20) * Tv.u;
padding-right: root.chip.tone == "field" ? 28 * Tv.u : root.chip.text == "" ? (root.height - 30 * Tv.u) / 2 : 26 * Tv.u;
spacing: 10 * Tv.u;
alignment: root.chip.tone == "field" ? start : center;
if root.chip.icon != "": SpIcon {
y: (parent.height - self.height) / 2;
name: root.chip.icon;
size: (root.chip.text == "" ? 30 : 28) * Tv.u;
ink: root.ink;
}
if root.chip.text != "": Text {
vertical-alignment: center;
horizontal-stretch: root.chip.tone == "field" ? 1 : 0;
text: root.chip.text;
font-size: (root.chip.tone == "field" ? 26 : 23) * Tv.u;
font-weight: root.chip.active || root.focused || root.chip.tone == "primary" ? 700 : 600;
color: root.ink;
overflow: elide;
}
}
}
// Three bars that move while a track plays (track rows, the nav capsule).
export component Equalizer inherits Rectangle {
in property <color> ink: Accent.green;
in property <bool> moving: true;
in property <length> size: 24 * Tv.u;
width: self.size;
height: self.size;
// Only ticks while moving: a paused screen draws no frames.
property <duration> t: root.moving ? animation-tick() : 0ms;
for i in 3: Rectangle {
property <float> phase: root.moving ? (1 + sin((root.t / 1ms) * (0.45 + i * 0.17) * 1deg)) / 2 : 0.35;
x: i * root.size / 3 + root.size / 18;
width: root.size / 4.5;
height: root.size * (0.25 + 0.75 * self.phase);
y: root.size - self.height;
border-radius: self.width / 3;
background: root.ink;
}
}
export component LinePage inherits Rectangle {
in property <float> alpha: 1;
in property <[Line]> lines;
in property <int> focus-line: -1;
// Vertical scroll position (design px), animated here.
in property <float> scroll;
// Top navigation (main sections).
in property <bool> show-nav;
in property <[string]> nav-items;
in property <int> nav-index;
in property <bool> nav-focused;
// "Now playing" right of the nav ("" = nothing loaded).
in property <string> np-title;
in property <string> np-artist;
in property <bool> np-playing;
in property <bool> np-focused;
// The signed-in user (top right): their picture, or their initial.
in property <image> user-image;
in property <string> user-initial;
// Embedded search keyboard: its top (design px, page coordinates; < 0 = none).
in property <float> kb-y: -1;
in property <bool> kb-focused;
in property <string> kb-placeholder;
in property <string> kb-submit-label: "Keresés";
in-out property <string> query;
callback search-submitted(string);
callback search-exit-down();
callback search-exit-up();
callback search-cancelled();
public function kb-key(event: KeyEvent) -> EventResult {
kb.key(event)
}
public function kb-reset() {
kb.reset();
}
// Content left edge (design px).
property <float> cx: 96;
out property <float> scroll-anim: self.scroll;
animate scroll-anim { duration: 380ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <bool> content-focus: !self.nav-focused && !self.np-focused && !self.kb-focused;
// ---- lines ----
for line[li] in root.lines: Rectangle {
property <float> ty: line.y - root.scroll-anim;
property <bool> lf: li == root.focus-line && root.content-focus;
x: (root.cx + line.x) * Tv.u;
y: self.ty * Tv.u;
width: line.w * Tv.u;
height: line.h * Tv.u;
visible: self.ty + line.h > -40 && self.ty < 1120;
opacity: root.alpha;
// hero without a cover (big title)
if line.kind == "hero" && !line.framed: Rectangle {
if line.style != "": Text {
x: 0;
y: 12 * Tv.u;
text: line.style;
font-size: 20 * Tv.u;
font-weight: 700;
letter-spacing: 3 * Tv.u;
color: Tv.text-secondary;
}
Display {
x: 0;
y: 90 * Tv.u;
width: 1300 * Tv.u;
text: line.title;
font-size: (line.title.character-count > 24 ? 64 : 88) * Tv.u;
}
Caption {
x: 0;
y: 242 * Tv.u;
width: 1300 * Tv.u;
text: line.subtitle;
}
Label {
x: 0;
y: 274 * Tv.u;
width: 1500 * Tv.u;
text: line.meta;
color: Tv.text;
}
Body {
x: 0;
y: 316 * Tv.u;
width: 1100 * Tv.u;
height: 152 * Tv.u;
text: line.text;
font-size: 26 * Tv.u;
}
for chip[ci] in line.chips: SpChip {
chip: chip;
focused: lf && line.col == ci;
on-glass: true;
}
}
// hero with a cover: picture left, texts and buttons right
if line.kind == "hero" && line.framed: Rectangle {
Rectangle {
x: 0;
y: 20 * Tv.u;
width: 360 * Tv.u;
height: 360 * Tv.u;
border-radius: line.round ? self.width / 2 : 18 * Tv.u;
background: #1b1d24;
drop-shadow-blur: 40 * Tv.u;
drop-shadow-offset-y: 16 * Tv.u;
drop-shadow-color: #000000a0;
}
Rectangle {
x: 0;
y: 20 * Tv.u;
width: 360 * Tv.u;
height: 360 * Tv.u;
border-radius: line.round ? self.width / 2 : 18 * Tv.u;
clip: true;
if line.icon == "liked": LikedArt { icon-size: 120 * Tv.u; }
Image {
width: 100%;
height: 100%;
source: line.cover;
image-fit: cover;
}
}
property <length> tx: 420 * Tv.u;
Text {
x: parent.tx;
y: 28 * Tv.u;
text: line.style;
font-size: 20 * Tv.u;
font-weight: 700;
letter-spacing: 3 * Tv.u;
color: Tv.text-secondary;
}
Text {
x: parent.tx;
y: 58 * Tv.u;
width: parent.width - parent.tx;
height: 120 * Tv.u;
vertical-alignment: center;
text: line.title;
font-size: (line.title.character-count > 40 ? 44 : line.title.character-count > 22 ? 58 : 80) * Tv.u;
font-weight: 700;
letter-spacing: -2 * Tv.u;
color: Tv.text;
wrap: word-wrap;
overflow: elide;
}
Text {
x: parent.tx;
y: 186 * Tv.u;
width: parent.width - parent.tx;
text: line.subtitle;
font-size: 28 * Tv.u;
font-weight: 700;
color: Tv.text;
overflow: elide;
}
Label {
x: parent.tx;
y: 226 * Tv.u;
width: parent.width - parent.tx;
text: line.meta;
color: Tv.text-secondary;
overflow: elide;
}
Text {
x: parent.tx;
y: 262 * Tv.u;
width: min(parent.width - parent.tx, 1100 * Tv.u);
height: 62 * Tv.u;
text: line.text;
font-size: 22 * Tv.u;
color: Tv.text-tertiary;
wrap: word-wrap;
overflow: elide;
}
for chip[ci] in line.chips: SpChip {
chip: chip;
focused: lf && line.col == ci;
on-glass: true;
}
}
// heading
if line.kind == "heading": Rectangle {
Text {
x: 0;
y: 4 * Tv.u;
text: line.title;
font-size: (line.style == "big" ? 56 : 38) * Tv.u;
font-weight: 700;
letter-spacing: (line.style == "big" ? -1 : -0.4) * Tv.u;
color: Tv.text;
}
Caption {
x: 0;
y: (line.style == "big" ? 76 : 54) * Tv.u;
width: parent.width;
text: line.subtitle;
}
}
// text
if line.kind == "text": Text {
x: 0;
y: 0;
width: parent.width;
height: parent.height;
text: line.text;
wrap: word-wrap;
vertical-alignment: top;
font-size: (line.style == "caption" ? 22 : line.style == "label" ? 24 : 26) * Tv.u;
font-weight: line.style == "label" ? 600 : 400;
color: line.style == "warn" ? Tv.warn-ink : line.style == "bad" ? Tv.danger-ink : line.style == "good" ? Tv.ok-ink : line.style == "caption" ? Tv.text-tertiary : Tv.text-secondary;
}
// notice
if line.kind == "notice": Rectangle {
SpIcon {
x: 0;
y: 4 * Tv.u;
size: 36 * Tv.u;
name: line.icon != "" ? line.icon : line.tone == "good" ? "check" : line.tone == "info" ? "info" : "warning";
ink: line.tone == "good" ? Tv.ok-ink : line.tone == "bad" ? Tv.danger-ink : line.tone == "warn" ? Tv.warn-ink : Tv.text-secondary;
}
Item {
x: 56 * Tv.u;
y: 4 * Tv.u;
width: parent.width - 56 * Tv.u;
text: line.title;
font-size: 27 * Tv.u;
}
Text {
x: 56 * Tv.u;
y: 44 * Tv.u;
width: parent.width - 56 * Tv.u;
height: parent.height - 44 * Tv.u;
text: line.text;
wrap: word-wrap;
font-size: 23 * Tv.u;
color: Tv.text-secondary;
}
}
// chips
if line.kind == "chips": Rectangle {
if line.title != "": Text {
x: 0;
y: 0;
text: line.title;
font-size: 22 * Tv.u;
font-weight: 600;
letter-spacing: 1 * Tv.u;
color: Tv.text-tertiary;
}
for chip[ci] in line.chips: SpChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// item
if line.kind == "item": Rectangle {
Text {
x: 0;
y: 6 * Tv.u;
width: parent.width;
text: line.title;
font-size: 26 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
Text {
x: 0;
y: 42 * Tv.u;
width: parent.width;
text: line.meta;
font-size: 21 * Tv.u;
font-weight: 500;
color: Tv.text-tertiary;
overflow: elide;
}
Text {
x: 0;
y: 74 * Tv.u;
width: min(parent.width, 1100 * Tv.u);
height: 58 * Tv.u;
text: line.text;
font-size: 21 * Tv.u;
color: Tv.text-secondary;
wrap: word-wrap;
overflow: elide;
}
for chip[ci] in line.chips: SpChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// track row
if line.kind == "track": Rectangle {
property <bool> f0: lf && line.col == 0;
property <bool> playing: line.tone == "playing";
property <length> body-w: parent.width - 96 * Tv.u;
property <color> ink: self.f0 ? Tv.ink : self.playing ? Accent.green : line.tone == "dim" ? Tv.text-tertiary : Tv.text;
if line.note != "" && line.tone != "playing": Text {
x: 8 * Tv.u;
width: 64 * Tv.u;
height: parent.height;
horizontal-alignment: center;
vertical-alignment: center;
text: line.note;
font-size: 24 * Tv.u;
font-weight: 600;
color: parent.f0 ? Tv.ink : Tv.text-tertiary;
}
if line.note != "" && line.tone == "playing": Equalizer {
x: 28 * Tv.u;
y: (parent.height - self.height) / 2;
ink: parent.f0 ? Tv.ink : Accent.green;
}
if line.note == "": Rectangle {
x: 10 * Tv.u;
y: 8 * Tv.u;
width: 64 * Tv.u;
height: 64 * Tv.u;
border-radius: 8 * Tv.u;
clip: true;
background: #1b1d24;
Image {
width: 100%;
height: 100%;
source: line.image;
image-fit: cover;
}
}
Text {
x: 96 * Tv.u;
y: 10 * Tv.u;
width: parent.body-w - 96 * Tv.u - 130 * Tv.u;
text: line.title;
font-size: 26 * Tv.u;
font-weight: 600;
color: parent.ink;
overflow: elide;
}
Text {
x: 96 * Tv.u;
y: 44 * Tv.u;
width: parent.body-w - 96 * Tv.u - 130 * Tv.u;
text: line.meta;
font-size: 21 * Tv.u;
font-weight: 500;
color: parent.f0 ? #121317b0 : Tv.text-tertiary;
overflow: elide;
}
Text {
x: parent.body-w - 130 * Tv.u;
width: 100 * Tv.u;
height: parent.height;
horizontal-alignment: right;
vertical-alignment: center;
text: line.extra;
font-size: 22 * Tv.u;
font-weight: 500;
color: parent.f0 ? Tv.ink : Tv.text-tertiary;
}
if line.chips.length > 1: SpChip {
chip: line.chips[1];
focused: lf && line.col == 1;
}
}
// cards
if line.kind == "cards": Rectangle {
property <float> cw: line.style == "landscape" ? 400 : 216;
property <float> ch: line.style == "landscape" ? 225 : 216;
property <float> step: self.cw + 32;
property <float> head: line.title != "" ? 56 : 0;
property <int> fit: floor((line.w + 32) / self.step);
property <float> scroll-to: clamp(line.col - 1, 0, max(0, line.cards.length - self.fit));
property <float> sc: self.scroll-to;
animate sc { duration: 320ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
if line.title != "": Text {
x: 0;
y: 0;
text: line.title;
font-size: 32 * Tv.u;
font-weight: 700;
color: lf ? Tv.text : #ffffffc8;
}
for card[ci] in line.cards: SpCard {
x: (ci - parent.sc) * parent.step * Tv.u;
y: parent.head * Tv.u;
width: parent.cw * Tv.u;
height: (parent.ch + (line.captions ? 80 : 0)) * Tv.u;
art-h: parent.ch * Tv.u;
round: line.style == "round";
visible: ci >= parent.sc - 2 && ci < parent.sc + parent.fit + 2;
card: card;
captions: line.captions;
focused: lf && line.col == ci;
}
}
}
// ---- embedded keyboard (search) ----
kb-pane := GlassPane {
x: (root.width - self.width) / 2;
y: (root.kb-y - root.scroll-anim) * Tv.u;
width: 1720 * Tv.u;
height: 508 * Tv.u;
radius: 48 * Tv.u;
frost: 3.4;
tint: Tv.smoke.with-alpha(0.44);
alpha: root.kb-y >= 0 ? root.alpha : 0;
visible: root.kb-y >= 0;
kb := Keyboard {
x: 0;
y: 40 * Tv.u;
width: parent.width;
compact: true;
placeholder: root.kb-placeholder;
submit-label: root.kb-submit-label;
min-length: 2;
max-length: 60;
active: root.kb-focused;
alpha: root.kb-y >= 0 ? root.alpha : 0;
text <=> root.query;
submitted(t) => { root.search-submitted(t); }
cancelled => { root.search-cancelled(); }
exit-down => { root.search-exit-down(); }
exit-up => { root.search-exit-up(); }
}
}
// ---- top navigation ----
property <length> tab-w: 190 * Tv.u;
property <float> nav-a: root.show-nav ? root.alpha * (root.nav-focused || root.np-focused ? 1 : clamp(1 - root.scroll-anim / 120, 0, 1)) : 0;
nav := GlassPane {
x: (root.width - self.width) / 2;
y: 40 * Tv.u;
width: root.nav-items.length * root.tab-w + 16 * Tv.u;
height: 80 * Tv.u;
radius: self.height / 2;
frost: 1.6;
tint: #ffffff0a;
alpha: root.nav-a;
visible: root.show-nav;
for t[i] in root.nav-items: Text {
x: 8 * Tv.u + i * root.tab-w;
width: root.tab-w;
height: parent.height;
horizontal-alignment: center;
vertical-alignment: center;
text: t;
font-size: 25 * Tv.u;
font-weight: 600;
color: i == root.nav-index ? (root.nav-focused ? Tv.ink : Tv.text) : Tv.text-secondary;
opacity: root.nav-a;
}
}
// ---- now playing capsule ----
property <bool> np-on: root.show-nav && root.np-title != "";
out property <float> np-t: self.np-focused ? 1 : 0;
animate np-t { duration: 220ms; easing: ease-out; }
np := Rectangle {
x: nav.x + nav.width + 24 * Tv.u;
y: nav.y + 4 * Tv.u;
width: max(0, min(460 * Tv.u, np-text.preferred-width + 100 * Tv.u, avatar.x - 24 * Tv.u - self.x));
height: 72 * Tv.u;
visible: root.np-on;
opacity: root.nav-a;
Equalizer {
x: 24 * Tv.u;
y: (parent.height - self.height) / 2;
moving: root.np-playing;
ink: root.np-focused ? Tv.ink : Accent.green;
}
np-text := VerticalLayout {
x: 64 * Tv.u;
width: parent.width - 88 * Tv.u;
alignment: center;
Text {
text: root.np-title;
font-size: 22 * Tv.u;
font-weight: 700;
color: root.np-focused ? Tv.ink : Tv.text;
overflow: elide;
}
Text {
text: root.np-artist;
font-size: 19 * Tv.u;
font-weight: 500;
color: root.np-focused ? #121317b0 : Tv.text-secondary;
overflow: elide;
}
}
}
// ---- the signed-in user ----
avatar := Rectangle {
x: root.width - Tv.safe-x - self.width;
y: 44 * Tv.u;
width: 72 * Tv.u;
height: 72 * Tv.u;
visible: root.show-nav && (root.user-initial != "" || root.user-image.width > 0);
opacity: root.nav-a;
Rectangle {
border-radius: self.width / 2;
background: #ffffff26;
drop-shadow-blur: 16 * Tv.u;
drop-shadow-offset-y: 6 * Tv.u;
drop-shadow-color: #00000070;
}
Rectangle {
border-radius: self.width / 2;
clip: true;
if root.user-image.width == 0: Text {
text: root.user-initial;
font-size: 32 * Tv.u;
font-weight: 700;
color: Tv.text;
}
Image {
width: 100%;
height: 100%;
source: root.user-image;
image-fit: cover;
}
}
}
out property <float> tab-pos: self.nav-index;
animate tab-pos { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> nav-t: self.nav-focused ? 1 : 0;
animate nav-t { duration: 220ms; easing: ease-out; }
// ---- glass ----
property <Line> fl: root.focus-line >= 0 && root.focus-line < root.lines.length ? root.lines[root.focus-line] : root.lines[0];
property <Chip> fc: root.fl.chips[max(0, root.fl.col)];
property <bool> pill-on: root.content-focus && root.focus-line >= 0 && root.fl.kind != "hero" && root.fl.kind != "cards" && root.fc.w > 0;
out property <float> pill-x: root.cx + root.fl.x + root.fc.x;
animate pill-x { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-w: root.fc.w;
animate pill-w { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-y: root.fl.y + root.fc.y;
animate pill-y { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-h: root.fc.h;
animate pill-h { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-a: root.pill-on ? 1 : 0;
animate pill-a { duration: 160ms; easing: ease-out; }
property <Line> hero: root.lines.length > 0 && root.lines[0].kind == "hero" ? root.lines[0] : root.fl;
property <bool> has-hero: root.lines.length > 0 && root.lines[0].kind == "hero";
pure function hero-rect(i: int) -> GlassRect {
let c = root.hero.chips[i];
let f = root.has-hero && root.focus-line == 0 && root.content-focus && root.hero.col == i ? 1 : 0;
let s = 1 + 0.05 * f;
{
x: (root.cx + root.hero.x + c.x) * Tv.u - c.w * Tv.u * (s - 1) / 2,
y: (root.hero.y + c.y - root.scroll-anim) * Tv.u - c.h * Tv.u * (s - 1) / 2,
w: c.w * Tv.u * s,
h: c.h * Tv.u * s,
r: c.h * Tv.u * s / 2,
focus: f,
alpha: root.has-hero && c.w > 0 && i < root.hero.chips.length ? root.alpha * (c.enabled ? 1 : 0.5) : 0,
blur: 1.4,
glow: c.tone == "primary" ? Accent.green : #ffffff,
tint: c.tone == "primary" ? Accent.deep.with-alpha(0.5 + 0.4 * f) : #ffffff.with-alpha((c.active ? 0.16 : 0.07) + 0.8 * f),
group: 0,
}
}
out property <[GlassRect]> glass: [
nav.glass,
{
x: nav.absolute-position.x + 8 * Tv.u + root.tab-pos * root.tab-w,
y: nav.absolute-position.y + 8 * Tv.u,
w: root.tab-w,
h: nav.height - 16 * Tv.u,
r: (nav.height - 16 * Tv.u) / 2,
focus: root.nav-t,
alpha: root.nav-a,
blur: -1,
glow: #ffffff,
tint: #ffffff.with-alpha(0.12 + 0.76 * root.nav-t),
group: 0,
},
{
x: np.absolute-position.x,
y: np.absolute-position.y,
w: np.width,
h: np.height,
r: np.height / 2,
focus: root.np-t,
alpha: root.np-on ? root.nav-a : 0,
blur: 1.6,
glow: Accent.green,
tint: #ffffff.with-alpha(0.06 + 0.82 * root.np-t),
group: 0,
},
root.hero-rect(0),
root.hero-rect(1),
root.hero-rect(2),
root.hero-rect(3),
{
x: root.pill-x * Tv.u,
y: (root.pill-y - root.scroll-anim) * Tv.u,
w: root.pill-w * Tv.u,
h: root.pill-h * Tv.u,
r: root.fc.tone == "field" ? 22 * Tv.u : root.pill-h * Tv.u / 2,
focus: 1,
alpha: root.alpha * root.pill-a,
blur: 1.2,
glow: root.fc.tone == "primary" ? Accent.green : #ffffff,
tint: root.fc.tone == "primary" ? Accent.deep.with-alpha(0.85) : #ffffff.with-alpha(root.fc.tone == "field" ? 0.82 : 0.88),
group: 0,
},
kb-pane.glass,
];
out property <[GlassRect]> glass-keyboard: kb.glass;
}

244
ui/signin.slint Normal file
View File

@@ -0,0 +1,244 @@
// Sign-in from the phone (Spotify Connect), the text input overlay (on a
// modal glass pane with the on-screen keyboard) and a plain message screen.
import { Tv, GlassRect, GlassPane, Keyboard, Spinner, Display, Title, Body, Label, Caption, Icon } from "@sf-ui/sf-ui.slint";
import { SpIcon } from "icons.slint";
// Sign-in, two ways: a pairing code (QR code or spotify.com/pair) or this
// TV picked in the Spotify app on the phone (Spotify Connect).
export component ConnectScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> device;
in property <string> code;
in property <image> qr;
in property <bool> busy;
in property <string> error;
pane := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 20 * Tv.u;
width: 1640 * Tv.u;
height: 760 * Tv.u;
radius: 56 * Tv.u;
frost: 3.6;
tint: Tv.smoke.with-alpha(0.46);
glow: #1ed760;
alpha: root.alpha;
// ---- left: title and the two ways ----
VerticalLayout {
x: 80 * Tv.u;
y: 72 * Tv.u;
width: 860 * Tv.u;
height: parent.height - 144 * Tv.u;
spacing: 18 * Tv.u;
opacity: root.alpha;
HorizontalLayout {
spacing: 24 * Tv.u;
alignment: start;
Rectangle {
width: 80 * Tv.u;
height: 80 * Tv.u;
border-radius: self.width / 2;
background: #1ed760;
SpIcon {
name: "audio";
size: 44 * Tv.u;
ink: #121317;
}
}
VerticalLayout {
alignment: center;
Title { text: "Jelentkezz be a telefonoddal"; }
Caption { text: "Spotify Premium fiók kell hozzá"; }
}
}
Rectangle { height: 14 * Tv.u; }
Text {
text: "QR-KÓDDAL";
font-size: 20 * Tv.u;
font-weight: 700;
letter-spacing: 3 * Tv.u;
color: #1ed760;
}
Body {
text: "Olvasd be a kódot a telefon kamerájával, és jelentkezz be. Vagy nyisd meg a spotify.com/pair oldalt, és írd be a kódot.";
font-size: 26 * Tv.u;
color: Tv.text;
}
Rectangle { height: 10 * Tv.u; }
Text {
text: "A SPOTIFY APPBÓL";
font-size: 20 * Tv.u;
font-weight: 700;
letter-spacing: 3 * Tv.u;
color: #1ed760;
}
Body {
text: "Ha a telefon ugyanazon a Wi-Fin van: indíts el egy számot, koppints az eszközök ikonjára, és válaszd: „" + root.device + "”.";
font-size: 26 * Tv.u;
color: Tv.text;
}
Rectangle { }
HorizontalLayout {
spacing: 16 * Tv.u;
alignment: start;
height: 48 * Tv.u;
Spinner { size: 40 * Tv.u; }
Label {
vertical-alignment: center;
text: root.busy ? "Bejelentkezés…" : root.error != "" ? root.error : "Várakozás a telefonra…";
color: root.error != "" && !root.busy ? Tv.warn-ink : Tv.text-secondary;
wrap: word-wrap;
}
}
}
// ---- right: the QR code and the code ----
qr-box := Rectangle {
x: parent.width - self.width - 96 * Tv.u;
y: 80 * Tv.u;
width: 440 * Tv.u;
height: 440 * Tv.u;
border-radius: 28 * Tv.u;
background: #ffffff;
opacity: root.alpha;
clip: true;
if root.qr.width > 0: Image {
x: 20 * Tv.u;
y: 20 * Tv.u;
width: parent.width - 40 * Tv.u;
height: parent.height - 40 * Tv.u;
source: root.qr;
image-rendering: pixelated;
}
if root.qr.width == 0: Spinner {
size: 64 * Tv.u;
ink: #121317;
}
}
Text {
x: qr-box.x;
y: qr-box.y + qr-box.height + 28 * Tv.u;
width: qr-box.width;
horizontal-alignment: center;
text: "spotify.com/pair";
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text-secondary;
opacity: root.alpha;
}
Text {
x: qr-box.x;
y: qr-box.y + qr-box.height + 66 * Tv.u;
width: qr-box.width;
horizontal-alignment: center;
text: root.code;
font-size: 64 * Tv.u;
font-weight: 700;
letter-spacing: 10 * Tv.u;
color: Tv.text;
opacity: root.alpha;
}
}
Caption {
x: pane.x;
y: pane.y + pane.height + 28 * Tv.u;
width: pane.width;
horizontal-alignment: center;
text: "Vissza: kilépés";
opacity: root.alpha;
}
out property <[GlassRect]> glass: [pane.glass];
}
// A text field over everything (the TV's name...).
export component InputScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> title;
in property <string> subtitle;
in property <string> placeholder;
in property <string> submit-label: "Kész";
in property <int> min-length: 1;
in-out property <string> text;
in-out property <string> error;
callback submitted(string);
callback cancelled();
public function key(event: KeyEvent) -> EventResult {
kb.key(event)
}
public function reset() {
kb.reset();
}
pane := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 24 * Tv.u;
width: 1720 * Tv.u;
height: 720 * Tv.u;
radius: 56 * Tv.u;
frost: 3.8;
tint: Tv.smoke.with-alpha(0.48);
glow: #1ed760;
alpha: root.alpha;
kb := Keyboard {
x: 0;
y: 72 * Tv.u;
width: parent.width;
title: root.title;
subtitle: root.subtitle;
placeholder: root.placeholder;
submit-label: root.submit-label;
min-length: root.min-length;
max-length: 60;
alpha: root.alpha;
active: true;
text <=> root.text;
error <=> root.error;
submitted(t) => { root.submitted(t); }
cancelled => { root.cancelled(); }
}
}
out property <[GlassRect]> glass: [pane.glass];
out property <[GlassRect]> glass-keyboard: kb.glass;
}
// Loading and errors.
export component MessageScreen inherits Rectangle {
in property <float> alpha: 1;
in property <bool> busy;
in property <string> title;
in property <string> text;
VerticalLayout {
x: Tv.safe-x;
width: root.width - 2 * Tv.safe-x;
y: 340 * Tv.u;
height: 400 * Tv.u;
spacing: 24 * Tv.u;
alignment: start;
opacity: root.alpha;
HorizontalLayout {
alignment: center;
if root.busy: Spinner { size: 72 * Tv.u; }
if !root.busy: Icon { name: "warning"; size: 64 * Tv.u; ink: Tv.warn-ink; }
}
Title {
horizontal-alignment: center;
text: root.title;
}
Label {
horizontal-alignment: center;
text: root.text;
wrap: word-wrap;
}
Caption {
horizontal-alignment: center;
text: root.busy ? "" : "Újrapróbálkozik magától. Vissza: kilépés";
}
}
}

91
ui/types.slint Normal file
View File

@@ -0,0 +1,91 @@
// Data the Rust side fills in. Every page is a list of Lines (src/page.rs);
// all lengths here are design px (1920x1080 grid), multiplied by Tv.u.
// A button / choice / text field on a line. x, y relative to the line.
export struct Chip {
id: string,
text: string,
icon: string,
x: float,
y: float,
w: float,
h: float,
// Selected (a choice, the current tab).
active: bool,
// "" | "primary" (accent glass) | "danger" | "field" (text field)
tone: string,
enabled: bool,
}
// A card in a cards line.
export struct Card {
id: string,
title: string,
// Under the card (cards lines with captions).
caption: string,
detail: string,
image: image,
// 0..1; negative = no bar.
progress: float,
badge: string,
badge-tone: string,
// "liked": the liked songs' card (a heart on a gradient).
mark: string,
big: string,
// Highlighted (plays now).
current: bool,
}
export struct Check {
state: int,
label: string,
detail: string,
}
// One line of a page.
// hero big title block with buttons; with a cover (`framed`) the
// texts sit right of a square (or round) picture
// heading section title (+ subtitle)
// text paragraph (style "body" | "caption" | "label" | "warn" | "bad" | "good")
// notice icon + title + text, toned ("good" | "bad" | "warn" | "info")
// chips a row of chips (title = label above them)
// cards a row of cards (style "square" | "round" | "landscape"; captions under them)
// item list row: optional picture, title, meta, text, chips
// track a song row: number or art, title, meta, duration, "more" chip
// checks two columns of check rows
// keyboard room for the page's on-screen keyboard
export struct Line {
id: string,
kind: string,
y: float,
h: float,
x: float,
w: float,
title: string,
subtitle: string,
meta: string,
extra: string,
text: string,
note: string,
style: string,
tone: string,
icon: string,
image: image,
logo: image,
cover: image,
round: bool,
framed: bool,
progress: float,
col: int,
captions: bool,
cards: [Card],
chips: [Chip],
checks: [Check],
}
// A row of the queue (now playing).
export struct QueueItem {
title: string,
artist: string,
image: image,
}