Initial Netflex TV app

This commit is contained in:
Tamas Csikel
2026-10-25 14:01:47 +01:00
commit 3e33ea6643
31 changed files with 17559 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
# On a tag (v1.2.3): build inside a SmartFox checkout (sf-ui lives there),
# sign, and publish a release with the three store assets.
#
# Secrets:
# SF_SIGNING_KEY base64 of key.pem on one line (base64 -w0 key.pem)
# SMARTFOX_TOKEN read access to bluefox/fox-in-the-box (it is private)
name: release
on:
push:
tags: ["v*"]
jobs:
release:
runs-on: ubuntu-latest
container:
image: debian:trixie
env:
SMARTFOX_REPO: gitea.bluefox.support/bluefox/fox-in-the-box
steps:
- name: Checkout
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq \
libfontconfig1-dev libfreetype-dev libxkbcommon-dev \
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev >/dev/null
git clone --depth 1 "https://oauth2:${{ secrets.SMARTFOX_TOKEN }}@${SMARTFOX_REPO}.git" work
git clone --depth 1 --branch "$GITHUB_REF_NAME" \
"${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" work/apps/netflex-tv
- name: Build and sign
env:
SF_SIGNING_KEY: ${{ secrets.SF_SIGNING_KEY }}
run: |
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal
export PATH="$HOME/.cargo/bin:$PATH"
cd work/apps/netflex-tv && ./package.sh
- 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" | jq -r .id)
for f in work/apps/netflex-tv/dist/*; do
curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null
done

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
/target
/pkg
/dist
key.pem

42
AGENTS.md Normal file
View File

@@ -0,0 +1,42 @@
# Notes for AI agents working on Netflex TV
Read first:
- `../../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.
## Layout
```
app.toml store manifest (id support.bluefox.netflex; permissions network, gpu, audio)
src/main.rs window, glass layer (lists every exported [GlassRect]), images, controller
src/app.rs Controller: screens (message, signin, home, detail, player), Back stack, start-up, sign-in
src/home.rs tabs (Kezdőlap, Filmek, Sorozatok, Listám, Keresés): rows, focus, lazy images, backdrop, search
src/detail.rs title page: Play/Continue/Next target, My List, seasons, episodes
src/player.rs sources -> /api/play/start -> probe -> sf_ui::video::Player; tracks, seek, OSD, progress
src/api.rs Netflex HTTP API (mirrors netflex/packages/client/src/api.ts)
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/{home,detail,player,signin}.slint, ui/types.slint
tools/mock_server.py stand-in server (real Cinemeta data, password "netflex", --video file streamed)
```
## 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 (signin, search).
- **Short borrows:** never hold `state.borrow_mut()` while calling `images.load*`; a cached picture calls back at once. Use the `Then` enum pattern: decide under the borrow, act after it.
- **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.
- **Texts are Hungarian.** Follow the Netflex web app's behaviour (resume rules, track picking: `player.rs` tests).
## Check your change
```sh
cargo test
python3 tools/mock_server.py --port 7881 &
HOME=/tmp/nfhome NETFLEX_SERVER=http://127.0.0.1:7881 SF_UI_SIZE=1920x1080 \
SF_UI_KEYS="wait wait d e v down enter wait n e t f l e x down enter wait wait wait down right enter wait wait" \
SF_UI_SNAPSHOT=/tmp/shot.png cargo run # then look at /tmp/shot.png
```
- **Signed in once:** later runs start on home, so drop the sign-in keys.
- **Playback** needs Linux (GStreamer): run the mock with `--video some.mkv`.
- **On Windows** use `127.0.0.1`, not `localhost` (the IPv6 fallback costs ~2 s).

7076
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

37
Cargo.toml Normal file
View File

@@ -0,0 +1,37 @@
[package]
name = "netflex-tv"
description = "Netflex for SmartFox: native TV client with Liquid Glass and hardware video playback"
version = "0.1.0"
edition = "2024"
# sf-ui (and Slint) are GPL-3.0 on a TV box.
license = "GPL-3.0-only"
publish = false
[dependencies]
# The SmartFox UI kit: Liquid Glass, TV components, images. This repository
# is built inside a SmartFox checkout, at apps/netflex-tv (the release CI
# clones SmartFox and puts it there). With a public sf-ui this can become
# a git dependency: sf-ui = { git = "<SmartFox repo URL>" }.
sf-ui = { path = "../../crates/sf-ui" }
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"] }
# Video playback (GStreamer) only on Linux, the TV.
[target.'cfg(target_os = "linux")'.dependencies]
sf-ui = { path = "../../crates/sf-ui", features = ["video"] }
[build-dependencies]
slint-build = "1.18"
[profile.release]
lto = "thin"
strip = true
# Not part of the SmartFox workspace: this is its own repository.
[workspace]

36
README.md Normal file
View File

@@ -0,0 +1,36 @@
# Netflex TV
Natív Netflex kliens Fennec OS-re (store app, `support.bluefox.netflex`).
- **Felület:** Rust + Slint az sf-ui Liquid Glass-ával, ugyanazzal, mint a launcher.
- **Képernyők:** kezdőlap (Folytatás és a szerver sorai), Filmek és Sorozatok műfaji sorokkal, Listám, Keresés képernyő-billentyűzettel, adatlap évadokkal és epizódokkal, lejátszás.
- **Lejátszás:** GStreamer, hardveres dekódolással (VA-API). A szerver nyers fájlját streameli (`/api/stream`, Range-kérésekkel), miközben a torrent töltődik. Az MKV minden hang- és feliratsávja választható; a hangkésés állítható és a szerveren megmarad. A haladás 15 másodpercenként mentődik, a sorozatoknál jön a következő rész.
- **Bejelentkezés:** a szerver címe, felhasználónév, jelszó; a token a `$HOME/.config/netflex/config.toml`-ban marad.
## Fejlesztés
A repó a Fennec OS checkout `apps/netflex-tv` mappájában él (az sf-ui path-függőség: `../../crates/sf-ui`).
```sh
# Mock szerver: valódi Cinemeta katalógus, jelszó: netflex
python3 tools/mock_server.py --port 7880 --video teszt.mkv
NETFLEX_SERVER=http://127.0.0.1:7880 NETFLEX_WINDOWED=1 cargo run
```
- **Windowson:** a felület fejleszthető, de videó nincs (a GStreamer csak Linuxon van bekötve).
- **Linuxon** (Debian trixie / WSL) kell még: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev gstreamer1.0-plugins-bad gstreamer1.0-libav gstreamer1.0-pipewire`.
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1920x1080 SF_UI_KEYS="wait wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (lásd `../../docs/sf-ui.md`, 11. fejezet).
## 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`) a Fennec OS checkouton belül épít, aláír, és release-t csinál a három store-fájllal.
CI secretek:
- `SF_SIGNING_KEY` = `base64 -w0 key.pem`. A `key.pem` csak helyben van: őrizd meg, és sose commitold.
- `SMARTFOX_TOKEN`: olvasási jog a `bluefox/fox-in-the-box` repóhoz.
Helyben: `SF_SIGNING_KEY_FILE=key.pem ./package.sh`.
A TV-n: Store → Források → a repó címe.

24
app.toml Normal file
View File

@@ -0,0 +1,24 @@
# SmartFox store app manifest (docs/store-app-guide.md in the SmartFox repo).
id = "support.bluefox.netflex"
name = "Netflex"
# Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
version = "0.1.0"
kind = "exec"
category = "Saját streaming"
description = "Filmek és sorozatok a saját Netflex szerveredről, natívan: azonnal indul, miközben töltődik, hardveres videódekódolással."
author = "Bluefox"
license = "GPL-3.0-only"
homepage = "https://gitea.bluefox.support/fennec/netflex"
exec = ["bin/netflex-tv"]
icon = "icon.png"
accent = "#E50914"
palette = ["#ff4a3d", "#8c0b14", "#120305"]
# Signing key's public half (sf-pack keygen). Every release must be signed
# with the same key (CI secret SF_SIGNING_KEY), or TVs won't update.
public_key = "NmaJZJOe61vIokabSvkW7hl1Cp6a4NUsOw9IDtm/ZB4="
[sandbox]
# network: the Netflex server; gpu: glass and hardware video decoding;
# 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: 19 KiB

28
package.sh Executable file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Builds the three store release assets into dist/: app.toml,
# support.bluefox.netflex-<version>.tar.zst and its .sig.
#
# SF_SIGNING_KEY=<base64 of key.pem> ./package.sh (CI)
# SF_SIGNING_KEY_FILE=key.pem ./package.sh (by hand)
#
# Runs inside a SmartFox checkout (this repo at apps/netflex-tv), on Debian
# trixie or older (the TV's glibc), with the GStreamer dev packages:
# libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
set -euo pipefail
cd "$(dirname "$0")"
cargo build --release --locked
target="${CARGO_TARGET_DIR:-target}"
rm -rf pkg dist
mkdir -p pkg/bin
cp app.toml icon.png pkg/
install -m755 "$target/release/netflex-tv" pkg/bin/netflex-tv
# sf-pack from PATH, else the one in the SmartFox checkout around us.
if command -v sf-pack >/dev/null; then
pack=(sf-pack)
else
pack=(cargo run -q --release --manifest-path ../../Cargo.toml -p sf-pack --)
fi
"${pack[@]}" build pkg dist
"${pack[@]}" verify dist

1693
src/api.rs Normal file

File diff suppressed because it is too large Load Diff

1293
src/app.rs Normal file

File diff suppressed because it is too large Load Diff

98
src/config.rs Normal file
View File

@@ -0,0 +1,98 @@
//! What the app remembers: the server and the session token. Lives in
//! `$HOME/.config/netflex/config.toml` (on the TV, $HOME is the app's own
//! data folder inside the sandbox).
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// The household's server, offered on the first start.
pub const DEFAULT_SERVER: &str = "https://netflex.furbidden.cloud";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub server: String,
#[serde(default)]
pub token: String,
#[serde(default)]
pub username: String,
}
fn path() -> PathBuf {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("APPDATA"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".config").join("netflex").join("config.toml")
}
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 let Ok(s) = std::env::var("NETFLEX_SERVER") {
c.server = s;
}
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());
}
}
}
/// Settings of this TV only (Beállítások → Megjelenés), like the web app's
/// per-device look: `$HOME/.config/netflex/device.toml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Local {
/// "auto" | "full" | "light" | "off"
#[serde(default = "auto")]
pub glass: String,
}
fn auto() -> String {
"auto".into()
}
impl Default for Local {
fn default() -> Self {
Local { glass: auto() }
}
}
fn local_path() -> PathBuf {
path().with_file_name("device.toml")
}
impl Local {
pub fn load() -> Local {
std::fs::read_to_string(local_path()).ok().and_then(|t| toml::from_str(&t).ok()).unwrap_or_default()
}
pub fn save(&self) {
let p = local_path();
let _ = std::fs::create_dir_all(p.parent().unwrap());
if let Err(e) = std::fs::write(&p, toml::to_string(self).unwrap_or_default()) {
log::warn!("saving {}: {e:#}", p.display());
}
}
}
/// Applies the glass look ("auto" = full: the TV's GPU handles it).
pub fn apply_look(glass: &sf_ui::Glass, look: &str) {
glass.set_quality(match look {
"light" => sf_ui::Quality::Light,
"off" => sf_ui::Quality::Flat,
_ => sf_ui::Quality::Full,
});
}

572
src/detail.rs Normal file
View File

@@ -0,0 +1,572 @@
//! A title's page: facts, Play / Continue / Next, My List, seasons and
//! episodes. The title's artwork is the glass backdrop.
use std::rc::Rc;
use slint::{Model, ModelRc, VecModel};
use crate::api::{self, EpisodeInfo, MediaType, ProgressRow, SeasonSummary, TitleDetail};
use crate::app::{Action, Controller, Screen};
use crate::home::Item;
use crate::{Episode, MenuItem, format, player, task};
pub struct Detail {
item: Item,
data: Option<TitleDetail>,
progress: Vec<ProgressRow>,
listed: bool,
/// The season whose episodes are shown.
season: i32,
episodes: Vec<EpisodeInfo>,
ep_model: Rc<VecModel<Episode>>,
/// 0 = buttons, 1 = episodes, 2 = season menu.
area: i32,
button: i32,
episode: usize,
season_focus: usize,
generation: u64,
}
fn seasons_of(d: &Detail) -> &[SeasonSummary] {
d.data.as_ref().map(|t| t.seasons.as_slice()).unwrap_or(&[])
}
/// Where Play goes, its label and the resume position (web: resumeTarget).
fn target(d: &Detail) -> (Option<(i32, i32)>, String, f64) {
let resume = |p: &ProgressRow| (p.position - 3.0).max(0.0);
let unfinished = |p: &ProgressRow| !p.completed && p.position > 60.0 && p.duration.is_none_or(|dur| p.position / dur < 0.95);
if d.item.kind == MediaType::Movie {
return match d.progress.iter().find(|p| p.season == 0 && p.episode == 0) {
Some(p) if unfinished(p) => (None, "Folytatás".into(), resume(p)),
_ => (None, "Lejátszás".into(), 0.0),
};
}
let seasons = seasons_of(d);
let first = seasons.iter().map(|s| s.number).find(|n| *n > 0).unwrap_or(1);
let latest = d.progress.iter().filter(|p| p.season > 0).max_by_key(|p| (p.season, p.episode));
let Some(latest) = latest else { return (Some((first, 1)), "Lejátszás".into(), 0.0) };
let (s, e) = (latest.season, latest.episode);
if !latest.completed {
return (Some((s, e)), format!("Folytatás · {}", format::episode_code(s, e)), if unfinished(latest) { resume(latest) } else { 0.0 });
}
match next_episode(seasons, &d.episodes, d.season, s, e) {
Some((ns, ne)) => (Some((ns, ne)), format!("Következő · {}", format::episode_code(ns, ne)), 0.0),
None => (Some((s, e)), "Újra".into(), 0.0),
}
}
/// The episode after `s`/`e`: the next aired one in the season, or the
/// first of the next season. `episodes` are those of season `shown`.
fn next_episode(seasons: &[SeasonSummary], episodes: &[EpisodeInfo], shown: i32, s: i32, e: i32) -> Option<(i32, i32)> {
let today = chrono_today();
let aired = |ep: &EpisodeInfo| ep.air_date.as_deref().is_none_or(|d| d <= today.as_str());
let in_season = if shown == s && !episodes.is_empty() {
episodes.iter().any(|ep| ep.episode == e + 1 && aired(ep))
} else {
seasons.iter().find(|x| x.number == s).is_some_and(|x| e < x.aired_count.unwrap_or(x.episode_count))
};
if in_season {
return Some((s, e + 1));
}
seasons.iter().find(|x| x.number == s + 1 && x.aired_count.unwrap_or(x.episode_count) > 0).map(|x| (x.number, 1))
}
fn chrono_today() -> String {
// YYYY-MM-DD without a date crate: days since the epoch -> civil date.
let days = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() / 86400).unwrap_or(0) as i64;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
format!("{y:04}-{m:02}-{d:02}")
}
/// The season to show first: where the viewer is, else the first one.
fn current_season(d: &Detail) -> i32 {
let seasons = seasons_of(d);
let first = seasons.iter().map(|s| s.number).find(|n| *n > 0).or_else(|| seasons.first().map(|s| s.number)).unwrap_or(1);
let last = d.progress.iter().filter(|p| p.season > 0).map(|p| p.season).max();
let Some(last) = last else { return first };
let Some(s) = seasons.iter().find(|x| x.number == last) else { return first };
let watched = d.progress.iter().filter(|p| p.season == last && p.completed).count() as i32;
if watched < s.aired_count.unwrap_or(s.episode_count) {
return last;
}
seasons.iter().find(|x| x.number > last && x.aired_count.unwrap_or(x.episode_count) > 0).map(|x| x.number).unwrap_or(last)
}
pub fn open(c: &Controller, item: &Item) {
let generation = {
let mut st = c.state.borrow_mut();
let generation = st.detail.as_ref().map(|d| d.generation + 1).unwrap_or(1);
st.detail = Some(Detail {
item: item.clone(),
data: None,
progress: Vec::new(),
listed: false,
season: 1,
episodes: Vec::new(),
ep_model: Rc::new(VecModel::default()),
area: 0,
button: 0,
episode: 0,
season_focus: 0,
generation,
});
generation
};
if let Some(ui) = c.ui() {
ui.set_detail_title(item.title.clone().into());
ui.set_detail_meta(item.meta.clone().into());
ui.set_detail_overview(item.overview.clone().into());
ui.set_detail_logo(Default::default());
ui.set_detail_is_series(item.kind == MediaType::Tv);
ui.set_detail_play_label("Lejátszás".into());
ui.set_detail_listed(false);
ui.set_detail_season_label("".into());
ui.set_detail_episodes(ModelRc::from(c.state.borrow().detail.as_ref().unwrap().ep_model.clone()));
ui.set_detail_seasons(ModelRc::default());
ui.set_detail_status("".into());
ui.set_detail_busy(true);
}
sync(c);
show_backdrop(c, item);
let px = c.px();
if !item.logo.is_empty() {
let k = c.clone();
c.images.load(&item.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
if k.state.borrow().detail.as_ref().is_some_and(|d| d.generation == generation) {
if let Some(ui) = k.ui() {
ui.set_detail_logo(img);
}
}
});
}
c.push(Screen::Detail);
load(c, generation);
}
fn show_backdrop(c: &Controller, item: &Item) {
if item.backdrop.is_empty() {
c.glass.set_backdrop(None);
return;
}
let k = c.clone();
let key = item.key();
let px = c.px();
c.images.load_pixels(&item.backdrop, ((1920.0 * px) as u32, (1080.0 * px) as u32), move |pixels| {
let st = k.state.borrow();
if st.screen == Screen::Detail && st.detail.as_ref().is_some_and(|d| d.item.key() == key) {
k.glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone()).dim(0.25).fade_left(1.0).fade_bottom(0.9).align(0.6, 0.2)));
}
});
}
fn load(c: &Controller, generation: u64) {
let Some((kind, id)) = c.state.borrow().detail.as_ref().map(|d| (d.item.kind, d.item.id.clone())) else { return };
let api = c.api();
let k = c.clone();
task::spawn(
move || -> anyhow::Result<_> {
let data = api.title(kind, &id)?;
let progress = api.progress(kind, &id).unwrap_or_default();
let listed = api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).map(|s| s.listed)).unwrap_or(false);
Ok((data, progress, listed))
},
move |r| {
let ok = {
let mut st = k.state.borrow_mut();
let Some(d) = st.detail.as_mut().filter(|d| d.generation == generation) else { return };
match r {
Ok((data, progress, listed)) => {
d.data = Some(data);
d.progress = progress;
d.listed = listed;
d.season = current_season(d);
Ok(())
}
Err(e) => Err(e),
}
};
match ok {
Ok(()) => {
refresh(&k);
let series = k.state.borrow().detail.as_ref().is_some_and(|d| d.item.kind == MediaType::Tv);
if series {
load_season(&k, generation);
} else if let Some(ui) = k.ui() {
ui.set_detail_busy(false);
}
}
Err(e) if api::is_unauthenticated(&e) => k.signed_out(),
Err(e) => {
if let Some(ui) = k.ui() {
ui.set_detail_busy(false);
ui.set_detail_status(api::describe(&e).into());
}
}
}
},
);
}
fn load_season(c: &Controller, generation: u64) {
let Some((id, season)) = c.state.borrow().detail.as_ref().map(|d| (d.item.id.clone(), d.season)) else { return };
if let Some(ui) = c.ui() {
ui.set_detail_busy(true);
ui.set_detail_status("".into());
}
let api = c.api();
let k = c.clone();
task::spawn(
move || api.season(&id, season),
move |r| {
let Some(ui) = k.ui() else { return };
ui.set_detail_busy(false);
match r {
Ok(s) => {
{
let mut st = k.state.borrow_mut();
let Some(d) = st.detail.as_mut().filter(|d| d.generation == generation && d.season == season) else { return };
d.episodes = s.episodes;
d.episode = first_unwatched(d);
}
refresh(&k);
load_stills(&k);
}
Err(e) => ui.set_detail_status(api::describe(&e).into()),
}
},
);
}
fn first_unwatched(d: &Detail) -> usize {
d.episodes
.iter()
.position(|e| !d.progress.iter().any(|p| p.season == e.season && p.episode == e.episode && p.completed))
.unwrap_or(0)
}
/// Labels, the episodes model and focus, from the state.
fn refresh(c: &Controller) {
let Some(ui) = c.ui() else { return };
let st = c.state.borrow();
let Some(d) = st.detail.as_ref() else { return };
let (_, label, _) = target(d);
ui.set_detail_play_label(label.into());
ui.set_detail_listed(d.listed);
if let Some(data) = &d.data {
let extra = if d.item.kind == MediaType::Tv {
let n = data.seasons.iter().filter(|s| s.number > 0).count();
if n > 0 { format!("{n} évad") } else { String::new() }
} else {
format::runtime(data.runtime)
};
ui.set_detail_meta(format::meta(&data.summary, &extra).into());
let season = data.seasons.iter().find(|s| s.number == d.season);
ui.set_detail_season_label(season.map(|s| if s.name.is_empty() { format!("{}. évad", s.number) } else { s.name.clone() }).unwrap_or_default().into());
let items: Vec<MenuItem> = data
.seasons
.iter()
.map(|s| MenuItem {
text: if s.name.is_empty() { format!("{}. évad", s.number) } else { s.name.clone() }.into(),
detail: format!("{} rész", s.aired_count.unwrap_or(s.episode_count)).into(),
checked: s.number == d.season,
})
.collect();
ui.set_detail_seasons(ModelRc::new(VecModel::from(items)));
}
// Episodes: keep pictures already loaded.
let old: Vec<Episode> = d.ep_model.iter().collect();
let eps: Vec<Episode> = d
.episodes
.iter()
.enumerate()
.map(|(i, e)| {
let p = d.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
let watched = p.is_some_and(|p| p.completed);
let progress = match p {
Some(p) if !p.completed => p.duration.filter(|x| *x > 0.0).map(|x| (p.position / x) as f32).unwrap_or(-1.0),
_ => -1.0,
};
let mut detail = format::runtime(e.runtime);
if let Some(date) = e.air_date.as_deref().filter(|d| d.len() >= 10) {
if !detail.is_empty() {
detail.push_str(" · ");
}
detail.push_str(&date[..10].replace('-', ". "));
detail.push('.');
}
Episode {
number: e.episode,
title: e.name.clone().unwrap_or_else(|| format!("{}. rész", e.episode)).into(),
detail: detail.into(),
image: old.get(i).filter(|o| o.number == e.episode).map(|o| o.image.clone()).unwrap_or_default(),
progress,
watched,
}
})
.collect();
d.ep_model.set_vec(eps);
drop(st);
sync(c);
}
fn load_stills(c: &Controller) {
let px = c.px();
let (wants, model) = {
let st = c.state.borrow();
let Some(d) = st.detail.as_ref() else { return };
let api = &st.api;
let wants: Vec<(usize, i32, String)> = d
.episodes
.iter()
.enumerate()
.filter_map(|(i, e)| e.still.as_deref().map(|s| (i, e.episode, api.image(Some(s), false))))
.collect();
(wants, d.ep_model.clone())
};
for (i, number, url) in wants {
let model = model.clone();
c.images.load(&url, ((384.0 * px * 1.1) as u32, (216.0 * px * 1.1) as u32), move |img| {
if let Some(mut e) = model.row_data(i) {
if e.number == number {
e.image = img;
model.set_row_data(i, e);
}
}
});
}
}
/// Focus state to Slint; the overview follows the focused episode.
fn sync(c: &Controller) {
let Some(ui) = c.ui() else { return };
let st = c.state.borrow();
let Some(d) = st.detail.as_ref() else { return };
ui.set_detail_area(d.area);
ui.set_detail_button(d.button);
ui.set_detail_episode(d.episode as i32);
ui.set_detail_season_focus(d.season_focus as i32);
let overview = d.data.as_ref().and_then(|t| t.summary.overview.clone()).unwrap_or_else(|| d.item.overview.clone());
match (d.area, d.episodes.get(d.episode)) {
(1, Some(e)) => {
let name = e.name.clone().unwrap_or_default();
ui.set_detail_overview(format!("{} {}\n{}", format::episode_code(e.season, e.episode), name, e.overview.clone().unwrap_or_default()).into());
}
_ => ui.set_detail_overview(overview.into()),
}
}
/// Back from the player: progress changed.
pub fn returned(c: &Controller) {
let Some((kind, id, generation, item)) =
c.state.borrow().detail.as_ref().map(|d| (d.item.kind, d.item.id.clone(), d.generation, d.item.clone()))
else {
return;
};
show_backdrop(c, &item);
let api = c.api();
let k = c.clone();
task::spawn(
move || api.progress(kind, &id),
move |r| {
if let Ok(p) = r {
if let Some(d) = k.state.borrow_mut().detail.as_mut().filter(|d| d.generation == generation) {
d.progress = p;
}
refresh(&k);
}
},
);
}
/// The episode after `ep` of the open series, if any (for the player).
pub fn next_after(c: &Controller, ep: (i32, i32)) -> Option<(i32, i32)> {
let st = c.state.borrow();
let d = st.detail.as_ref()?;
next_episode(seasons_of(d), &d.episodes, d.season, ep.0, ep.1)
}
/// The name of an episode of the shown season, if known.
pub fn episode_name(c: &Controller, ep: (i32, i32)) -> String {
let st = c.state.borrow();
st.detail
.as_ref()
.and_then(|d| d.episodes.iter().find(|e| e.season == ep.0 && e.episode == ep.1))
.and_then(|e| e.name.clone())
.unwrap_or_default()
}
fn play(c: &Controller, ep: Option<(i32, i32)>, resume: f64) {
let req = {
let st = c.state.borrow();
let Some(d) = st.detail.as_ref() else { return };
let next = ep.and_then(|e| next_episode(seasons_of(d), &d.episodes, d.season, e.0, e.1));
player::Request {
kind: d.item.kind,
id: d.item.id.clone(),
title: d.item.title.clone(),
ep,
episode_name: String::new(),
resume,
backdrop: d.item.backdrop.clone(),
next,
}
};
let req = player::Request { episode_name: ep.map(|e| episode_name(c, e)).unwrap_or_default(), ..req };
player::play(c, req);
}
pub fn key(c: &Controller, a: Action, _repeat: bool) {
enum Then {
Sync,
Pop,
Play(Option<(i32, i32)>, f64),
ToggleList,
Season(i32),
}
let then = {
let mut st = c.state.borrow_mut();
let Some(d) = st.detail.as_mut() else { return };
let series = d.item.kind == MediaType::Tv;
let buttons = if series && d.data.is_some() { 3 } else { 2 };
match (d.area, a) {
(0, Action::Left) => {
d.button = (d.button - 1).max(0);
Then::Sync
}
(0, Action::Right) => {
d.button = (d.button + 1).min(buttons - 1);
Then::Sync
}
(0, Action::Down) if series && !d.episodes.is_empty() => {
d.area = 1;
Then::Sync
}
(0, Action::Ok | Action::PlayPause) => match d.button {
0 if d.data.is_some() || d.item.kind == MediaType::Movie => {
let (ep, _, resume) = target(d);
Then::Play(ep, resume)
}
1 => Then::ToggleList,
2 => {
let seasons = seasons_of(d);
d.season_focus = seasons.iter().position(|s| s.number == d.season).unwrap_or(0);
d.area = 2;
Then::Sync
}
_ => Then::Sync,
},
(0, Action::Back) => Then::Pop,
(1, Action::Left) => {
d.episode = d.episode.saturating_sub(1);
Then::Sync
}
(1, Action::Right) => {
d.episode = (d.episode + 1).min(d.episodes.len().saturating_sub(1));
Then::Sync
}
(1, Action::Up | Action::Back) => {
d.area = 0;
Then::Sync
}
(1, Action::Ok | Action::PlayPause) => match d.episodes.get(d.episode) {
Some(e) => {
let p = d.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
let resume = p.filter(|p| !p.completed && p.position > 60.0).map(|p| (p.position - 3.0).max(0.0)).unwrap_or(0.0);
Then::Play(Some((e.season, e.episode)), resume)
}
None => Then::Sync,
},
(2, Action::Up) => {
d.season_focus = d.season_focus.saturating_sub(1);
Then::Sync
}
(2, Action::Down) => {
d.season_focus = (d.season_focus + 1).min(seasons_of(d).len().saturating_sub(1));
Then::Sync
}
(2, Action::Ok) => match seasons_of(d).get(d.season_focus).map(|s| s.number) {
Some(n) => {
d.area = 0;
Then::Season(n)
}
None => Then::Sync,
},
(2, Action::Back | Action::Left | Action::Right) => {
d.area = 0;
Then::Sync
}
_ => Then::Sync,
}
};
match then {
Then::Sync => sync(c),
Then::Pop => {
c.pop();
}
Then::Play(ep, resume) => play(c, ep, resume),
Then::ToggleList => {
let (kind, id, on) = {
let mut st = c.state.borrow_mut();
let Some(d) = st.detail.as_mut() else { return };
d.listed = !d.listed;
(d.item.kind, d.item.id.clone(), d.listed)
};
if let Some(ui) = c.ui() {
ui.set_detail_listed(on);
}
let api = c.api();
task::background("my list", move || api.set_listed(kind, &id, on));
}
Then::Season(n) => {
let generation = {
let mut st = c.state.borrow_mut();
let Some(d) = st.detail.as_mut() else { return };
if d.season == n {
0
} else {
d.season = n;
d.episodes.clear();
d.episode = 0;
d.ep_model.set_vec(Vec::new());
d.generation
}
};
refresh(c);
if generation > 0 {
load_season(c, generation);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn season(n: i32, count: i32) -> SeasonSummary {
SeasonSummary { number: n, name: String::new(), episode_count: count, aired_count: Some(count) }
}
#[test]
fn next_episodes() {
let seasons = [season(1, 3), season(2, 2)];
assert_eq!(next_episode(&seasons, &[], 1, 1, 2), Some((1, 3)));
assert_eq!(next_episode(&seasons, &[], 1, 1, 3), Some((2, 1)));
assert_eq!(next_episode(&seasons, &[], 1, 2, 2), None);
}
#[test]
fn today_looks_like_a_date() {
let t = chrono_today();
assert_eq!(t.len(), 10);
assert!(t.starts_with("20"));
}
}

399
src/format.rs Normal file
View File

@@ -0,0 +1,399 @@
//! Texts for the screen (Hungarian), as in the Netflex web app.
use crate::api::TitleSummary;
/// 3725 -> "1:02:05", 65 -> "1:05".
pub fn time(sec: f64) -> String {
let s = if sec.is_finite() && sec > 0.0 { sec as u64 } else { 0 };
let (h, m, s) = (s / 3600, (s % 3600) / 60, s % 60);
if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
}
/// 135 -> "2 ó 15 p".
pub fn runtime(min: Option<i32>) -> String {
match min {
Some(m) if m > 0 => {
let (h, r) = (m / 60, m % 60);
match (h, r) {
(0, r) => format!("{r} p"),
(h, 0) => format!("{h} ó"),
(h, r) => format!("{h} ó {r} p"),
}
}
_ => String::new(),
}
}
pub fn episode_code(season: i32, episode: i32) -> String {
format!("S{season:02}E{episode:02}")
}
/// "Film · 2024 · IMDb 7.8 · Dráma, Krimi"
pub fn meta(t: &TitleSummary, extra: &str) -> String {
let mut parts: Vec<String> = vec![t.kind.label().to_string()];
if let Some(y) = t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())) {
parts.push(y);
}
if !extra.is_empty() {
parts.push(extra.to_string());
}
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
parts.push(format!("IMDb {r:.1}"));
}
if !t.genres.is_empty() {
parts.push(t.genres.iter().take(3).map(|g| genre(g)).collect::<Vec<_>>().join(", "));
}
parts.join(" · ")
}
/// Cinemeta's English genre names in Hungarian.
pub fn genre(g: &str) -> String {
match g {
"Action" => "Akció",
"Adventure" => "Kaland",
"Animation" => "Animáció",
"Biography" => "Életrajzi",
"Comedy" => "Vígjáték",
"Crime" => "Krimi",
"Documentary" => "Dokumentum",
"Drama" => "Dráma",
"Family" => "Családi",
"Fantasy" => "Fantasy",
"History" => "Történelmi",
"Horror" => "Horror",
"Music" => "Zenés",
"Musical" => "Musical",
"Mystery" => "Rejtély",
"Romance" => "Romantikus",
"Sci-Fi" => "Sci-fi",
"Sport" => "Sport",
"Thriller" => "Thriller",
"War" => "Háborús",
"Western" => "Western",
"Reality-TV" => "Valóságshow",
"Talk-Show" => "Talk-show",
"Game-Show" => "Vetélkedő",
"News" => "Hírek",
other => other,
}
.to_string()
}
/// ISO 639-1 / 639-2 code -> Hungarian name.
pub fn language(code: Option<&str>) -> String {
let c = code.unwrap_or("").to_lowercase();
let name = match c.as_str() {
"hu" | "hun" => "Magyar",
"en" | "eng" => "Angol",
"de" | "ger" | "deu" => "Német",
"fr" | "fre" | "fra" => "Francia",
"es" | "spa" => "Spanyol",
"it" | "ita" => "Olasz",
"ja" | "jpn" => "Japán",
"ko" | "kor" => "Koreai",
"ru" | "rus" => "Orosz",
"pl" | "pol" => "Lengyel",
"cs" | "cze" | "ces" => "Cseh",
"sk" | "slo" | "slk" => "Szlovák",
"ro" | "rum" | "ron" => "Román",
"pt" | "por" => "Portugál",
"nl" | "dut" | "nld" => "Holland",
"sv" | "swe" => "Svéd",
"da" | "dan" => "Dán",
"no" | "nor" => "Norvég",
"fi" | "fin" => "Finn",
"tr" | "tur" => "Török",
"zh" | "chi" | "zho" => "Kínai",
"hi" | "hin" => "Hindi",
"ar" | "ara" => "Arab",
"uk" | "ukr" => "Ukrán",
"hr" | "hrv" => "Horvát",
"sr" | "srp" => "Szerb",
"el" | "gre" | "ell" => "Görög",
"he" | "heb" => "Héber",
"" | "und" => "Ismeretlen",
_ => return c.to_uppercase(),
};
name.to_string()
}
/// "hun" -> "hu" (GStreamer and ffprobe tag tracks either way).
pub fn lang_code(code: Option<&str>) -> Option<String> {
let c = code?.trim().to_lowercase();
let base = c.split(['-', '_']).next().unwrap_or("").to_string();
let two = match base.as_str() {
"hun" => "hu",
"eng" => "en",
"ger" | "deu" => "de",
"fre" | "fra" => "fr",
"spa" => "es",
"ita" => "it",
"jpn" => "ja",
"kor" => "ko",
"rus" => "ru",
"pol" => "pl",
"por" => "pt",
"dut" | "nld" => "nl",
"chi" | "zho" => "zh",
"und" | "" => return None,
other if other.len() == 2 => other,
other => return Some(other.to_string()),
};
Some(two.to_string())
}
/// "5.1", "Sztereó"...
pub fn channels(n: Option<i64>) -> String {
match n {
Some(1) => "Mono".into(),
Some(2) => "Sztereó".into(),
Some(6) => "5.1".into(),
Some(8) => "7.1".into(),
Some(n) if n > 0 => format!("{n} csat."),
_ => String::new(),
}
}
/// "+300 ms", "−1200 ms", "0 ms".
pub fn delay(ms: i64) -> String {
match ms {
0 => "0 ms".into(),
m if m > 0 => format!("+{m} ms"),
m => format!("−{} ms", -m),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn texts() {
assert_eq!(time(3725.0), "1:02:05");
assert_eq!(time(65.4), "1:05");
assert_eq!(runtime(Some(135)), "2 ó 15 p");
assert_eq!(runtime(Some(60)), "1 ó");
assert_eq!(episode_code(1, 3), "S01E03");
assert_eq!(language(Some("hun")), "Magyar");
assert_eq!(language(Some("xx")), "XX");
assert_eq!(lang_code(Some("eng")).as_deref(), Some("en"));
assert_eq!(lang_code(Some("pt-BR")).as_deref(), Some("pt"));
assert_eq!(lang_code(Some("und")), None);
assert_eq!(delay(-1200), "−1200 ms");
assert_eq!(anime_score(84.0), "8,4");
assert_eq!(anime_season(Some("SPRING"), Some(2024)), "Tavasz 2024");
assert_eq!(date(Some("2024-05-01")), "2024. máj. 1.");
assert_eq!(parse_iso("1970-01-02T00:00:00Z"), Some(86400));
assert_eq!(duration(7200.0), "2 ó 0 p");
assert_eq!(plain_text("A<br>B &amp; <i>C</i>"), "A\nB & C");
assert_eq!(today().len(), 10);
}
}
/// IMDb rating with one decimal ("8.1").
pub fn rating(r: f64) -> String {
format!("{r:.1}")
}
/// AniList score 0..100 as "8,4".
pub fn anime_score(s: f64) -> String {
format!("{:.1}", s / 10.0).replace('.', ",")
}
pub fn anime_format(f: Option<&str>) -> String {
match f.unwrap_or("") {
"TV" => "TV-sorozat",
"TV_SHORT" => "Rövid sorozat",
"MOVIE" => "Film",
"SPECIAL" => "Különkiadás",
"OVA" => "OVA",
"ONA" => "ONA",
"MUSIC" => "Zenei videó",
other => return other.to_string(),
}
.to_string()
}
pub fn anime_status(s: Option<&str>) -> String {
match s.unwrap_or("") {
"RELEASING" => "Fut",
"FINISHED" => "Befejeződött",
"NOT_YET_RELEASED" => "Hamarosan",
"CANCELLED" => "Törölve",
"HIATUS" => "Szünetel",
other => return other.to_string(),
}
.to_string()
}
pub fn anime_season_name(s: &str) -> &'static str {
match s {
"WINTER" => "Tél",
"SPRING" => "Tavasz",
"SUMMER" => "Nyár",
"FALL" => "Ősz",
_ => "",
}
}
/// "Tavasz 2024"
pub fn anime_season(season: Option<&str>, year: Option<i32>) -> String {
[season.map(anime_season_name).unwrap_or("").to_string(), year.map(|y| y.to_string()).unwrap_or_default()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
pub fn anime_genre(g: &str) -> String {
match g {
"Action" => "Akció",
"Adventure" => "Kaland",
"Comedy" => "Vígjáték",
"Drama" => "Dráma",
"Ecchi" => "Ecchi",
"Fantasy" => "Fantasy",
"Horror" => "Horror",
"Mahou Shoujo" => "Varázslólány",
"Mecha" => "Mecha",
"Music" => "Zenés",
"Mystery" => "Rejtély",
"Psychological" => "Pszichológiai",
"Romance" => "Romantikus",
"Sci-Fi" => "Sci-fi",
"Slice of Life" => "Hétköznapok",
"Sports" => "Sport",
"Supernatural" => "Természetfeletti",
"Thriller" => "Thriller",
other => other,
}
.to_string()
}
/// Anime episode label ("5. rész"; 0 = prologue).
pub fn anime_episode(n: i32) -> String {
if n == 0 { "Előzmény (0. rész)".into() } else { format!("{n}. rész") }
}
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."];
const MONTHS_LONG: [&str; 12] = ["január", "február", "március", "április", "május", "június", "július", "augusztus", "szeptember", "október", "november", "december"];
/// "2024-05-01..." -> "2024. máj. 1."
pub fn date(iso: Option<&str>) -> String {
let Some(d) = iso.filter(|d| d.len() >= 10) else { return String::new() };
let (y, m, day) = (&d[0..4], d[5..7].parse::<usize>().unwrap_or(1), d[8..10].parse::<u32>().unwrap_or(1));
format!("{y}. {} {day}.", MONTHS[(m.max(1) - 1).min(11)])
}
/// "2024-11-03" -> "november 3."
pub fn date_long(iso: Option<&str>) -> String {
let Some(d) = iso.filter(|d| d.len() >= 10) else { return String::new() };
let (m, day) = (d[5..7].parse::<usize>().unwrap_or(1), d[8..10].parse::<u32>().unwrap_or(1));
format!("{} {day}.", MONTHS_LONG[(m.max(1) - 1).min(11)])
}
/// "2024-05-01T18:30:00Z" -> "2024. máj. 1. 18:30"
pub fn date_time(iso: Option<&str>) -> String {
let Some(d) = iso.filter(|d| d.len() >= 16) else { return date(iso) };
format!("{} {}", date(Some(d)), &d[11..16])
}
/// Seconds since the epoch, now.
pub fn now_secs() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// ISO 8601 -> seconds since the epoch (as UTC).
pub fn parse_iso(iso: &str) -> Option<i64> {
let n = |r: std::ops::Range<usize>| iso.get(r)?.parse::<i64>().ok();
let (y, m, d, hh, mm, ss) = (n(0..4)?, n(5..7)?, n(8..10)?, n(11..13)?, n(14..16)?, n(17..19)?);
// Days from the civil date (Howard Hinnant's algorithm).
let y2 = if m <= 2 { y - 1 } else { y };
let era = y2.div_euclid(400);
let yoe = y2 - era * 400;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
Some(days * 86400 + hh * 3600 + mm * 60 + ss)
}
/// "5 perce", "3 órája", "2 nap múlva" (as the web app's settings say it).
pub fn ago(iso: Option<&str>) -> String {
let Some(t) = iso.and_then(parse_iso) else { return "–".into() };
let s = now_secs() - t;
if s < 0 {
let f = -s;
return if f < 3600 {
format!("{} perc múlva", (f / 60).max(1))
} else if f < 172_800 {
format!("{} óra múlva", f / 3600)
} else {
format!("{} nap múlva", f / 86400)
};
}
if s < 60 {
format!("{s} mp-e")
} else if s < 3600 {
format!("{} perce", s / 60)
} else if s < 172_800 {
format!("{} órája", s / 3600)
} else {
format!("{} napja", s / 86400)
}
}
/// 7200 s -> "2 ó 0 p", 90 s -> "2 p"
pub fn duration(sec: f64) -> String {
let s = sec.max(0.0) as i64;
if s >= 86400 {
format!("{} n {} ó", s / 86400, (s % 86400) / 3600)
} else if s >= 3600 {
format!("{} ó {} p", s / 3600, (s % 3600) / 60)
} else {
format!("{} p", ((s as f64) / 60.0).round().max(1.0) as i64)
}
}
/// Today as "YYYY-MM-DD" (UTC).
pub fn today() -> String {
let days = now_secs() / 86400;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
format!("{y:04}-{m:02}-{d:02}")
}
/// AniList descriptions carry a little HTML (<br>, <i>) and entities.
pub fn plain_text(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut tag = String::new();
let mut in_tag = false;
for ch in html.chars() {
match ch {
'<' => {
in_tag = true;
tag.clear();
}
'>' if in_tag => {
in_tag = false;
if tag.trim_start_matches('/').to_lowercase().starts_with("br") {
out.push('\n');
}
}
c if in_tag => tag.push(c),
c => out.push(c),
}
}
let out = out.replace("&quot;", "\"").replace("&amp;", "&").replace("&#039;", "'").replace("&lt;", "<").replace("&gt;", ">");
let mut s = out.trim().to_string();
while s.contains("\n\n\n") {
s = s.replace("\n\n\n", "\n\n");
}
s
}

823
src/home.rs Normal file
View File

@@ -0,0 +1,823 @@
//! Home and its tabs: Kezdőlap, Filmek, Sorozatok, Listám, Keresés.
//!
//! Every tab is rows of cards under a hero that shows the focused title; its
//! artwork becomes the glass backdrop shortly after the focus settles.
//! Pictures load only around the focus.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::time::Duration;
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::api::{self, Api, MediaType, TitleSummary};
use crate::app::{Action, Controller, Screen};
use crate::{App, Card, Row, detail, format, player, task};
pub const TABS: usize = 5;
const SEARCH: usize = 4;
/// Cards per row in grids (Listám, Keresés).
const GRID: usize = 8;
/// Genre rows fetched at a time (Filmek, Sorozatok).
const GENRE_BATCH: usize = 3;
/// Where a "continue watching" card starts.
#[derive(Debug, Clone, Copy)]
pub struct Resume {
pub ep: Option<(i32, i32)>,
pub position: f64,
}
#[derive(Debug, Clone)]
pub struct Item {
pub kind: MediaType,
pub id: String,
pub title: String,
pub meta: String,
pub overview: String,
pub poster: String,
pub backdrop: String,
pub logo: String,
pub resume: Option<Resume>,
/// 0..1 watched (Folytatás), negative = no bar.
pub progress: f32,
}
impl Item {
pub fn key(&self) -> String {
format!("{}:{}", self.kind.key(), self.id)
}
fn from_summary(api: &Api, t: TitleSummary) -> Item {
Item {
kind: t.kind,
id: t.id.clone(),
title: t.title.clone(),
meta: format::meta(&t, ""),
overview: t.overview.clone().unwrap_or_default(),
poster: api.image(t.poster.as_deref(), false),
backdrop: api.image(t.backdrop.as_deref(), false),
logo: api.image(t.logo.as_deref(), false),
resume: None,
progress: -1.0,
}
}
fn card(&self) -> Card {
Card { key: self.key().into(), title: self.title.clone().into(), image: Default::default(), progress: self.progress, badge: "".into() }
}
}
/// Continuation of a row (more pages on scroll).
#[derive(Debug, Clone)]
enum More {
No,
Browse { kind: MediaType, genre: Option<String>, cursor: Option<String>, page: u32 },
}
struct RowData {
title: String,
landscape: bool,
items: Vec<Item>,
model: Rc<VecModel<Card>>,
col: usize,
requested: HashSet<usize>,
more: More,
loading_more: bool,
}
impl RowData {
fn new(title: &str, landscape: bool, items: Vec<Item>, more: More) -> RowData {
let model = Rc::new(VecModel::from(items.iter().map(Item::card).collect::<Vec<_>>()));
RowData { title: title.into(), landscape, items, model, col: 0, requested: HashSet::new(), more, loading_more: false }
}
fn slint(&self) -> Row {
Row { title: self.title.clone().into(), landscape: self.landscape, col: self.col as i32, cards: ModelRc::from(self.model.clone()) }
}
}
pub struct Home {
tab: usize,
nav: bool,
rows: Vec<RowData>,
row: usize,
model: Rc<VecModel<Row>>,
/// Bumped on every tab load: late answers for an old tab are dropped.
generation: u64,
genres: Vec<api::Genre>,
next_genre: usize,
loading_genres: bool,
/// Search tab: the keyboard has the focus.
kb: bool,
query: String,
searched: String,
search_timer: slint::Timer,
hero_timer: slint::Timer,
/// Poster colours (for the backdrop palette when a title has no artwork).
colours: Rc<RefCell<HashMap<String, slint::Color>>>,
/// The title whose artwork is the backdrop now.
backdrop_key: String,
/// Focus to put back when the reloaded rows arrive (row, column).
restore: Option<(usize, usize)>,
}
impl Default for Home {
fn default() -> Self {
Home {
tab: 0,
nav: false,
rows: Vec::new(),
row: 0,
model: Rc::new(VecModel::default()),
generation: 0,
genres: Vec::new(),
next_genre: 0,
loading_genres: false,
kb: true,
query: String::new(),
searched: String::new(),
search_timer: slint::Timer::default(),
hero_timer: slint::Timer::default(),
colours: Rc::default(),
backdrop_key: String::new(),
restore: None,
}
}
}
pub fn wire(c: &Controller, ui: &App) {
ui.set_home_rows(ModelRc::from(c.state.borrow().home.model.clone()));
let k = c.clone();
ui.on_search_submitted(move |q| search_now(&k, q.to_string()));
let k = c.clone();
ui.on_search_changed(move |q| search_soon(&k, q.to_string()));
let k = c.clone();
ui.on_search_exit_down(move || {
let has = !k.state.borrow().home.rows.is_empty();
if has {
set_kb(&k, false);
}
});
let k = c.clone();
ui.on_search_exit_up(move || {
set_kb(&k, false);
let mut st = k.state.borrow_mut();
st.home.nav = true;
drop(st);
sync(&k);
});
let k = c.clone();
ui.on_search_cancelled(move || {
k.state.borrow_mut().home.nav = true;
set_kb(&k, false);
sync(&k);
});
}
/// Shows home with `tab` (clears the Back stack: home is the root).
pub fn open(c: &Controller, tab: usize) {
c.state.borrow_mut().back.clear();
c.show(Screen::Home);
load_tab(c, tab);
}
/// Back from a details page or the player: refresh what may have changed.
pub fn returned(c: &Controller) {
let tab = c.state.borrow().home.tab;
{
c.state.borrow_mut().home.backdrop_key.clear();
}
if tab == 0 || tab == 3 {
reload_keeping_focus(c);
} else {
focus_changed(c, true);
}
}
fn set_kb(c: &Controller, on: bool) {
c.state.borrow_mut().home.kb = on;
if let Some(ui) = c.ui() {
ui.set_home_kb_focused(on);
}
focus_changed(c, false);
}
fn load_tab(c: &Controller, tab: usize) {
let (api, generation) = {
let mut st = c.state.borrow_mut();
let h = &mut st.home;
h.tab = tab;
h.generation += 1;
h.rows.clear();
h.row = 0;
h.model.set_vec(Vec::new());
h.genres.clear();
h.next_genre = 0;
h.loading_genres = false;
h.backdrop_key.clear();
if tab == SEARCH {
h.kb = true;
h.nav = false;
}
let generation = h.generation;
(st.api.clone(), generation)
};
c.images.cancel_pending();
if let Some(ui) = c.ui() {
ui.set_home_tab(tab as i32);
ui.set_home_row(0);
ui.set_home_kb_focused(tab == SEARCH);
ui.set_home_status("".into());
ui.set_home_busy(tab != SEARCH);
ui.set_home_hero_title("".into());
ui.set_home_hero_meta("".into());
ui.set_home_hero_overview("".into());
ui.set_home_hero_logo(Default::default());
if tab == SEARCH {
ui.invoke_home_kb_reset();
ui.set_home_query("".into());
}
}
if tab == SEARCH {
let mut st = c.state.borrow_mut();
st.home.query.clear();
st.home.searched.clear();
drop(st);
c.glass.set_backdrop(None);
sync(c);
return;
}
let c2 = c.clone();
match tab {
0 => task::spawn(
move || api.home().map(|h| (api.clone(), h)),
move |r| match r {
Ok((api, h)) => {
let mut rows = Vec::new();
if !h.continue_watching.is_empty() {
let items: Vec<Item> = h
.continue_watching
.into_iter()
.map(|ci| {
let mut it = Item::from_summary(&api, ci.title);
let ep = ci.season.zip(ci.episode).filter(|(s, _)| *s > 0);
if let Some((s, e)) = ep {
it.meta = format!("{} · {}", format::episode_code(s, e), it.meta);
}
// Landscape artwork: the backdrop.
it.poster = if it.backdrop.is_empty() { it.poster.clone() } else { it.backdrop.clone() };
it.resume = Some(Resume { ep, position: ci.position });
it.progress = ci.duration.filter(|d| *d > 0.0).map(|d| (ci.position / d) as f32).unwrap_or(-1.0);
it
})
.collect();
rows.push(RowData::new("Folytatás", true, items, More::No));
}
for r in h.rows {
let items = r.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
rows.push(RowData::new(&r.title, false, items, More::No));
}
set_rows(&c2, generation, rows, "");
}
Err(e) => failed(&c2, generation, e),
},
),
1 | 2 => {
let kind = if tab == 1 { MediaType::Movie } else { MediaType::Tv };
task::spawn(
move || -> anyhow::Result<_> {
let genres = api.genres(kind).unwrap_or_default();
let popular = api.browse(kind, None, None, 1)?;
let first: Vec<_> = genres.iter().take(GENRE_BATCH).map(|g| (g.clone(), api.browse(kind, Some(&g.id), None, 1))).collect();
Ok((api, genres, popular, first))
},
move |r| match r {
Ok((api, genres, popular, first)) => {
let mut rows = vec![RowData::new(
"Népszerű",
false,
popular.items.into_iter().map(|t| Item::from_summary(&api, t)).collect(),
More::Browse { kind, genre: None, cursor: popular.cursor, page: if popular.has_more { 2 } else { 0 } },
)];
for (g, page) in first {
if let Ok(p) = page {
if p.items.is_empty() {
continue;
}
rows.push(RowData::new(
&g.name,
false,
p.items.into_iter().map(|t| Item::from_summary(&api, t)).collect(),
More::Browse { kind, genre: Some(g.id.clone()), cursor: p.cursor, page: if p.has_more { 2 } else { 0 } },
));
}
}
{
let mut st = c2.state.borrow_mut();
if st.home.generation == generation {
st.home.next_genre = GENRE_BATCH.min(genres.len());
st.home.genres = genres;
}
}
set_rows(&c2, generation, rows, "");
}
Err(e) => failed(&c2, generation, e),
},
);
}
_ => task::spawn(
move || api.my_list().map(|l| (api.clone(), l)),
move |r| match r {
Ok((api, list)) => {
let items: Vec<Item> = list.into_iter().map(|l| Item::from_summary(&api, l.title)).collect();
let rows = grid_rows("Listám", items);
set_rows(&c2, generation, rows, "A listád üres. Egy film vagy sorozat adatlapján a Listám gombbal adhatsz hozzá.");
}
Err(e) => failed(&c2, generation, e),
},
),
}
}
fn grid_rows(title: &str, items: Vec<Item>) -> Vec<RowData> {
let mut rows = Vec::new();
let mut it = items.into_iter().peekable();
while it.peek().is_some() {
let chunk: Vec<Item> = it.by_ref().take(GRID).collect();
rows.push(RowData::new(if rows.is_empty() { title } else { "" }, false, chunk, More::No));
}
rows
}
fn failed(c: &Controller, generation: u64, e: anyhow::Error) {
if api::is_unauthenticated(&e) {
return c.signed_out();
}
if c.state.borrow().home.generation != generation {
return;
}
log::warn!("home: {e:#}");
if let Some(ui) = c.ui() {
ui.set_home_busy(false);
ui.set_home_status(format!("{}\nOK: újra", api::describe(&e)).into());
}
}
/// Replaces the tab's rows (when the answer is for the current tab).
fn set_rows(c: &Controller, generation: u64, rows: Vec<RowData>, empty: &str) {
{
let mut st = c.state.borrow_mut();
let h = &mut st.home;
if h.generation != generation {
return;
}
let mut rows = rows;
if let Some((row, col)) = h.restore.take() {
if !rows.is_empty() {
h.row = row.min(rows.len() - 1);
let r = &mut rows[h.row];
r.col = col.min(r.items.len().saturating_sub(1));
}
}
h.model.set_vec(rows.iter().map(RowData::slint).collect::<Vec<_>>());
h.rows = rows;
h.row = h.row.min(h.rows.len().saturating_sub(1));
}
let n = c.state.borrow().home.rows.len();
if let Some(ui) = c.ui() {
ui.set_home_busy(false);
ui.set_home_status(if n == 0 { empty.into() } else { "".into() });
}
focus_changed(c, true);
}
fn reload_keeping_focus(c: &Controller) {
let (tab, pos) = {
let st = c.state.borrow();
let h = &st.home;
(h.tab, (h.row, h.rows.get(h.row).map(|r| r.col).unwrap_or(0)))
};
load_tab(c, tab);
c.state.borrow_mut().home.restore = Some(pos);
}
// ---- search ----
fn search_soon(c: &Controller, q: String) {
let k = c.clone();
let mut st = c.state.borrow_mut();
st.home.query = q.clone();
st.home.search_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(650), move || search_now(&k, q.clone()));
}
fn search_now(c: &Controller, q: String) {
let q = q.trim().to_string();
let (api, generation) = {
let mut st = c.state.borrow_mut();
if st.home.tab != SEARCH || q.chars().count() < 2 || q == st.home.searched {
return;
}
st.home.searched = q.clone();
(st.api.clone(), st.home.generation)
};
if let Some(ui) = c.ui() {
ui.set_home_busy(true);
ui.set_home_status("".into());
}
let c2 = c.clone();
task::spawn(
move || api.search(&q).map(|p| (api.clone(), p, q)),
move |r| match r {
Ok((api, page, q)) => {
if c2.state.borrow().home.searched != q {
return;
}
let items = page.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
let rows = grid_rows("Találatok", items);
c2.state.borrow_mut().home.row = 0;
set_rows(&c2, generation, rows, "Nincs találat.");
}
Err(e) => failed(&c2, generation, e),
},
);
}
// ---- keys ----
pub fn key(c: &Controller, a: Action, _repeat: bool) {
enum Then {
Nothing,
Tab(usize),
Open(Item),
Quit,
Keyboard,
Retry,
}
let then = {
let mut st = c.state.borrow_mut();
let h = &mut st.home;
let n_rows = h.rows.len();
if h.nav {
match a {
Action::Left if h.tab > 0 => Then::Tab(h.tab - 1),
Action::Right if h.tab + 1 < TABS => Then::Tab(h.tab + 1),
Action::Down | Action::Ok => {
if h.tab == SEARCH {
h.nav = false;
Then::Keyboard
} else if n_rows > 0 {
h.nav = false;
Then::Nothing
} else if a == Action::Ok {
Then::Retry
} else {
Then::Nothing
}
}
Action::Back if h.tab != 0 => Then::Tab(0),
Action::Back => Then::Quit,
_ => Then::Nothing,
}
} else if n_rows == 0 {
match a {
Action::Up | Action::Back => {
h.nav = true;
Then::Nothing
}
Action::Ok => Then::Retry,
_ => Then::Nothing,
}
} else {
let row = &mut h.rows[h.row];
match a {
Action::Left => {
row.col = row.col.saturating_sub(1);
Then::Nothing
}
Action::Right => {
if row.col + 1 < row.items.len() {
row.col += 1;
}
Then::Nothing
}
Action::Up if h.row > 0 => {
h.row -= 1;
Then::Nothing
}
Action::Up if h.tab == SEARCH => Then::Keyboard,
Action::Up => {
h.nav = true;
Then::Nothing
}
Action::Down => {
if h.row + 1 < n_rows {
h.row += 1;
// Grids keep the column; other rows remember their own.
if h.tab >= 3 {
let col = h.rows[h.row - 1].col;
let next = &mut h.rows[h.row];
next.col = col.min(next.items.len().saturating_sub(1));
}
}
Then::Nothing
}
Action::Ok | Action::PlayPause => match row.items.get(row.col) {
Some(it) => Then::Open(it.clone()),
None => Then::Nothing,
},
Action::Back => {
if h.tab == SEARCH {
Then::Keyboard
} else {
h.nav = true;
Then::Nothing
}
}
}
}
};
match then {
Then::Nothing => focus_changed(c, false),
Then::Tab(t) => {
c.state.borrow_mut().home.nav = true;
load_tab(c, t);
}
Then::Keyboard => set_kb(c, true),
Then::Retry => {
let tab = c.state.borrow().home.tab;
load_tab(c, tab);
}
Then::Quit => {
let _ = slint::quit_event_loop();
}
Then::Open(it) => match it.resume {
// "Folytatás" plays right away, where it stopped.
Some(r) => player::play(
c,
player::Request {
kind: it.kind,
id: it.id.clone(),
title: it.title.clone(),
ep: r.ep,
episode_name: String::new(),
resume: (r.position - 3.0).max(0.0),
backdrop: it.backdrop.clone(),
next: None,
},
),
None => detail::open(c, &it),
},
}
}
// ---- focus, hero, pictures ----
/// After any focus change: Slint state, hero texts, the backdrop (soon),
/// pictures around the focus, more rows / pages when near the end.
pub fn focus_changed(c: &Controller, now: bool) {
let Some(ui) = c.ui() else { return };
let (focused, nav, kb, tab) = {
let st = c.state.borrow();
let h = &st.home;
if h.row < h.rows.len() {
// The remembered column is part of the row struct.
let r = &h.rows[h.row];
if let Some(mut row) = h.model.row_data(h.row) {
if row.col != r.col as i32 {
row.col = r.col as i32;
h.model.set_row_data(h.row, row);
}
}
}
ui.set_home_row(h.row as i32);
ui.set_home_nav_focused(h.nav);
let focused = h.rows.get(h.row).and_then(|r| r.items.get(r.col)).cloned();
(focused, h.nav, h.kb, h.tab)
};
let _ = (nav, kb);
match &focused {
Some(it) if tab != SEARCH => {
ui.set_home_hero_title(it.title.clone().into());
ui.set_home_hero_meta(it.meta.clone().into());
ui.set_home_hero_overview(it.overview.clone().into());
ui.set_home_hero_logo(Default::default());
if !it.logo.is_empty() {
let w = ui.as_weak();
let key = it.key();
let k = c.clone();
let px = c.px();
c.images.load(&it.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
let still = {
let st = k.state.borrow();
let h = &st.home;
h.rows.get(h.row).and_then(|r| r.items.get(r.col)).is_some_and(|f| f.key() == key)
};
if let (true, Some(ui)) = (still, w.upgrade()) {
ui.set_home_hero_logo(img);
}
});
}
}
_ => {}
}
schedule_backdrop(c, if now { 60 } else { 320 });
ensure_images(c);
maybe_load_more(c);
}
fn schedule_backdrop(c: &Controller, ms: u64) {
let k = c.clone();
let st = c.state.borrow();
st.home.hero_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(ms), move || apply_backdrop(&k));
}
fn apply_backdrop(c: &Controller) {
let (it, tab, colours) = {
let st = c.state.borrow();
if st.screen != Screen::Home {
return;
}
let h = &st.home;
(h.rows.get(h.row).and_then(|r| r.items.get(r.col)).cloned(), h.tab, h.colours.clone())
};
let Some(it) = it.filter(|_| tab != SEARCH) else {
c.glass.set_backdrop(None);
return;
};
let key = it.key();
{
let mut st = c.state.borrow_mut();
if st.home.backdrop_key == key {
return;
}
st.home.backdrop_key = key.clone();
}
if let Some(col) = colours.borrow().get(&key).copied() {
c.glass.set_palette(sf_ui::Palette::from_color(col));
}
if it.backdrop.is_empty() {
c.glass.set_backdrop(None);
return;
}
let k = c.clone();
let px = c.px();
c.images.load_pixels(&it.backdrop, ((1920.0 * px) as u32, (1080.0 * px) as u32), move |pixels| {
let still = k.state.borrow().home.backdrop_key == key && k.state.borrow().screen == Screen::Home;
if still {
k.glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone()).dim(0.3).fade_left(1.0).fade_bottom(1.0).align(0.6, 0.2)));
}
});
}
fn ensure_images(c: &Controller) {
let px = c.px();
struct Want {
url: String,
size: (u32, u32),
model: Rc<VecModel<Card>>,
index: usize,
key: String,
}
let (wants, colours) = {
let mut st = c.state.borrow_mut();
let h = &mut st.home;
let mut wants = Vec::new();
let lo = h.row.saturating_sub(1);
let hi = (h.row + 3).min(h.rows.len());
for row in &mut h.rows[lo..hi] {
let (cw, ch) = if row.landscape { (400.0, 225.0) } else { (196.0, 294.0) };
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
let start = row.col.saturating_sub(3);
let end = (row.col + 11).min(row.items.len());
for i in start..end {
if row.requested.insert(i) {
let it = &row.items[i];
if !it.poster.is_empty() {
wants.push(Want { url: it.poster.clone(), size, model: row.model.clone(), index: i, key: it.key() });
}
}
}
}
(wants, h.colours.clone())
};
// No state borrow here: a cached picture calls back at once.
for w in wants {
let model = w.model;
let colours = colours.clone();
let (index, key) = (w.index, w.key);
c.images.load_pixels(&w.url, w.size, move |pixels| {
if let Some(mut card) = model.row_data(index) {
if card.key.as_str() == key {
card.image = slint::Image::from_rgba8(pixels.clone());
model.set_row_data(index, card);
}
}
colours.borrow_mut().entry(key).or_insert_with(|| sf_ui::images::average_color(pixels));
});
}
}
/// More genre rows near the bottom, the next page near the end of a row.
fn maybe_load_more(c: &Controller) {
let (api, generation) = (c.api(), c.state.borrow().home.generation);
// Genre rows.
let next = {
let mut st = c.state.borrow_mut();
let h = &mut st.home;
if (h.tab == 1 || h.tab == 2) && !h.loading_genres && h.row + 3 >= h.rows.len() && h.next_genre < h.genres.len() {
h.loading_genres = true;
let batch: Vec<api::Genre> = h.genres[h.next_genre..(h.next_genre + GENRE_BATCH).min(h.genres.len())].to_vec();
h.next_genre += batch.len();
Some((if h.tab == 1 { MediaType::Movie } else { MediaType::Tv }, batch))
} else {
None
}
};
if let Some((kind, batch)) = next {
let c2 = c.clone();
let api2 = api.clone();
task::spawn(
move || batch.into_iter().map(|g| { let p = api2.browse(kind, Some(&g.id), None, 1); (g, p) }).collect::<Vec<_>>(),
move |pages| {
let mut st = c2.state.borrow_mut();
let h = &mut st.home;
if h.generation != generation {
return;
}
h.loading_genres = false;
for (g, p) in pages {
let Ok(p) = p else { continue };
if p.items.is_empty() {
continue;
}
let items = p.items.into_iter().map(|t| Item::from_summary(&api, t)).collect();
let row = RowData::new(&g.name, false, items, More::Browse { kind, genre: Some(g.id), cursor: p.cursor, page: if p.has_more { 2 } else { 0 } });
h.model.push(row.slint());
h.rows.push(row);
}
},
);
}
// Next page of the focused row.
let page = {
let mut st = c.state.borrow_mut();
let h = &mut st.home;
let ri = h.row;
match h.rows.get_mut(ri) {
Some(r) if !r.loading_more && r.col + 6 >= r.items.len() => match &r.more {
More::Browse { kind, genre, cursor, page } if *page > 0 || cursor.is_some() => {
r.loading_more = true;
Some((ri, *kind, genre.clone(), cursor.clone(), *page))
}
_ => None,
},
_ => None,
}
};
if let Some((ri, kind, genre, cursor, page)) = page {
let c2 = c.clone();
let api2 = c.api();
let g = genre.clone();
task::spawn(
move || api2.browse(kind, g.as_deref(), cursor.as_deref(), page).map(|p| (api2, p)),
move |r| {
let mut st = c2.state.borrow_mut();
let h = &mut st.home;
if h.generation != generation {
return;
}
let Some(row) = h.rows.get_mut(ri) else { return };
row.loading_more = false;
match r {
Ok((api, p)) => {
let seen: HashSet<String> = row.items.iter().map(Item::key).collect();
for t in p.items {
let it = Item::from_summary(&api, t);
if seen.contains(&it.key()) {
continue;
}
row.model.push(it.card());
row.items.push(it);
}
let next_page = if p.has_more { page + 1 } else { 0 };
row.more = More::Browse { kind, genre: genre.clone(), cursor: p.cursor, page: next_page };
}
Err(e) => {
log::warn!("more: {e:#}");
row.more = More::No;
}
}
},
);
}
}
/// Re-sends the focus state to Slint (after nav changes).
fn sync(c: &Controller) {
focus_changed(c, false);
}

62
src/main.rs Normal file
View File

@@ -0,0 +1,62 @@
//! Netflex for SmartFox: a native TV client for a Netflex server.
//!
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer.
//! - State and focus: src/app.rs and the screen modules; every remote key
//! arrives in `App::key`.
//! - Playback: sf-ui's GStreamer player (Linux), streaming the file straight
//! from the server while the torrent downloads.
// Without a player (Windows, for UI work) some playback code sits unused.
#![cfg_attr(not(target_os = "linux"), allow(dead_code, unused_imports))]
mod api;
mod app;
mod config;
mod detail;
mod format;
mod home;
mod player;
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")).init();
sf_ui::init()?;
#[cfg(target_os = "linux")]
if let Err(e) = sf_ui::video::init() {
log::error!("video: {e:#}");
}
let ui = App::new()?;
ui.sf_ui_setup();
if std::env::var_os("SF_UI_SIZE").is_none() && std::env::var_os("NETFLEX_WINDOWED").is_none() {
ui.window().set_fullscreen(true);
}
let glass = sf_ui::Glass::install(&ui, |ui, p| {
p.extend(ui.get_glass_message().iter());
p.extend(ui.get_glass_signin().iter());
p.extend(ui.get_glass_signin_keyboard().iter());
p.extend(ui.get_glass_home().iter());
p.extend(ui.get_glass_home_keyboard().iter());
p.extend(ui.get_glass_detail().iter());
p.extend(ui.get_glass_detail_menu().iter());
p.extend(ui.get_glass_player().iter());
p.extend(ui.get_glass_player_audio().iter());
p.extend(ui.get_glass_player_subs().iter());
p.extend(ui.get_glass_player_sync().iter());
})?;
glass.set_palette(sf_ui::Palette::from_hex(["#ff4a3d", "#8c0b14", "#120305"]));
let images = sf_ui::images::Images::new(384 << 20);
let app = app::Controller::new(&ui, glass, images);
app.start();
ui.run()?;
app.shutdown();
Ok(())
}

963
src/page.rs Normal file
View File

@@ -0,0 +1,963 @@
//! The page engine. Every browsing screen describes itself as a list of
//! lines (`L`): hero, headings, texts, notices, chip rows, card rows, list
//! items, checks. This module lays them out on the 1920x1080 grid, owns the
//! focus and the scroll position, loads the pictures that are about to show,
//! and hands the result to ui/page.slint.
//!
//! Navigation is generic: up/down between focusable lines (and between the
//! rows of a wrapped chip line), left/right inside a line, the top nav above
//! the first line, the settings side list left of the content.
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use slint::{Model, ModelRc, VecModel};
use crate::{Card, Check, Chip, Line};
/// Width of the content on a page without the side list (design px).
pub const CONTENT_W: f32 = 1728.0;
/// Content left edge and width with the settings side list.
pub const SIDE_X: f32 = 600.0;
pub const SIDE_W: f32 = 1224.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Hero,
Heading,
Text,
Notice,
Chips,
Cards,
Item,
Checks,
Keyboard,
Gap,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Hero => "hero",
Kind::Heading => "heading",
Kind::Text => "text",
Kind::Notice => "notice",
Kind::Chips => "chips",
Kind::Cards => "cards",
Kind::Item => "item",
Kind::Checks => "checks",
Kind::Keyboard => "keyboard",
Kind::Gap => "gap",
}
}
}
/// A chip (button, choice, text field).
#[derive(Debug, Clone, Default)]
pub struct Ch {
pub id: String,
pub text: String,
pub icon: String,
pub active: bool,
pub tone: &'static str,
pub enabled: bool,
/// Fixed width (design px); else from the text.
pub w: Option<f32>,
}
impl Ch {
pub fn new(id: impl Into<String>, text: impl Into<String>) -> Ch {
Ch { id: id.into(), text: text.into(), enabled: true, ..Ch::default() }
}
pub fn icon(mut self, icon: &str) -> Ch {
self.icon = icon.into();
self
}
pub fn active(mut self, on: bool) -> Ch {
self.active = on;
self
}
pub fn tone(mut self, tone: &'static str) -> Ch {
self.tone = tone;
self
}
pub fn enabled(mut self, on: bool) -> Ch {
self.enabled = on;
self
}
pub fn width(mut self, w: f32) -> Ch {
self.w = Some(w);
self
}
/// A text field: shows `value` (or the placeholder), opens the keyboard.
pub fn field(id: impl Into<String>, value: &str, placeholder: &str, icon: &str) -> Ch {
let text = if value.is_empty() { placeholder.to_string() } else { value.to_string() };
Ch { id: id.into(), text, icon: icon.into(), tone: "field", enabled: true, w: Some(900.0), ..Ch::default() }
}
fn width_of(&self) -> f32 {
if let Some(w) = self.w {
return w;
}
// Onest 23/600: about 12.4 px per character; capitals are wider.
let chars: f32 = self.text.chars().map(|c| if c.is_uppercase() { 15.5 } else { 12.4 }).sum();
if self.text.is_empty() {
return 64.0;
}
let icon = if self.icon.is_empty() { 0.0 } else { 38.0 };
(chars + icon + if self.icon.is_empty() { 52.0 } else { 46.0 }).max(88.0)
}
fn height_of(&self) -> f32 {
if self.tone == "field" { 80.0 } else { 64.0 }
}
}
/// A card.
#[derive(Debug, Clone, Default)]
pub struct C {
pub id: String,
pub title: String,
pub caption: String,
pub detail: String,
pub image: String,
pub progress: f32,
pub badge: String,
pub badge_tone: &'static str,
pub mark: &'static str,
pub big: String,
pub current: bool,
}
impl C {
pub fn new(id: impl Into<String>, title: impl Into<String>, image: impl Into<String>) -> C {
C { id: id.into(), title: title.into(), image: image.into(), progress: -1.0, ..C::default() }
}
}
/// One line of a page, as screens describe it.
#[derive(Debug, Clone)]
pub struct L {
pub id: String,
pub kind: Kind,
pub title: String,
pub subtitle: String,
pub meta: String,
pub extra: String,
pub text: String,
pub note: String,
pub style: String,
pub tone: String,
pub icon: String,
pub image: String,
pub logo: String,
pub progress: f32,
pub captions: bool,
/// Grids keep the column when moving between their lines.
pub grid: bool,
pub cards: Vec<C>,
pub chips: Vec<Ch>,
pub checks: Vec<(i32, String, String)>,
/// Fixed height (design px).
pub h: Option<f32>,
pub indent: f32,
}
impl L {
pub fn new(id: impl Into<String>, kind: Kind) -> L {
L {
id: id.into(),
kind,
title: String::new(),
subtitle: String::new(),
meta: String::new(),
extra: String::new(),
text: String::new(),
note: String::new(),
style: String::new(),
tone: String::new(),
icon: String::new(),
image: String::new(),
logo: String::new(),
progress: -1.0,
captions: false,
grid: false,
cards: Vec::new(),
chips: Vec::new(),
checks: Vec::new(),
h: None,
indent: 0.0,
}
}
pub fn heading(id: impl Into<String>, title: impl Into<String>) -> L {
let mut l = L::new(id, Kind::Heading);
l.title = title.into();
l
}
/// A page title (56 px).
pub fn page_title(id: impl Into<String>, title: impl Into<String>, subtitle: impl Into<String>) -> L {
let mut l = L::heading(id, title);
l.style = "big".into();
l.subtitle = subtitle.into();
l
}
pub fn text(id: impl Into<String>, text: impl Into<String>, style: &str) -> L {
let mut l = L::new(id, Kind::Text);
l.text = text.into();
l.style = style.into();
l
}
pub fn notice(id: impl Into<String>, tone: &str, title: impl Into<String>, text: impl Into<String>) -> L {
let mut l = L::new(id, Kind::Notice);
l.tone = tone.into();
l.title = title.into();
l.text = text.into();
l
}
pub fn chips(id: impl Into<String>, label: impl Into<String>, chips: Vec<Ch>) -> L {
let mut l = L::new(id, Kind::Chips);
l.title = label.into();
l.chips = chips;
l
}
pub fn cards(id: impl Into<String>, title: impl Into<String>, style: &str, cards: Vec<C>) -> L {
let mut l = L::new(id, Kind::Cards);
l.title = title.into();
l.style = style.into();
l.cards = cards;
l
}
pub fn item(id: impl Into<String>, title: impl Into<String>, meta: impl Into<String>, text: impl Into<String>, chips: Vec<Ch>) -> L {
let mut l = L::new(id, Kind::Item);
l.title = title.into();
l.meta = meta.into();
l.text = text.into();
l.chips = chips;
l
}
pub fn checks(id: impl Into<String>, checks: Vec<(i32, String, String)>) -> L {
let mut l = L::new(id, Kind::Checks);
l.checks = checks;
l
}
pub fn gap(h: f32) -> L {
let mut l = L::new(format!("gap{h}"), Kind::Gap);
l.h = Some(h);
l
}
pub fn sub(mut self, s: impl Into<String>) -> L {
self.subtitle = s.into();
self
}
pub fn image(mut self, url: impl Into<String>) -> L {
self.image = url.into();
self.style = "image".into();
self
}
pub fn progress(mut self, p: f32) -> L {
self.progress = p;
self
}
pub fn tone(mut self, t: &str) -> L {
self.tone = t.into();
self
}
pub fn captions(mut self) -> L {
self.captions = true;
self
}
pub fn grid(mut self) -> L {
self.grid = true;
self
}
fn focusable(&self) -> bool {
match self.kind {
Kind::Chips | Kind::Item | Kind::Hero => self.chips.iter().any(|c| c.enabled) || (self.kind == Kind::Item && !self.chips.is_empty()),
Kind::Cards => !self.cards.is_empty(),
Kind::Keyboard => true,
_ => false,
}
}
fn len(&self) -> usize {
if self.kind == Kind::Cards { self.cards.len() } else { self.chips.len() }
}
}
/// Splits a list into grid lines of `n` cards.
pub fn grid_lines(id: &str, title: &str, style: &str, cards: Vec<C>, n: usize) -> Vec<L> {
let mut out = Vec::new();
let mut it = cards.into_iter().peekable();
let mut i = 0;
while it.peek().is_some() {
let chunk: Vec<C> = it.by_ref().take(n).collect();
out.push(L::cards(format!("{id}#{i}"), if i == 0 { title } else { "" }, style, chunk).captions().grid());
i += 1;
}
out
}
/// What a screen shows besides its lines.
#[derive(Debug, Clone, Default)]
pub struct Frame {
/// The top navigation with this section lit.
pub nav: Option<usize>,
/// Settings: (title, items, current).
pub side: Option<(String, Vec<String>, usize)>,
/// The embedded search keyboard's placeholder (its line has kind Keyboard).
pub keyboard: Option<String>,
}
pub struct Spec {
pub lines: Vec<L>,
pub frame: Frame,
}
/// Where the focus is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Focus {
Nav,
Side,
Line,
}
#[derive(Debug, Clone, Default)]
struct Laid {
y: f32,
h: f32,
x: f32,
w: f32,
/// Chips: (x, y, w, h, row).
chips: Vec<(f32, f32, f32, f32, usize)>,
}
/// The page on screen: its lines laid out, the focus, the Slint models.
pub struct View {
pub lines: Vec<L>,
laid: Vec<Laid>,
pub frame: Frame,
pub focus: Focus,
pub line: usize,
cols: HashMap<String, usize>,
pub side_focus: usize,
pub nav_index: usize,
pub scroll: f32,
total: f32,
model: Rc<VecModel<Line>>,
card_models: Vec<Option<Rc<VecModel<Card>>>>,
shown: HashSet<String>,
}
impl Default for View {
fn default() -> Self {
View {
lines: Vec::new(),
laid: Vec::new(),
frame: Frame::default(),
focus: Focus::Line,
line: 0,
cols: HashMap::new(),
side_focus: 0,
nav_index: 0,
scroll: 0.0,
total: 0.0,
model: Rc::new(VecModel::default()),
card_models: Vec::new(),
shown: HashSet::new(),
}
}
}
/// Lines' heights and positions on the grid.
fn layout(lines: &[L], side: bool) -> (Vec<Laid>, f32) {
let (x0, w) = if side { (0.0, SIDE_W) } else { (0.0, CONTENT_W) };
let mut y = if side { 184.0 } else { 150.0 };
let mut out = Vec::with_capacity(lines.len());
let est = |text: &str, char_w: f32, width: f32, line_h: f32| -> f32 {
if text.is_empty() {
return 0.0;
}
let per_line = (width / char_w).max(10.0);
let n: f32 = text.split('\n').map(|p| (p.chars().count() as f32 / per_line).ceil().max(1.0)).sum();
n * line_h
};
for (i, l) in lines.iter().enumerate() {
let lw = w - l.indent;
let mut chips = Vec::new();
let h = match l.kind {
Kind::Hero => {
for (ci, c) in l.chips.iter().enumerate() {
let cw = c.width_of();
let cx = chips.last().map(|p: &(f32, f32, f32, f32, usize)| p.0 + p.2 + 20.0).unwrap_or(0.0);
let _ = ci;
chips.push((cx, 520.0, cw, 72.0, 0));
}
l.h.unwrap_or(640.0)
}
Kind::Heading => {
if l.style == "big" { 96.0 + if l.subtitle.is_empty() { 0.0 } else { 34.0 } } else { 58.0 + if l.subtitle.is_empty() { 0.0 } else { 34.0 } }
}
Kind::Text => {
let (cw, lh) = match l.style.as_str() {
"caption" => (10.6, 30.0),
"label" => (11.8, 34.0),
_ => (12.6, 38.0),
};
est(&l.text, cw, lw, lh) + 4.0
}
Kind::Notice => 48.0 + est(&l.text, 11.2, lw - 56.0, 32.0),
Kind::Checks => ((l.checks.len() + 1) / 2) as f32 * 84.0,
Kind::Chips => {
let top = if l.title.is_empty() { 0.0 } else { 38.0 };
let (mut cx, mut row, mut ry) = (0.0f32, 0usize, top);
let mut row_h = 0.0f32;
for c in &l.chips {
let (cw, ch) = (c.width_of().min(lw), c.height_of());
if cx > 0.0 && cx + cw > lw {
cx = 0.0;
row += 1;
ry += row_h + 14.0;
row_h = 0.0;
}
chips.push((cx, ry, cw, ch, row));
cx += cw + 14.0;
row_h = row_h.max(ch);
}
ry + row_h
}
Kind::Cards => {
let ch = match l.style.as_str() {
"landscape" => 225.0,
"season" => 252.0,
_ => 294.0,
};
(if l.title.is_empty() { 0.0 } else { 56.0 }) + ch + if l.captions { 80.0 } else { 0.0 } + 10.0
}
Kind::Item => {
let tx = if l.style == "image" { 288.0 } else { 0.0 };
let mut ty = 6.0 + 36.0 + if l.meta.is_empty() { 0.0 } else { 32.0 };
if !l.text.is_empty() {
ty += est(&l.text, 10.0, (lw - tx).min(1100.0), 29.0).min(58.0) + 6.0;
}
let mut cx = tx;
for c in &l.chips {
let cw = c.width_of();
chips.push((cx, ty + 4.0, cw, 60.0, 0));
cx += cw + 12.0;
}
let mut h = ty + if l.chips.is_empty() { 8.0 } else { 74.0 };
if l.style == "image" {
h = h.max(162.0);
}
if l.progress >= 0.0 && l.style != "image" {
h += 14.0;
}
h
}
Kind::Keyboard => 540.0,
Kind::Gap => 0.0,
};
let h = l.h.unwrap_or(h);
out.push(Laid { y, h, x: x0 + l.indent, w: lw, chips });
let next = lines.get(i + 1).map(|n| n.kind);
let gap = match (l.kind, next) {
(Kind::Gap, _) => 0.0,
(Kind::Heading, _) => 14.0,
(Kind::Cards, Some(Kind::Cards)) if l.grid => 18.0,
(Kind::Item, Some(Kind::Item)) => 14.0,
(Kind::Hero, _) => 24.0,
(_, Some(Kind::Heading)) => 44.0,
_ => 28.0,
};
y += h + gap;
}
(out, y)
}
impl View {
pub fn model(&self) -> ModelRc<Line> {
ModelRc::from(self.model.clone())
}
/// Shows new lines, keeping the focus on the same line (by id) and item.
pub fn set(&mut self, spec: Spec, images: &sf_ui::images::Images, px: f32) {
let old_id = self.lines.get(self.line).map(|l| l.id.clone());
if let Some(l) = self.lines.get(self.line) {
let c = self.col();
self.cols.insert(l.id.clone(), c);
}
let side = spec.frame.side.is_some();
self.lines = spec.lines;
self.frame = spec.frame;
let (laid, total) = layout(&self.lines, side);
self.laid = laid;
self.total = total;
self.line = match old_id.and_then(|id| self.lines.iter().position(|l| l.id == id)) {
Some(i) => i,
None => self.first_focusable().unwrap_or(0),
};
if !self.lines.get(self.line).is_some_and(L::focusable) {
self.line = self.nearest_focusable(self.line).unwrap_or(0);
}
if let Some((_, items, cur)) = &self.frame.side {
if self.focus != Focus::Side {
self.side_focus = *cur;
}
self.side_focus = self.side_focus.min(items.len().saturating_sub(1));
}
if self.focus == Focus::Nav && self.frame.nav.is_none() {
self.focus = Focus::Line;
}
if self.focus == Focus::Line && self.first_focusable().is_none() {
if self.frame.nav.is_some() {
self.focus = Focus::Nav;
} else if self.frame.side.is_some() {
self.focus = Focus::Side;
}
}
self.shown.clear();
self.card_models = vec![None; self.lines.len()];
let rows: Vec<Line> = (0..self.lines.len()).map(|i| self.slint_line(i, images, px)).collect();
self.model.set_vec(rows);
self.clamp_scroll();
}
/// Line `i`'s top (design px).
pub fn line_y(&self, i: usize) -> f32 {
self.laid.get(i).map(|l| l.y).unwrap_or(0.0)
}
pub fn has_lines(&self) -> bool {
!self.lines.is_empty()
}
fn first_focusable(&self) -> Option<usize> {
self.lines.iter().position(L::focusable)
}
fn nearest_focusable(&self, from: usize) -> Option<usize> {
(from..self.lines.len()).find(|&i| self.lines[i].focusable()).or_else(|| (0..from).rev().find(|&i| self.lines[i].focusable()))
}
pub fn col(&self) -> usize {
let Some(l) = self.lines.get(self.line) else { return 0 };
let c = self.cols.get(&l.id).copied().unwrap_or(0);
c.min(l.len().saturating_sub(1))
}
fn set_col(&mut self, c: usize) {
if let Some(l) = self.lines.get(self.line) {
self.cols.insert(l.id.clone(), c);
}
}
/// Sets the focus on line `id` (and item index), if it exists.
pub fn focus_on(&mut self, id: &str, col: usize) {
if let Some(i) = self.lines.iter().position(|l| l.id == id) {
self.line = i;
self.focus = Focus::Line;
self.set_col(col);
self.clamp_scroll();
}
}
/// The focused line's id and item id ("" if none).
pub fn target(&self) -> (String, String) {
let Some(l) = self.lines.get(self.line) else { return (String::new(), String::new()) };
let c = self.col();
let item = match l.kind {
Kind::Cards => l.cards.get(c).map(|c| c.id.clone()),
_ => l.chips.get(c).map(|c| c.id.clone()),
};
(l.id.clone(), item.unwrap_or_default())
}
pub fn focused_kind(&self) -> Option<Kind> {
if self.focus != Focus::Line {
return None;
}
self.lines.get(self.line).map(|l| l.kind)
}
/// Center x of the focused element (for spatial up/down).
fn focus_x(&self) -> f32 {
let Some(l) = self.lines.get(self.line) else { return 0.0 };
let c = self.col();
match l.kind {
Kind::Cards => {
let step = card_step(&l.style);
let fit = ((CONTENT_W + 32.0) / step).floor() as usize;
let scroll = c.saturating_sub(1).min(l.cards.len().saturating_sub(fit));
(c - scroll) as f32 * step + step / 2.0
}
_ => self.laid[self.line].chips.get(c).map(|p| p.0 + p.2 / 2.0).unwrap_or(0.0),
}
}
fn nearest_in(&self, li: usize, x: f32, row: Option<usize>) -> usize {
let l = &self.lines[li];
match l.kind {
Kind::Cards => {
let step = card_step(&l.style);
((x / step).floor() as usize).min(l.cards.len().saturating_sub(1))
}
_ => {
let chips = &self.laid[li].chips;
let mut best = (f32::MAX, 0usize);
for (i, p) in chips.iter().enumerate() {
if let Some(r) = row {
if p.4 != r {
continue;
}
}
if !l.chips[i].enabled {
continue;
}
let d = (p.0 + p.2 / 2.0 - x).abs();
if d < best.0 {
best = (d, i);
}
}
best.1
}
}
}
/// Up/down. Returns false at the edges (the caller may move to the nav).
pub fn vertical(&mut self, down: bool) -> bool {
let Some(l) = self.lines.get(self.line) else { return false };
let x = self.focus_x();
// Inside a wrapped chip line first.
if l.kind == Kind::Chips {
let row = self.laid[self.line].chips.get(self.col()).map(|p| p.4).unwrap_or(0);
let rows = self.laid[self.line].chips.iter().map(|p| p.4).max().unwrap_or(0);
let next = if down { (row < rows).then_some(row + 1) } else { row.checked_sub(1) };
if let Some(r) = next {
let c = self.nearest_in(self.line, x, Some(r));
self.set_col(c);
self.clamp_scroll();
return true;
}
}
let grid_col = if l.grid { Some(self.col()) } else { None };
let mut i = self.line as isize;
loop {
i += if down { 1 } else { -1 };
if i < 0 || i as usize >= self.lines.len() {
return false;
}
if self.lines[i as usize].focusable() {
break;
}
}
let prev = self.line;
self.line = i as usize;
let nl = &self.lines[self.line];
match nl.kind {
Kind::Cards if nl.grid && grid_col.is_some() => self.set_col(grid_col.unwrap().min(nl.cards.len().saturating_sub(1))),
Kind::Cards => {}
Kind::Chips | Kind::Item | Kind::Hero => {
let rows = self.laid[self.line].chips.iter().map(|p| p.4).max().unwrap_or(0);
let row = if down { 0 } else { rows };
let c = self.nearest_in(self.line, x, Some(row));
self.set_col(c);
}
_ => {}
}
let _ = prev;
self.clamp_scroll();
true
}
/// Left/right inside the line. Returns false at the edges.
pub fn horizontal(&mut self, right: bool) -> bool {
let Some(l) = self.lines.get(self.line) else { return false };
let n = l.len();
let c = self.col();
let mut next = c as isize;
loop {
next += if right { 1 } else { -1 };
if next < 0 || next as usize >= n {
return false;
}
let ok = match l.kind {
Kind::Cards => true,
_ => l.chips[next as usize].enabled,
};
if ok {
break;
}
}
self.set_col(next as usize);
true
}
/// Scrolls so the focused line sits comfortably on screen.
pub fn clamp_scroll(&mut self) {
let Some(laid) = self.laid.get(self.line) else {
self.scroll = 0.0;
return;
};
let top_margin = if self.frame.side.is_some() { 184.0 } else { 150.0 };
let mut target = if self.line == 0 || laid.y - top_margin < 120.0 {
0.0
} else {
laid.y - 230.0
};
// Tall lines (the keyboard) and wrapped chip rows: keep the focused row visible.
if let Some(l) = self.lines.get(self.line) {
if l.kind == Kind::Chips {
if let Some(p) = laid.chips.get(self.col()) {
if laid.y + p.1 + p.3 - target > 1000.0 {
target = laid.y + p.1 + p.3 - 1000.0;
}
}
}
}
let max = (self.total - 1000.0).max(0.0);
self.scroll = target.clamp(0.0, max.max(0.0)).max(0.0);
if self.focus == Focus::Nav {
self.scroll = 0.0;
}
}
/// Slint's struct for line `i`.
fn slint_line(&mut self, i: usize, images: &sf_ui::images::Images, px: f32) -> Line {
let l = &self.lines[i];
let laid = &self.laid[i];
let chips: Vec<Chip> = l
.chips
.iter()
.zip(laid.chips.iter())
.map(|(c, p)| Chip {
id: c.id.clone().into(),
text: c.text.clone().into(),
icon: c.icon.clone().into(),
x: p.0,
y: p.1,
w: p.2,
h: p.3,
active: c.active,
tone: c.tone.into(),
enabled: c.enabled,
})
.collect();
let (cw, ch) = card_size(&l.style);
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
let cards: Vec<Card> = l
.cards
.iter()
.map(|c| Card {
id: c.id.clone().into(),
title: c.title.clone().into(),
caption: c.caption.clone().into(),
detail: c.detail.clone().into(),
image: images.cached(&c.image, size).unwrap_or_default(),
progress: c.progress,
badge: c.badge.clone().into(),
badge_tone: c.badge_tone.into(),
mark: c.mark.into(),
big: c.big.clone().into(),
current: c.current,
})
.collect();
let card_model = Rc::new(VecModel::from(cards));
let checks: Vec<Check> = l.checks.iter().map(|(s, a, b)| Check { state: *s, label: a.clone().into(), detail: b.clone().into() }).collect();
let logo_size = ((620.0 * px) as u32, (190.0 * px) as u32);
let item_size = ((256.0 * px * 1.1) as u32, (144.0 * px * 1.1) as u32);
let line = Line {
id: l.id.clone().into(),
kind: l.kind.name().into(),
y: laid.y,
h: laid.h,
x: laid.x,
w: laid.w,
title: l.title.clone().into(),
subtitle: l.subtitle.clone().into(),
meta: l.meta.clone().into(),
extra: l.extra.clone().into(),
text: l.text.clone().into(),
note: l.note.clone().into(),
style: l.style.clone().into(),
tone: l.tone.clone().into(),
icon: l.icon.clone().into(),
image: if l.image.is_empty() { Default::default() } else { images.cached(&l.image, item_size).unwrap_or_default() },
logo: if l.logo.is_empty() { Default::default() } else { images.cached(&l.logo, logo_size).unwrap_or_default() },
progress: l.progress,
col: self.cols.get(&l.id).copied().unwrap_or(0).min(l.len().saturating_sub(1)) as i32,
captions: l.captions,
cards: ModelRc::from(card_model.clone()),
chips: ModelRc::new(VecModel::from(chips)),
checks: ModelRc::new(VecModel::from(checks)),
};
self.card_models[i] = Some(card_model);
line
}
/// Sends the focus (column, line, scroll) to Slint's models.
pub fn sync_cols(&self) {
for (i, l) in self.lines.iter().enumerate() {
let want = self.cols.get(&l.id).copied().unwrap_or(0).min(l.len().saturating_sub(1)) as i32;
if let Some(mut row) = self.model.row_data(i) {
if row.col != want {
row.col = want;
self.model.set_row_data(i, row);
}
}
}
}
/// Loads the pictures of the lines around the focus (cached ones were
/// set when building).
pub fn load_images(&mut self, images: &sf_ui::images::Images, px: f32) {
let view_top = self.scroll - 400.0;
let view_bottom = self.scroll + 1080.0 + 900.0;
for i in 0..self.lines.len() {
let laid = &self.laid[i];
if laid.y + laid.h < view_top || laid.y > view_bottom {
continue;
}
let l = &self.lines[i];
if !l.logo.is_empty() && self.shown.insert(format!("{}#logo", l.id)) {
let model = self.model.clone();
let id = l.id.clone();
images.load(&l.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
if let Some(idx) = (0..model.row_count()).find(|&k| model.row_data(k).is_some_and(|r| r.id == id)) {
let mut row = model.row_data(idx).unwrap();
row.logo = img;
model.set_row_data(idx, row);
}
});
}
if !l.image.is_empty() && self.shown.insert(format!("{}#image", l.id)) {
let model = self.model.clone();
let id = l.id.clone();
images.load(&l.image, ((256.0 * px * 1.1) as u32, (144.0 * px * 1.1) as u32), move |img| {
if let Some(idx) = (0..model.row_count()).find(|&k| model.row_data(k).is_some_and(|r| r.id == id)) {
let mut row = model.row_data(idx).unwrap();
row.image = img;
model.set_row_data(idx, row);
}
});
}
if l.kind != Kind::Cards || l.cards.is_empty() {
continue;
}
let col = self.cols.get(&l.id).copied().unwrap_or(0);
let step = card_step(&l.style);
let fit = ((CONTENT_W + 32.0) / step).floor() as usize;
let start = col.saturating_sub(2);
let end = (col + fit + 3).min(l.cards.len());
let (cw, ch) = card_size(&l.style);
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
let Some(Some(model)) = self.card_models.get(i).cloned() else { continue };
for ci in start..end {
let c = &l.cards[ci];
if c.image.is_empty() || !self.shown.insert(format!("{}#{}", l.id, c.id)) {
continue;
}
let model = model.clone();
let card_id = c.id.clone();
images.load(&c.image, size, move |img| {
if let Some(mut row) = model.row_data(ci) {
if row.id == card_id && row.image.size().width == 0 {
row.image = img;
model.set_row_data(ci, row);
}
}
});
}
}
}
/// Lines whose end is near the focus (infinite lists ask for more).
pub fn near_end(&self) -> Option<String> {
let l = self.lines.get(self.line)?;
if l.grid {
// The last grid line of this list is close.
let prefix = l.id.split('#').next().unwrap_or("");
let last = self.lines.iter().rposition(|x| x.id.starts_with(&format!("{prefix}#")))?;
if last <= self.line + 2 {
return Some(prefix.to_string());
}
} else if l.kind == Kind::Cards && self.col() + 6 >= l.cards.len() {
return Some(l.id.clone());
}
None
}
/// Replaces one card's picture (a backdrop loaded elsewhere...).
pub fn line_index(&self, id: &str) -> Option<usize> {
self.lines.iter().position(|l| l.id == id)
}
}
pub fn card_size(style: &str) -> (f32, f32) {
match style {
"landscape" => (400.0, 225.0),
"season" => (168.0, 252.0),
_ => (196.0, 294.0),
}
}
fn card_step(style: &str) -> f32 {
card_size(style).0 + 32.0
}
/// Cards per grid line.
pub const GRID: usize = 8;
#[cfg(test)]
mod tests {
use super::*;
fn chips_line(n: usize) -> L {
L::chips("c", "Műfaj", (0..n).map(|i| Ch::new(format!("g{i}"), format!("Műfaj {i}"))).collect())
}
#[test]
fn wraps_chips_and_moves_by_rows() {
let lines = vec![chips_line(40), L::cards("r", "Sor", "poster", (0..20).map(|i| C::new(format!("{i}"), "x", "")).collect())];
let (laid, _) = layout(&lines, false);
let rows = laid[0].chips.iter().map(|p| p.4).max().unwrap();
assert!(rows >= 2, "40 chips wrap");
assert!(laid[0].chips.iter().all(|p| p.0 + p.2 <= CONTENT_W + 0.1));
let mut v = View { lines: lines.clone(), laid, ..View::default() };
v.total = 2000.0;
assert!(v.vertical(true));
assert_eq!(v.line, 0, "first down stays in the chip line (next row)");
let row = v.laid[0].chips[v.col()].4;
assert_eq!(row, 1);
for _ in 0..rows {
v.vertical(true);
}
assert_eq!(v.line, 1, "then the cards");
assert!(!v.vertical(true), "nothing below");
}
#[test]
fn grids_keep_the_column() {
let cards: Vec<C> = (0..20).map(|i| C::new(format!("{i}"), "x", "")).collect();
let lines = grid_lines("g", "Rács", "poster", cards, 8);
assert_eq!(lines.len(), 3);
let (laid, total) = layout(&lines, false);
let mut v = View { lines, laid, total, ..View::default() };
v.set_col(5);
v.vertical(true);
assert_eq!((v.line, v.col()), (1, 5));
v.vertical(true);
assert_eq!((v.line, v.col()), (2, 3), "clamped to the short last line");
assert_eq!(v.near_end().as_deref(), Some("g"));
}
#[test]
fn skips_disabled_chips() {
let line = L::chips("c", "", vec![Ch::new("a", "A"), Ch::new("b", "B").enabled(false), Ch::new("c", "C")]);
let (laid, total) = layout(std::slice::from_ref(&line), false);
let mut v = View { lines: vec![line], laid, total, ..View::default() };
assert!(v.horizontal(true));
assert_eq!(v.target().1, "c");
assert!(!v.horizontal(true));
}
}

714
src/player.rs Normal file
View File

@@ -0,0 +1,714 @@
//! Playback: title (+ episode) -> an nCore source -> the torrent started on
//! the server -> the file probed -> GStreamer plays the server's raw stream
//! (`/api/stream`, range requests) while the torrent keeps downloading.
//!
//! The video is the glass backdrop, so the controls are glass over the film.
//! Remote: OK = play/pause, left/right = seek (held: faster), up = audio,
//! subtitles and sync, down = "next episode", Back = hide controls / leave.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use slint::{ModelRc, VecModel};
use crate::api::{self, MediaType, ProbeInfo};
#[cfg(target_os = "linux")]
use crate::api::MediaTrack;
use crate::app::{Action, Controller, Screen};
use crate::{MenuItem, detail, format, task};
/// What to play.
#[derive(Debug, Clone)]
pub struct Request {
pub kind: MediaType,
pub id: String,
pub title: String,
pub ep: Option<(i32, i32)>,
pub episode_name: String,
/// Start position, seconds.
pub resume: f64,
pub backdrop: String,
/// The episode after this one, if any.
pub next: Option<(i32, i32)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Stage {
Prep,
Play,
Error,
}
struct Media {
hash: String,
file: i64,
probe: ProbeInfo,
}
/// One track as shown in the menus (from GStreamer, with the server's
/// probe filling in flags when the counts match).
#[derive(Debug, Clone, Default)]
struct Track {
index: i32,
language: Option<String>,
title: Option<String>,
channels: Option<i64>,
default: bool,
forced: bool,
}
const SYNC_STEPS: [i64; 13] = [-2000, -1000, -500, -300, -200, -100, 0, 100, 200, 300, 500, 1000, 2000];
const OSD_SECONDS: u64 = 4;
const SAVE_EVERY: Duration = Duration::from_secs(15);
const COMMENTARY: [&str; 3] = ["commentary", "kommentár", "director"];
const FORCED: [&str; 3] = ["forced", "kényszerített", "sign"];
pub struct Player {
req: Request,
generation: u64,
cancel: Arc<AtomicBool>,
stage: Stage,
media: Option<Media>,
#[cfg(target_os = "linux")]
video: Option<sf_ui::video::Player>,
timer: slint::Timer,
osd_until: Instant,
seek_target: Option<f64>,
seek_commit: Instant,
/// 0 = closed, 1 = audio, 2 = subtitles, 3 = sync.
panel: i32,
focus: [usize; 3],
audio: Vec<Track>,
subs: Vec<Track>,
audio_on: i32,
subs_on: Option<i32>,
delay_ms: i64,
position: f64,
duration: Option<f64>,
last_save: Instant,
next_focused: bool,
playing: bool,
}
static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn subtitle_line(req: &Request) -> String {
match req.ep {
Some((s, e)) if req.episode_name.is_empty() => format::episode_code(s, e),
Some((s, e)) => format!("{} · {}", format::episode_code(s, e), req.episode_name),
None => String::new(),
}
}
/// Starts playing `req` (replacing whatever plays).
pub fn play(c: &Controller, req: Request) {
stop(c, true);
let generation = GENERATION.fetch_add(1, Ordering::Relaxed);
let cancel = Arc::new(AtomicBool::new(false));
{
let mut st = c.state.borrow_mut();
st.player = Some(Player {
req: req.clone(),
generation,
cancel: cancel.clone(),
stage: Stage::Prep,
media: None,
#[cfg(target_os = "linux")]
video: None,
timer: slint::Timer::default(),
osd_until: Instant::now(),
seek_target: None,
seek_commit: Instant::now(),
panel: 0,
focus: [0; 3],
audio: Vec::new(),
subs: Vec::new(),
audio_on: 0,
subs_on: None,
delay_ms: 0,
position: req.resume,
duration: None,
last_save: Instant::now(),
next_focused: false,
playing: false,
});
}
if let Some(ui) = c.ui() {
ui.set_player_stage("prep".into());
ui.set_player_title(req.title.clone().into());
ui.set_player_subtitle(subtitle_line(&req).into());
ui.set_player_stage_text("Forrás keresése az nCore-on…".into());
ui.set_player_detail_text("".into());
ui.set_player_error_text("".into());
ui.set_player_osd(false);
ui.set_player_paused(false);
ui.set_player_buffering(false);
ui.set_player_progress(0.0);
ui.set_player_buffered(0.0);
ui.set_player_seeking(false);
ui.set_player_panel(0);
ui.set_player_next_label("".into());
ui.set_player_next_focused(false);
}
// While preparing: the title's artwork, soft.
if !req.backdrop.is_empty() {
let k = c.clone();
let px = c.px();
c.images.load_pixels(&req.backdrop, ((960.0 * px) as u32, (540.0 * px) as u32), move |pixels| {
if k.state.borrow().player.as_ref().is_some_and(|p| p.generation == generation && p.stage == Stage::Prep) {
k.glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone()).dim(0.55).fade_left(0.0).fade_bottom(0.0).soft()));
}
});
}
if c.state.borrow().screen == Screen::Player {
c.show(Screen::Player);
} else {
c.push(Screen::Player);
}
let api = c.api();
let weak = c.ui.clone();
let stage = move |text: String| {
let w = weak.clone();
let _ = w.upgrade_in_event_loop(move |ui| ui.set_player_stage_text(text.into()));
};
let weak2 = c.ui.clone();
let detail_text = move |text: String| {
let _ = weak2.upgrade_in_event_loop(move |ui| ui.set_player_detail_text(text.into()));
};
let k = c.clone();
let flag = cancel.clone();
task::spawn(
move || -> anyhow::Result<Media> {
let sources = api.sources(req.kind, &req.id, req.ep)?;
anyhow::ensure!(
!sources.candidates.is_empty(),
match req.ep {
Some((s, e)) => format!("Nincs nCore torrent ehhez: {}.", format::episode_code(s, e)),
None => "Nincs nCore torrent ehhez a filmhez.".into(),
}
);
let mut last: Option<anyhow::Error> = None;
for cand in sources.candidates.iter().take(3) {
if flag.load(Ordering::Relaxed) {
anyhow::bail!("cancelled");
}
let local = matches!(cand.local.as_deref(), Some("seeding" | "eligible"));
stage(if local { "Indítás a szerveren lévő fájlból…".into() } else { "Torrent indítása…".into() });
detail_text(format!("{} · {} · {} seeder", cand.torrent.name, api::format_bytes(cand.torrent.size), cand.torrent.seeders));
let started = match api.start_play(req.kind, &req.id, cand.torrent.id, req.ep) {
Ok(s) => s,
Err(e) => {
// VPN, disk quota or nCore trouble: another torrent fails the same way.
if let Some(a) = e.downcast_ref::<api::ApiError>() {
if matches!(a.status, 401 | 409 | 503 | 507) {
return Err(e);
}
}
last = Some(e);
continue;
}
};
stage("A fájl elejének letöltése és elemzése…".into());
let cancelled = || flag.load(Ordering::Relaxed);
match api::probe_while_downloading(&api, &started.info_hash, started.file_index, &stage, &cancelled) {
Ok(probe) => return Ok(Media { hash: started.info_hash, file: started.file_index, probe }),
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| anyhow::anyhow!("Nem sikerült elindítani")))
},
move |r| {
if cancel.load(Ordering::Relaxed) || !k.state.borrow().player.as_ref().is_some_and(|p| p.generation == generation) {
return;
}
match r {
Ok(media) => start(&k, media),
Err(e) if api::is_unauthenticated(&e) => k.signed_out(),
Err(e) => fail(&k, &api::describe(&e)),
}
},
);
}
fn fail(c: &Controller, text: &str) {
if let Some(p) = c.state.borrow_mut().player.as_mut() {
p.stage = Stage::Error;
}
c.glass.set_video(None);
if let Some(ui) = c.ui() {
ui.set_player_stage("error".into());
ui.set_player_error_text(text.into());
}
}
#[cfg(not(target_os = "linux"))]
fn start(c: &Controller, media: Media) {
if let Some(p) = c.state.borrow_mut().player.as_mut() {
p.media = Some(media);
}
fail(c, "Ezen a gépen nincs lejátszó: a videó a TV-n (Linux, GStreamer) játszik.");
}
#[cfg(target_os = "linux")]
fn start(c: &Controller, media: Media) {
let (uri, opts, generation) = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let opts = sf_ui::video::PlayerOptions {
start: p.req.resume,
audio_offset_ms: media.probe.audio_delay_ms.unwrap_or(0),
subtitles: true,
user_agent: Some(concat!("NetflexTV/", env!("CARGO_PKG_VERSION"), " SmartFox").into()),
..Default::default()
};
(st.api.stream_url(&media.hash, media.file), opts, p.generation)
};
let delay = opts.audio_offset_ms;
match sf_ui::video::Player::new(&uri, opts) {
Ok(v) => {
c.glass.set_backdrop(None);
c.glass.set_video(Some(v.video()));
{
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
p.duration = media.probe.duration_sec;
p.media = Some(media);
p.video = Some(v);
p.stage = Stage::Play;
p.delay_ms = delay;
p.osd_until = Instant::now() + Duration::from_secs(OSD_SECONDS);
p.last_save = Instant::now();
let k = c.clone();
p.timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || tick(&k, generation));
}
if let Some(ui) = c.ui() {
ui.set_player_stage("play".into());
ui.set_player_buffering(true);
ui.set_player_osd(true);
}
}
Err(e) => fail(c, &format!("A lejátszó nem indult: {e:#}")),
}
}
#[cfg(target_os = "linux")]
fn tick(c: &Controller, generation: u64) {
use sf_ui::video::Event;
enum End {
No,
Finished,
Failed(String),
}
let mut end = End::No;
let mut save: Option<(f64, Option<f64>)> = None;
{
let mut st = c.state.borrow_mut();
let settings_sub = st.settings.subtitle_lang.clone().unwrap_or_else(|| "hu".into());
let Some(p) = st.player.as_mut().filter(|p| p.generation == generation) else { return };
let Some(v) = p.video.as_mut() else { return };
let ui = c.ui();
for ev in v.poll() {
match ev {
Event::Ready { duration } => {
if duration.is_some() {
p.duration = duration;
}
let probe = p.media.as_ref().map(|m| m.probe.tracks.clone()).unwrap_or_default();
p.audio = merge(v.audio_tracks(), &probe, "audio");
p.subs = merge(v.text_tracks(), &probe, "subtitle");
p.audio_on = pick_audio(&p.audio).unwrap_or(v.current_audio().max(0));
v.set_audio(p.audio_on);
let audio_lang = p.audio.iter().find(|t| t.index == p.audio_on).and_then(|t| t.language.clone());
p.subs_on = pick_subtitle(&p.subs, audio_lang.as_deref(), &settings_sub);
v.set_text(p.subs_on);
p.playing = true;
}
Event::Buffering(pct) => {
if let Some(ui) = &ui {
ui.set_player_buffering(pct < 100);
}
}
Event::Playing(on) => {
p.playing = on || v.is_playing();
if let Some(ui) = &ui {
ui.set_player_paused(!v.is_playing());
if on {
ui.set_player_buffering(false);
}
}
}
Event::Seeked => {}
Event::Eos => end = End::Finished,
Event::Error(e) => end = End::Failed(e),
}
}
let now = Instant::now();
if let Some(t) = p.seek_target {
if now >= p.seek_commit {
v.seek(t, false);
p.seek_target = None;
p.position = t;
}
} else if let Some(pos) = v.position() {
p.position = pos;
}
if let Some(d) = v.duration() {
p.duration = Some(d);
}
if v.is_playing() && now.duration_since(p.last_save) >= SAVE_EVERY && p.position > 5.0 {
p.last_save = now;
save = Some((p.position, p.duration));
}
if let Some(ui) = &ui {
let shown = p.seek_target.unwrap_or(p.position);
let dur = p.duration.unwrap_or(0.0);
ui.set_player_progress(if dur > 0.0 { (shown / dur) as f32 } else { 0.0 });
ui.set_player_time_text(format::time(shown).into());
ui.set_player_remaining_text(if dur > 0.0 { format::time(dur).into() } else { "".into() });
ui.set_player_seeking(p.seek_target.is_some());
ui.set_player_buffering(v.is_buffering() && !matches!(end, End::Failed(_)));
ui.set_player_paused(!v.is_playing());
let osd = p.panel > 0 || p.next_focused || !v.is_playing() || now < p.osd_until;
ui.set_player_osd(osd);
let near_end = dur > 0.0 && dur - shown < 45.0;
let label = match p.req.next {
Some((s, e)) if near_end || p.next_focused => format!("Következő rész · {}", format::episode_code(s, e)),
_ => String::new(),
};
if label.is_empty() {
p.next_focused = false;
}
ui.set_player_next_label(label.into());
ui.set_player_next_focused(p.next_focused);
}
}
if let Some((pos, dur)) = save {
save_progress(c, pos, dur);
}
match end {
End::No => {}
End::Finished => finished(c),
End::Failed(e) => fail(c, &format!("Lejátszási hiba: {e}")),
}
}
/// GStreamer's tracks, with the server's probe flags when the counts match
/// (both list the file's tracks in order).
#[cfg(target_os = "linux")]
fn merge(tracks: Vec<sf_ui::video::Track>, probe: &[MediaTrack], kind: &str) -> Vec<Track> {
let probe: Vec<&MediaTrack> = probe.iter().filter(|t| t.kind == kind).collect();
let same = probe.len() == tracks.len();
tracks
.into_iter()
.enumerate()
.map(|(i, t)| {
let p = if same { probe.get(i).copied() } else { None };
Track {
index: t.index,
language: p.and_then(|p| p.language.clone()).or_else(|| format::lang_code(t.language.as_deref())),
title: p.and_then(|p| p.title.clone()).or(t.title),
channels: p.and_then(|p| p.channels),
default: p.is_some_and(|p| p.is_default),
forced: p.is_some_and(|p| p.is_forced),
}
})
.collect()
}
fn has_any(s: &Option<String>, words: &[&str]) -> bool {
s.as_deref().map(str::to_lowercase).is_some_and(|t| words.iter().any(|w| t.contains(w)))
}
/// Hungarian audio when there is any, else the default track, else the first.
fn pick_audio(tracks: &[Track]) -> Option<i32> {
let usable: Vec<&Track> = tracks.iter().filter(|t| !has_any(&t.title, &COMMENTARY)).collect();
usable
.iter()
.find(|t| t.language.as_deref() == Some("hu"))
.or_else(|| usable.iter().find(|t| t.default))
.or_else(|| usable.first())
.map(|t| t.index)
.or_else(|| tracks.first().map(|t| t.index))
}
/// With Hungarian audio: only a forced Hungarian track. Otherwise full
/// subtitles in the preferred language, falling back to English.
fn pick_subtitle(tracks: &[Track], audio_lang: Option<&str>, prefer: &str) -> Option<i32> {
let forced = |t: &Track| t.forced || has_any(&t.title, &FORCED);
let lang = |l: &str| tracks.iter().filter(|t| t.language.as_deref() == Some(l)).collect::<Vec<_>>();
if audio_lang == Some("hu") {
return lang("hu").into_iter().find(|t| forced(t)).map(|t| t.index);
}
let mut cands = lang(prefer);
if cands.is_empty() {
cands = lang("en");
}
let full: Vec<&&Track> = cands.iter().filter(|t| !forced(t)).collect();
full.iter().find(|t| t.default).or_else(|| full.first()).map(|t| t.index).or_else(|| cands.first().map(|t| t.index))
}
fn track_label(t: &Track) -> String {
let lang = format::language(t.language.as_deref());
match &t.title {
Some(title) if !title.to_lowercase().contains(&lang.to_lowercase()) && !title.trim().is_empty() => format!("{lang} — {title}"),
_ => lang,
}
}
fn menus(c: &Controller) {
let Some(ui) = c.ui() else { return };
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let audio: Vec<MenuItem> = p
.audio
.iter()
.map(|t| MenuItem { text: track_label(t).into(), detail: format::channels(t.channels).into(), checked: t.index == p.audio_on })
.collect();
let mut subs = vec![MenuItem { text: "Kikapcsolva".into(), detail: "".into(), checked: p.subs_on.is_none() }];
subs.extend(p.subs.iter().map(|t| MenuItem {
text: track_label(t).into(),
detail: if t.forced { "kényszerített".into() } else { "".into() },
checked: Some(t.index) == p.subs_on,
}));
let sync: Vec<MenuItem> =
SYNC_STEPS.iter().map(|ms| MenuItem { text: format::delay(*ms).into(), detail: "".into(), checked: *ms == p.delay_ms }).collect();
ui.set_player_audio(ModelRc::new(VecModel::from(audio)));
ui.set_player_subs(ModelRc::new(VecModel::from(subs)));
ui.set_player_sync(ModelRc::new(VecModel::from(sync)));
ui.set_player_panel(p.panel);
ui.set_player_audio_focus(p.focus[0] as i32);
ui.set_player_subs_focus(p.focus[1] as i32);
ui.set_player_sync_focus(p.focus[2] as i32);
}
fn save_progress(c: &Controller, position: f64, duration: Option<f64>) {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let Some(m) = p.media.as_ref() else { return };
let (api, kind, id, ep, hash, file) = (st.api.clone(), p.req.kind, p.req.id.clone(), p.req.ep, m.hash.clone(), m.file);
task::background("progress", move || api.save_progress(kind, &id, ep, position, duration, &hash, file));
}
/// The end of the film: the next episode, or back.
fn finished(c: &Controller) {
let (next, auto, req, duration) = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
(p.req.next, st.settings.auto_next.unwrap_or(true), p.req.clone(), p.duration)
};
if let Some(d) = duration {
save_progress(c, d, Some(d));
}
match next {
Some(ep) if auto => play_next(c, &req, ep),
_ => leave(c),
}
}
fn play_next(c: &Controller, req: &Request, ep: (i32, i32)) {
let next = detail::next_after(c, ep);
let name = detail::episode_name(c, ep);
play(c, Request { ep: Some(ep), episode_name: name, resume: 0.0, next, ..req.clone() });
}
/// Stops playback; `save`: remember the position on the server.
pub fn stop(c: &Controller, save: bool) {
let pos = {
let st = c.state.borrow();
st.player.as_ref().filter(|p| p.stage == Stage::Play).map(|p| (p.seek_target.unwrap_or(p.position), p.duration))
};
if save {
if let Some((pos, dur)) = pos.filter(|(p, _)| *p > 5.0) {
save_progress(c, pos, dur);
}
}
let old = c.state.borrow_mut().player.take();
if let Some(p) = old {
p.cancel.store(true, Ordering::Relaxed);
p.timer.stop();
drop(p);
c.glass.set_video(None);
}
}
fn leave(c: &Controller) {
stop(c, true);
if !c.pop() {
crate::home::open(c, 0);
}
}
pub fn key(c: &Controller, a: Action, repeat: bool) {
let stage = c.state.borrow().player.as_ref().map(|p| p.stage.clone());
match stage {
Some(Stage::Play) => {}
Some(_) => {
if a == Action::Back {
leave(c);
}
return;
}
None => return,
}
enum Then {
Nothing,
Menus,
Leave,
Next(Request, (i32, i32)),
}
let then = {
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
let now = Instant::now();
p.osd_until = now + Duration::from_secs(OSD_SECONDS);
#[cfg(target_os = "linux")]
let v = p.video.as_mut();
if p.panel > 0 {
let col = (p.panel - 1) as usize;
let len = match col {
0 => p.audio.len(),
1 => p.subs.len() + 1,
_ => SYNC_STEPS.len(),
};
match a {
Action::Up => p.focus[col] = p.focus[col].saturating_sub(1),
Action::Down => p.focus[col] = (p.focus[col] + 1).min(len.saturating_sub(1)),
Action::Left => p.panel = (p.panel - 1).max(1),
Action::Right => p.panel = (p.panel + 1).min(3),
Action::Back => p.panel = 0,
Action::Ok | Action::PlayPause => {
let i = p.focus[col];
match col {
0 => {
if let Some(t) = p.audio.get(i) {
p.audio_on = t.index;
#[cfg(target_os = "linux")]
if let Some(v) = v {
v.set_audio(t.index);
}
}
}
1 => {
p.subs_on = if i == 0 { None } else { p.subs.get(i - 1).map(|t| t.index) };
#[cfg(target_os = "linux")]
if let Some(v) = v {
v.set_text(p.subs_on);
}
}
_ => {
let ms = SYNC_STEPS[i.min(SYNC_STEPS.len() - 1)];
p.delay_ms = ms;
#[cfg(target_os = "linux")]
if let Some(v) = v {
v.set_audio_offset_ms(ms);
}
drop(st);
menus(c);
return save_delay(c, ms);
}
}
}
}
Then::Menus
} else {
match a {
Action::Ok | Action::PlayPause => {
if p.next_focused {
match p.req.next {
Some(ep) => Then::Next(p.req.clone(), ep),
None => Then::Nothing,
}
} else {
#[cfg(target_os = "linux")]
if let Some(v) = v {
let playing = v.toggle();
if !playing {
// Paused: a good moment to remember where.
p.last_save = now - SAVE_EVERY;
}
}
Then::Nothing
}
}
Action::Left | Action::Right => {
p.next_focused = false;
let step = if repeat { 30.0 } else { 10.0 };
let base = p.seek_target.unwrap_or(p.position);
let max = p.duration.map(|d| (d - 2.0).max(0.0)).unwrap_or(f64::MAX);
let t = if a == Action::Left { base - step } else { base + step };
p.seek_target = Some(t.clamp(0.0, max));
p.seek_commit = now + Duration::from_millis(if repeat { 900 } else { 700 });
Then::Nothing
}
Action::Up => {
if p.next_focused {
p.next_focused = false;
} else {
p.panel = 1;
p.focus = [
p.audio.iter().position(|t| t.index == p.audio_on).unwrap_or(0),
p.subs_on.and_then(|s| p.subs.iter().position(|t| t.index == s)).map(|i| i + 1).unwrap_or(0),
SYNC_STEPS.iter().position(|ms| *ms == p.delay_ms).unwrap_or(6),
];
}
Then::Menus
}
Action::Down => {
if p.req.next.is_some() && p.duration.is_some_and(|d| d - p.position < 45.0) {
p.next_focused = true;
}
Then::Nothing
}
Action::Back => {
if p.next_focused {
p.next_focused = false;
Then::Nothing
} else if p.seek_target.is_some() {
p.seek_target = None;
Then::Nothing
} else {
Then::Leave
}
}
}
}
};
match then {
Then::Nothing => {}
Then::Menus => menus(c),
Then::Leave => leave(c),
Then::Next(req, ep) => play_next(c, &req, ep),
}
}
fn save_delay(c: &Controller, ms: i64) {
let st = c.state.borrow();
let Some(m) = st.player.as_ref().and_then(|p| p.media.as_ref()) else { return };
let (api, hash, file) = (st.api.clone(), m.hash.clone(), m.file);
task::background("audio delay", move || api.set_audio_delay(&hash, file, ms));
}
#[cfg(test)]
mod tests {
use super::*;
fn t(index: i32, lang: &str, title: &str, default: bool, forced: bool) -> Track {
Track { index, language: Some(lang.into()), title: (!title.is_empty()).then(|| title.into()), channels: None, default, forced }
}
#[test]
fn picks_tracks_like_the_web_app() {
let audio = [t(0, "en", "", true, false), t(1, "en", "Commentary", false, false), t(2, "hu", "", false, false)];
assert_eq!(pick_audio(&audio), Some(2));
assert_eq!(pick_audio(&audio[..2]), Some(0));
let subs = [t(0, "hu", "Forced", false, true), t(1, "hu", "", false, false), t(2, "en", "", true, false)];
// Hungarian audio: only the forced track.
assert_eq!(pick_subtitle(&subs, Some("hu"), "hu"), Some(0));
// English audio: full Hungarian subtitles.
assert_eq!(pick_subtitle(&subs, Some("en"), "hu"), Some(1));
assert_eq!(pick_subtitle(&subs[2..], Some("ja"), "hu"), Some(2));
assert_eq!(pick_subtitle(&[], Some("en"), "hu"), None);
}
}

608
src/screens/detail.rs Normal file
View File

@@ -0,0 +1,608 @@
//! A movie's or series' page (the web app's pages/Detail.tsx): hero with
//! Play / Continue / Next, My List, watched, versions; seasons as poster
//! cards, episodes as rows; nCore versions with their badges; cast.
use std::any::Any;
use std::collections::HashMap;
use crate::api::{EpisodeInfo, MediaType, ProgressRow, ReleaseLanguages, SeasonDetail, SourceCandidate, SourcesResult, TitleDetail, TitleState, TitleSummary};
use crate::app::{Cx, Look, Screen};
use crate::page::{C, Ch, Frame, Kind, L, Spec};
use crate::screens::Load;
use crate::screens::home::meta_line;
use crate::{format, player};
/// NFO languages load by themselves for the top rows only (one nCore page each).
const AUTO_LANGS: usize = 5;
type Ep = (i32, i32);
pub struct Detail {
kind: MediaType,
id: String,
summary: Option<TitleSummary>,
data: Load<TitleDetail>,
progress: Vec<ProgressRow>,
state: TitleState,
season: Option<i32>,
seasons: HashMap<i32, Load<SeasonDetail>>,
/// Versions open: the movie (None) or an episode.
open: Option<Option<Ep>>,
sources: HashMap<String, Load<SourcesResult>>,
langs: HashMap<i64, Load<ReleaseLanguages>>,
all_langs: bool,
started: bool,
}
fn source_key(ep: Option<Ep>) -> String {
ep.map(|(s, e)| format!("{s}:{e}")).unwrap_or_else(|| "movie".into())
}
impl Detail {
pub fn new(kind: MediaType, id: &str, summary: Option<TitleSummary>) -> Detail {
Detail {
kind,
id: id.to_string(),
summary,
data: Load::Loading,
progress: Vec::new(),
state: TitleState::default(),
season: None,
seasons: HashMap::new(),
open: None,
sources: HashMap::new(),
langs: HashMap::new(),
all_langs: false,
started: false,
}
}
fn load(&mut self, cx: &Cx) {
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.spawn::<Detail, _>(
move || {
let d = api.title(kind, &id);
let p = api.progress(kind, &id).unwrap_or_default();
let st = api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).cloned()).unwrap_or_default();
let hu = api.hungarian(&[(kind, id.clone())]).ok().and_then(|m| m.into_values().next()).flatten();
(d, p, st, hu)
},
|s, cx, (d, p, st, hu)| {
s.data = Load::from(d, cx);
s.progress = p;
s.state = st;
if let Some(d) = s.data.ready_mut() {
if d.summary.hu.is_none() {
d.summary.hu = hu;
}
}
if s.kind == MediaType::Tv && s.season.is_none() {
if let Some(d) = s.data.ready() {
let n = current_season(d, &s.progress);
s.season = Some(n);
s.load_season(cx, n);
}
}
},
);
}
fn load_season(&mut self, cx: &Cx, n: i32) {
if self.seasons.contains_key(&n) {
return;
}
self.seasons.insert(n, Load::Loading);
let (api, id) = (cx.api(), self.id.clone());
cx.spawn::<Detail, _>(move || api.season(&id, n), move |s, cx, r| {
s.seasons.insert(n, Load::from(r, cx));
});
}
fn reload_progress(&mut self, cx: &Cx) {
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.spawn::<Detail, _>(
move || (api.progress(kind, &id).unwrap_or_default(), api.list_status().ok().and_then(|m| m.get(&format!("{}:{}", kind.key(), id)).cloned())),
|s, _cx, (p, st)| {
s.progress = p;
if let Some(st) = st {
s.state = st;
}
},
);
}
fn load_sources(&mut self, cx: &Cx, ep: Option<Ep>) {
let key = source_key(ep);
if self.sources.contains_key(&key) {
self.load_langs(cx, &key);
return;
}
self.sources.insert(key.clone(), Load::Loading);
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.spawn::<Detail, _>(move || api.sources(kind, &id, ep), move |s, cx, r| {
s.sources.insert(key.clone(), Load::from(r, cx));
s.load_langs(cx, &key);
});
}
fn load_langs(&mut self, cx: &Cx, key: &str) {
let Some(list) = self.sources.get(key).and_then(|l| l.ready()) else { return };
let n = if self.all_langs { list.candidates.len() } else { AUTO_LANGS };
let ids: Vec<i64> = list.candidates.iter().take(n).map(|c| c.torrent.id).filter(|id| !self.langs.contains_key(id)).collect();
for nid in ids {
self.langs.insert(nid, Load::Loading);
let api = cx.api();
cx.spawn::<Detail, _>(move || api.release_languages(nid), move |s, cx, r| {
s.langs.insert(nid, Load::from(r, cx));
});
}
}
fn title(&self) -> String {
self.data.ready().map(|d| d.summary.title.clone()).or_else(|| self.summary.as_ref().map(|s| s.title.clone())).unwrap_or_default()
}
fn backdrop(&self) -> Option<String> {
self.data.ready().and_then(|d| d.summary.backdrop.clone()).or_else(|| self.summary.as_ref().and_then(|s| s.backdrop.clone()))
}
fn play(&self, cx: &Cx, ep: Option<Ep>, ncore: Option<i64>) {
let mut r = player::Request::title(self.kind, &self.id, self.title(), ep, self.backdrop());
r.pinned = ncore;
cx.play(r);
}
fn source_lines(&self, cx: &Cx, ep: Option<Ep>, out: &mut Vec<L>) {
let key = source_key(ep);
let id = |s: &str| format!("src:{key}:{s}");
match self.sources.get(&key) {
None | Some(Load::Loading) => out.push(L::text(id("loading"), "Verziók keresése az nCore-on…", "caption")),
Some(Load::Failed(e)) => out.push(L::text(id("error"), e.clone(), "bad")),
Some(Load::Ready(r)) if r.candidates.is_empty() => out.push(L::text(
id("none"),
format!("Ehhez most nincs verzió az nCore-on{}.", if r.searched_by.as_deref() == Some("name") { " (IMDb azonosító nélkül, név alapján kerestünk)" } else { "" }),
"label",
)),
Some(Load::Ready(r)) => {
for (i, c) in r.candidates.iter().enumerate() {
out.push(self.source_item(&key, i, c));
}
let rest = r.candidates.len().saturating_sub(AUTO_LANGS);
if rest > 0 && !self.all_langs {
out.push(L::chips(format!("srclangs:{key}"), "", vec![Ch::new("langs", "Hangsávok a többi verziónál is").icon("audio")]));
}
}
}
let _ = cx;
}
fn source_item(&self, key: &str, i: usize, c: &SourceCandidate) -> L {
let mut badges: Vec<String> = Vec::new();
if i == 0 {
badges.push("Ajánlott".into());
}
if let Some(local) = &c.local {
badges.push(
match local.as_str() {
"seeding" => "A szerveren, seedel",
"eligible" => "A szerveren",
"downloading" => "Letöltés alatt",
_ => "A szerveren",
}
.into(),
);
}
let nfo = self.langs.get(&c.torrent.id).and_then(|l| l.ready());
let subs: Vec<String> = nfo.map(|n| n.subs.clone()).unwrap_or_default();
if c.parsed.hungarian_audio {
badges.push("Magyar szinkron".into());
}
if c.parsed.hungarian_subs && !subs.iter().any(|s| s == "hu") {
badges.push("Magyar felirat".into());
}
if let Some(n) = nfo {
if !n.audio.is_empty() {
badges.push(format!("Hang: {}", n.audio.iter().map(|l| format::language(Some(l)).to_lowercase()).collect::<Vec<_>>().join(", ")));
}
if !subs.is_empty() {
badges.push(format!("Felirat: {}", subs.iter().map(|l| format::language(Some(l)).to_lowercase()).collect::<Vec<_>>().join(", ")));
}
if n.found && n.audio.is_empty() && subs.is_empty() {
badges.push("nyelv ismeretlen".into());
}
} else if matches!(self.langs.get(&c.torrent.id), Some(Load::Loading)) {
badges.push("NFO…".into());
}
if let Some(r) = c.parsed.resolution {
badges.push(format!("{}{}", if r >= 2160 { "4K".to_string() } else { format!("{r}p") }, if c.parsed.hdr { " HDR" } else { "" }));
}
badges.push(format!("{} seeder", c.torrent.seeders));
if c.torrent.freeleech {
badges.push("Freeleech".into());
}
let mut text = vec![crate::api::format_bytes(c.torrent.size)];
if c.pack {
text.push("évadcsomag".into());
}
if let Some(d) = &c.torrent.uploaded_at {
text.push(format::date(Some(d)));
}
let mut l = L::item(
format!("src:{key}:{}", c.torrent.id),
c.torrent.name.clone(),
badges.join(" · "),
text.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · "),
vec![Ch::new("play", if i == 0 { "Lejátszás ezzel (ajánlott)" } else { "Lejátszás ezzel" }).icon("play")],
);
l.indent = 40.0;
l
}
fn episode_item(&self, d: &TitleDetail, e: &EpisodeInfo, cx: &Cx) -> L {
let today = format::today();
let aired = e.air_date.as_deref().is_none_or(|a| a <= today.as_str());
let p = self.progress.iter().find(|p| p.season == e.season && p.episode == e.episode);
let done = p.is_some_and(|p| p.completed);
let mut meta = vec![format!("{}. rész", e.episode)];
let rt = format::runtime(e.runtime);
if !rt.is_empty() {
meta.push(rt);
}
if !aired {
meta.push(format!("érkezik: {}", format::date(e.air_date.as_deref())));
} else if let Some(a) = &e.air_date {
meta.push(format::date(Some(a)));
}
if done {
meta.push("megnézted".into());
}
let open = self.open == Some(Some((e.season, e.episode)));
let chips = if aired {
vec![
Ch::new("play", "Lejátszás").icon("play"),
Ch::new("versions", "Verziók").icon("list").active(open),
Ch::new("watched", if done { "Megnézve" } else { "Megnéztem" }).icon("check").active(done),
]
} else {
Vec::new()
};
let mut l = L::item(
format!("ep:{}:{}", e.season, e.episode),
e.name.clone().unwrap_or_else(|| format!("{}. rész", e.episode)),
meta.join(" · "),
e.overview.clone().unwrap_or_default(),
chips,
);
let still = cx.api().image(e.still.as_deref().or(d.summary.backdrop.as_deref()), false);
l = l.image(still);
l.progress = match p {
Some(p) if p.completed => 1.0,
Some(p) => p.duration.filter(|x| *x > 0.0).map(|x| (p.position / x).min(1.0) as f32).unwrap_or(-1.0),
None => -1.0,
};
if !aired {
l.tone = "dim".into();
}
l
}
}
/// Where Play goes, and its label (web: resumeTarget).
fn target(d: &TitleDetail, progress: &[ProgressRow]) -> (Option<Ep>, String) {
if d.summary.kind == MediaType::Movie {
let p = progress.iter().find(|r| r.season == 0 && r.episode == 0);
return (None, if p.is_some_and(|p| !p.completed && p.position > 60.0) { "Folytatás".into() } else { "Lejátszás".into() });
}
let latest = progress.iter().filter(|r| r.season > 0).max_by_key(|r| (r.season, r.episode));
let Some(latest) = latest else {
return (Some((d.seasons.first().map(|s| s.number).unwrap_or(1), 1)), "Lejátszás".into());
};
if !latest.completed {
return (Some((latest.season, latest.episode)), format!("Folytatás · {}", format::episode_code(latest.season, latest.episode)));
}
let season = d.seasons.iter().find(|s| s.number == latest.season);
let next = if season.is_some_and(|s| latest.episode < s.episode_count) {
Some((latest.season, latest.episode + 1))
} else if d.seasons.iter().any(|s| s.number == latest.season + 1) {
Some((latest.season + 1, 1))
} else {
None
};
match next {
Some((s, e)) => (Some((s, e)), format!("Következő · {}", format::episode_code(s, e))),
None => (Some((latest.season, latest.episode)), "Újra".into()),
}
}
/// The season you are in (web: currentSeason).
fn current_season(d: &TitleDetail, progress: &[ProgressRow]) -> i32 {
let first = d.seasons.first().map(|s| s.number).unwrap_or(1);
let last = progress.iter().filter(|r| r.season > 0).map(|r| r.season).max().unwrap_or(0);
if last == 0 {
return first;
}
let Some(s) = d.seasons.iter().find(|x| x.number == last) else { return last };
let watched = progress.iter().filter(|r| r.season == last && r.completed).count() as i32;
if watched < s.aired() {
return last;
}
d.seasons.iter().find(|x| x.number > last && x.aired() > 0).map(|x| x.number).unwrap_or(last)
}
impl Screen for Detail {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let api = cx.api();
let mut lines = Vec::new();
let d = self.data.ready().cloned();
let summary = d.as_ref().map(|d| d.summary.clone()).or_else(|| self.summary.clone());
// ---- hero ----
let mut hero = L::new("hero", Kind::Hero);
if let Some(t) = &summary {
hero.title = t.title.clone();
hero.logo = api.image(t.logo.as_deref(), true);
hero.subtitle = t.original_title.clone().filter(|o| *o != t.title).unwrap_or_default();
let extra = match &d {
Some(d) if d.summary.kind == MediaType::Movie => format::runtime(d.runtime),
Some(d) => d.number_of_seasons.filter(|n| *n > 0).map(|n| format!("{n} évad")).unwrap_or_default(),
None => String::new(),
};
hero.meta = meta_line(t, &extra);
let overview = t.overview.clone().unwrap_or_default();
hero.text = match d.as_ref().and_then(|d| d.tagline.clone()) {
Some(tag) if !tag.is_empty() => format!("{tag}\n{overview}"),
_ => overview,
};
}
if let Some(d) = &d {
if let Some(n) = d.next_episode_to_air.as_ref().filter(|_| d.summary.kind == MediaType::Tv) {
hero.extra = format!("Új rész érkezik: {} · {}", format::episode_code(n.season, n.episode), format::date_long(n.air_date.as_deref()));
}
let (_, label) = target(d, &self.progress);
hero.chips.push(Ch::new("play", label).icon("play").tone("primary"));
} else {
hero.chips.push(Ch::new("play", "Lejátszás").icon("play").tone("primary").enabled(false));
}
hero.chips.push(Ch::new("list", if self.state.listed { "Listámon" } else { "Listám" }).icon(if self.state.listed { "check" } else { "plus" }).active(self.state.listed));
if self.kind == MediaType::Movie {
hero.chips.push(Ch::new("watched", if self.state.watched { "Megnézve" } else { "Megnéztem" }).icon("check").active(self.state.watched));
hero.chips.push(Ch::new("versions", "Verziók").icon("list").active(self.open == Some(None)));
if let Some(p) = self.progress.iter().find(|r| r.season == 0 && r.episode == 0 && !r.completed && r.position > 60.0) {
if let Some(dur) = p.duration.filter(|d| *d > 0.0) {
hero.progress = (p.position / dur).min(1.0) as f32;
hero.note = format!("még {} perc", ((dur - p.position) / 60.0).round().max(1.0) as i64);
}
}
}
lines.push(hero);
if let Some(st) = self.data.status("status") {
lines.push(st);
}
// ---- movie: versions ----
if self.kind == MediaType::Movie && self.open == Some(None) {
lines.push(L::heading("versions-h", "Verziók az nCore-on").sub("A Lejátszás magától a legjobb verziót választja; itt kézzel is dönthetsz."));
self.source_lines(cx, None, &mut lines);
lines.push(L::chips("versions-close", "", vec![Ch::new("close", "Bezárás").icon("close")]));
}
// ---- series: seasons and episodes ----
if let (Some(d), MediaType::Tv) = (&d, self.kind) {
if !d.seasons.is_empty() {
let season = self.season.unwrap_or(1);
lines.push(L::heading("eps-h", "Epizódok").sub(if d.seasons.len() > 1 { format!("{} évad", d.seasons.len()) } else { String::new() }));
let cards: Vec<C> = d
.seasons
.iter()
.map(|s| {
let watched = self.progress.iter().filter(|p| p.season == s.number && p.completed).count() as i32;
let aired = s.aired();
let complete = aired > 0 && watched >= aired;
let poster = s.poster.as_deref().or(d.summary.poster.as_deref());
let mut c = C::new(format!("season:{}", s.number), s.label(), api.image(poster, false));
c.caption = s.label();
c.detail = format!(
"{}{}",
if watched > 0 { format!("{} / {aired} rész", watched.min(aired)) } else { format!("{} rész", s.episode_count) },
s.air_date.as_deref().filter(|a| a.len() >= 4).map(|a| format!(" · {}", &a[..4])).unwrap_or_default()
);
if s.poster.is_none() {
c.big = s.number.to_string();
}
if complete {
c.mark = "check";
} else if watched > 0 && aired > 0 {
c.progress = watched as f32 / aired as f32;
}
c.current = s.number == season;
c
})
.collect();
let mut sl = L::cards("seasons", "", "season", cards).captions();
sl.indent = 0.0;
lines.push(sl);
let current = d.seasons.iter().find(|s| s.number == season);
match self.seasons.get(&season) {
None | Some(Load::Loading) => lines.push(L::text("eps-loading", "Epizódok betöltése…", "caption")),
Some(Load::Failed(e)) => lines.push(L::notice("eps-error", "bad", "Az epizódok nem töltődtek be", e.clone())),
Some(Load::Ready(sd)) => {
let today = format::today();
let aired: Vec<&EpisodeInfo> = sd.episodes.iter().filter(|e| e.air_date.as_deref().is_none_or(|a| a <= today.as_str())).collect();
let done = aired.iter().filter(|e| self.progress.iter().any(|p| p.season == e.season && p.episode == e.episode && p.completed)).count();
let all = !aired.is_empty() && done == aired.len();
let mut h = L::heading("season-h", current.map(|s| s.label()).unwrap_or_else(|| format!("{season}. évad")));
if !aired.is_empty() {
h.subtitle = format!("{done} / {} rész megnézve", aired.len());
}
lines.push(h);
if !aired.is_empty() {
lines.push(L::chips(
"season-watched",
"",
vec![Ch::new("all", if all { "Évad megnézettségének törlése" } else { "Egész évad megnézve" }).icon("check").active(all)],
));
}
for e in &sd.episodes {
lines.push(self.episode_item(d, e, cx));
if self.open == Some(Some((e.season, e.episode))) {
self.source_lines(cx, Some((e.season, e.episode)), &mut lines);
}
}
}
}
}
}
// ---- cast ----
if let Some(d) = &d {
if !d.cast.is_empty() || !d.directors.is_empty() {
lines.push(L::heading("cast-h", "Szereplők és alkotók"));
if !d.directors.is_empty() {
lines.push(L::text("directors", format!("{}: {}", if d.directors.len() > 1 { "Rendezők" } else { "Rendező" }, d.directors.join(", ")), "label"));
}
if !d.cast.is_empty() {
lines.push(L::text("cast", format!("Szereplők: {}", d.cast.iter().take(14).cloned().collect::<Vec<_>>().join(", ")), "label"));
}
}
}
Spec { lines, frame: Frame::default() }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
match (line, item) {
("hero", "play") => {
if let Some(d) = self.data.ready() {
let (ep, _) = target(d, &self.progress);
self.play(cx, ep, None);
}
}
("hero", "list") => {
let on = !self.state.listed;
self.state.listed = on;
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.call::<Detail>("Listám", move || api.set_listed(kind, &id, on), |_, _| {});
cx.toast(if on { "Mentve a könyvtáradba" } else { "Eltávolítva a könyvtáradból" });
}
("hero", "watched") => {
let on = !self.state.watched;
self.state.watched = on;
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &[(0, 0)], on), |s, cx| s.reload_progress(cx));
}
("hero", "versions") => {
if self.open == Some(None) {
self.open = None;
} else {
self.open = Some(None);
self.load_sources(cx, None);
cx.focus_on("versions-h", 0);
}
}
("versions-close", _) => {
self.open = None;
cx.focus_on("hero", 3);
}
("seasons", s) => {
if let Some(n) = s.strip_prefix("season:").and_then(|n| n.parse::<i32>().ok()) {
self.season = Some(n);
self.open = None;
self.load_season(cx, n);
}
}
("season-watched", _) => {
let Some(season) = self.season else { return };
let Some(sd) = self.seasons.get(&season).and_then(|l| l.ready()) else { return };
let today = format::today();
let eps: Vec<Ep> = sd.episodes.iter().filter(|e| e.air_date.as_deref().is_none_or(|a| a <= today.as_str())).map(|e| (e.season, e.episode)).collect();
let all = eps.iter().all(|(s, e)| self.progress.iter().any(|p| p.season == *s && p.episode == *e && p.completed));
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &eps, !all), |s, cx| s.reload_progress(cx));
}
(l, act) if l.starts_with("ep:") => {
let mut p = l[3..].split(':');
let (Some(s), Some(e)) = (p.next().and_then(|v| v.parse().ok()), p.next().and_then(|v| v.parse().ok())) else { return };
match act {
"play" => self.play(cx, Some((s, e)), None),
"versions" => {
if self.open == Some(Some((s, e))) {
self.open = None;
} else {
self.open = Some(Some((s, e)));
self.load_sources(cx, Some((s, e)));
}
}
"watched" => {
let done = self.progress.iter().any(|p| p.season == s && p.episode == e && p.completed);
let (api, kind, id) = (cx.api(), self.kind, self.id.clone());
cx.call::<Detail>("Megnézve", move || api.mark_watched(kind, &id, &[(s, e)], !done), |s, cx| s.reload_progress(cx));
}
_ => {}
}
}
(l, "langs") if l.starts_with("srclangs:") => {
self.all_langs = true;
let key = l["srclangs:".len()..].to_string();
self.load_langs(cx, &key);
}
(l, "play") if l.starts_with("src:") => {
// src:<key>:<ncore id>, key = "movie" or "s:e"
let rest = &l[4..];
let (key, nid) = rest.rsplit_once(':').unwrap_or((rest, ""));
let Ok(nid) = nid.parse::<i64>() else { return };
let ep = if key == "movie" {
None
} else {
let mut p = key.split(':');
p.next().and_then(|v| v.parse().ok()).zip(p.next().and_then(|v| v.parse().ok()))
};
self.play(cx, ep, Some(nid));
}
_ => {}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, _item: &str) {
let url = cx.api().image(self.backdrop().as_deref(), false);
cx.backdrop(&url, Look::Sharp, &format!("detail:{}", self.id));
}
fn shown(&mut self, cx: &Cx) {
self.reload_progress(cx);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
fn detail(seasons: &[(i32, i32)]) -> TitleDetail {
let json = format!(
r#"{{"type":"tv","id":"tt1","title":"X","genres":[],"seasons":[{}]}}"#,
seasons.iter().map(|(n, c)| format!(r#"{{"number":{n},"episodeCount":{c},"airedCount":{c}}}"#)).collect::<Vec<_>>().join(",")
);
serde_json::from_str(&json).unwrap()
}
fn row(s: i32, e: i32, completed: bool) -> ProgressRow {
ProgressRow { season: s, episode: e, position: 100.0, duration: Some(1000.0), completed }
}
#[test]
fn resume_targets() {
let d = detail(&[(1, 3), (2, 2)]);
assert_eq!(target(&d, &[]), (Some((1, 1)), "Lejátszás".into()));
assert_eq!(target(&d, &[row(1, 2, false)]).1, "Folytatás · S01E02");
assert_eq!(target(&d, &[row(1, 3, true)]), (Some((2, 1)), "Következő · S02E01".into()));
assert_eq!(target(&d, &[row(2, 2, true)]).1, "Újra");
assert_eq!(current_season(&d, &[row(1, 1, true), row(1, 2, true), row(1, 3, true)]), 2);
assert_eq!(current_season(&d, &[row(1, 1, true)]), 1);
}
}

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

@@ -0,0 +1,283 @@
//! Kezdőlap: the admin's setup checklist, the spotlight (popular movies and
//! series taking turns), "Folytasd, ahol abbahagytad", the server's rows.
use std::any::Any;
use std::collections::HashMap;
use std::time::Instant;
use crate::api::{HomeData, MediaType, NcoreStatus, TitleState, TitleSummary, VpnStatus};
use crate::app::{Cx, Look, Screen};
use crate::page::{Ch, Frame, Kind, L, Spec};
use crate::screens::{self, Load, continue_card, row_copy, title_cards};
use crate::{format, player};
const DWELL_SECS: u64 = 9;
pub struct Home {
data: Load<HomeData>,
states: HashMap<String, TitleState>,
setup: Option<(VpnStatus, NcoreStatus)>,
/// The server answered 409: nothing can play until VPN / nCore are set up.
needs_setup: bool,
spotlight: Vec<TitleSummary>,
index: usize,
since: Instant,
hero_focused: bool,
loaded: bool,
}
impl Home {
pub fn new() -> Home {
Home {
data: Load::Loading,
states: HashMap::new(),
setup: None,
needs_setup: false,
spotlight: Vec::new(),
index: 0,
since: Instant::now(),
hero_focused: true,
loaded: false,
}
}
fn load(&mut self, cx: &Cx) {
let api = cx.api();
let admin = cx.user().is_admin;
cx.spawn::<Home, _>(
move || {
let home = api.home();
let states = api.list_status().unwrap_or_default();
let setup = if admin { api.vpn().ok().zip(api.ncore().ok()) } else { None };
(home, states, setup)
},
|s, cx, (home, states, setup)| {
s.needs_setup = matches!(&home, Err(e) if crate::api::status_of(e) == Some(409));
s.data = if s.needs_setup { Load::Ready(HomeData { rows: Vec::new(), continue_watching: Vec::new() }) } else { Load::from(home, cx) };
s.states = states;
s.setup = setup;
if let Some(d) = s.data.ready() {
s.spotlight = spotlight(&d.rows);
s.index = s.index.min(s.spotlight.len().saturating_sub(1));
}
},
);
}
fn current(&self) -> Option<&TitleSummary> {
self.spotlight.get(self.index)
}
fn find(&self, key: &str) -> Option<TitleSummary> {
let d = self.data.ready()?;
if let Some((kind, id)) = screens::parse_title_key(key) {
return d.rows.iter().flat_map(|r| r.items.iter()).chain(self.spotlight.iter()).find(|t| t.kind == kind && t.id == id).cloned();
}
if let Some((kind, id, _)) = screens::parse_continue(key) {
return d.continue_watching.iter().map(|c| &c.title).find(|t| t.kind == kind && t.id == id).cloned();
}
None
}
}
/// Popular movies and series, alternating, that have artwork worth showing.
fn spotlight(rows: &[crate::api::HomeRow]) -> Vec<TitleSummary> {
let pick = |id: &str| -> Vec<TitleSummary> { rows.iter().find(|r| r.id == id).map(|r| r.items.iter().filter(|t| t.backdrop.is_some()).cloned().collect()).unwrap_or_default() };
let (movies, series) = (pick("popular-movie"), pick("popular-tv"));
let mut out = Vec::new();
let mut i = 0;
while out.len() < 6 && (i < movies.len() || i < series.len()) {
if let Some(m) = movies.get(i) {
out.push(m.clone());
}
if let Some(s) = series.get(i).filter(|_| out.len() < 6) {
out.push(s.clone());
}
i += 1;
}
if out.is_empty() {
out.extend(rows.first().map(|r| r.items.iter().filter(|t| t.backdrop.is_some()).take(6).cloned().collect::<Vec<_>>()).unwrap_or_default());
}
out
}
pub fn hu_text(t: &TitleSummary) -> &'static str {
match t.hu {
Some(h) if h.dub => "Magyar szinkron",
Some(h) if h.sub => "Magyar felirat",
_ => "",
}
}
/// "★ 7.8 · 2024 · Film · Dráma, Krimi · Magyar szinkron"
pub fn meta_line(t: &TitleSummary, extra: &str) -> String {
let mut p: Vec<String> = Vec::new();
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
p.push(format!("★ {}", format::rating(r)));
}
if let Some(y) = t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())) {
p.push(y);
}
p.push(t.kind.label().into());
if !extra.is_empty() {
p.push(extra.into());
}
if !t.genres.is_empty() {
p.push(t.genres.iter().take(2).map(|g| format::genre(g)).collect::<Vec<_>>().join(", "));
}
let hu = hu_text(t);
if !hu.is_empty() {
p.push(hu.into());
}
p.join(" · ")
}
impl Screen for Home {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.loaded {
self.loaded = true;
self.load(cx);
}
let api = cx.api();
let mut lines = Vec::new();
// Setup checklist (admin): VPN and nCore.
if let Some((vpn, ncore)) = &self.setup {
let vpn_ok = vpn.traffic.path == "vpn";
let ncore_ok = ncore.configured && ncore.circuit.state == "ok";
let left = [vpn_ok, ncore_ok].iter().filter(|b| !**b).count();
if left > 0 || self.needs_setup {
let title = match left {
0 => "Minden készen áll".to_string(),
1 => "Még egy lépés, és indulhat a filmezés".to_string(),
_ => "Még két lépés, és indulhat a filmezés".to_string(),
};
lines.push(L::notice("setup", "info", title, "Tunnel nélkül semmi nem megy ki a szerverről, a katalógus sem tölt be. Az nCore fiókból jönnek a filmek és a sorozatok."));
lines.push(L::checks(
"setup-checks",
vec![
(vpn_ok as i32, "WireGuard tunnel csatlakoztatva".into(), vpn.traffic.reason.clone().unwrap_or_default()),
(ncore_ok as i32, "nCore fiók megadva".into(), ncore.circuit.message.clone().unwrap_or_default()),
],
));
let mut chips = Vec::new();
if !vpn_ok {
chips.push(Ch::new("vpn", "VPN beállítása").tone("primary"));
}
if !ncore_ok {
chips.push(Ch::new("ncore", "nCore fiók megadása").tone("primary"));
}
if !chips.is_empty() {
lines.push(L::chips("setup-go", "", chips));
}
}
} else if self.needs_setup {
lines.push(L::notice("setup", "info", "A szerver még nincs kész", "A VPN-t és az nCore fiókot az admin állítja be. Amint kész, itt megjelennek a filmek és a sorozatok."));
}
// Spotlight.
if let Some(t) = self.current() {
let listed = self.states.get(&format!("{}:{}", t.kind.key(), t.id)).is_some_and(|s| s.listed);
let mut hero = L::new("hero", Kind::Hero);
hero.style = "KIEMELT TARTALOM".into();
hero.title = t.title.clone();
hero.logo = api.image(t.logo.as_deref(), true);
hero.meta = meta_line(t, "");
hero.text = t.overview.clone().unwrap_or_default();
hero.subtitle = format!("{} / {}", self.index + 1, self.spotlight.len());
hero.chips = vec![
Ch::new("play", if t.kind == MediaType::Movie { "Lejátszás" } else { "Epizódok" }).icon("play").tone("primary"),
Ch::new("info", "További infók").icon("info"),
Ch::new("list", "").icon(if listed { "check" } else { "plus" }).active(listed),
];
lines.push(hero);
}
if let Some(st) = self.data.status("status") {
lines.push(st);
}
if let Some(d) = self.data.ready() {
if !d.continue_watching.is_empty() {
lines.push(L::cards("continue", "Folytasd, ahol abbahagytad", "landscape", d.continue_watching.iter().map(|c| continue_card(&api, c)).collect()).captions());
}
for r in &d.rows {
let (title, note) = row_copy(&r.id).map(|(t, n)| (t.to_string(), n.to_string())).unwrap_or((r.title.clone(), String::new()));
lines.push(L::cards(format!("row:{}", r.id), title, "poster", title_cards(&api, &r.items, &self.states)).sub(note));
}
}
Spec { lines, frame: Frame { nav: Some(0), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
match (line, item) {
("setup-go", "vpn") => cx.c.open_settings("vpn"),
("setup-go", "ncore") => cx.c.open_settings("ncore"),
("hero", "play") => {
let Some(t) = self.current().cloned() else { return };
if t.kind == MediaType::Movie {
cx.play(player::Request::title(t.kind, &t.id, t.title.clone(), None, t.backdrop.clone()));
} else {
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
}
}
("hero", "info") => {
if let Some(t) = self.current().cloned() {
cx.push(Box::new(screens::detail::Detail::new(t.kind, &t.id, Some(t))));
}
}
("hero", "list") => {
let Some(t) = self.current().cloned() else { return };
let key = format!("{}:{}", t.kind.key(), t.id);
let on = !self.states.get(&key).is_some_and(|s| s.listed);
self.states.entry(key).or_default().listed = on;
let api = cx.api();
cx.call::<Home>("Listám", move || api.set_listed(t.kind, &t.id, on), |_, _| {});
cx.toast(if on { "Hozzáadva a listádhoz" } else { "Eltávolítva a listádról" });
}
(_, key) => {
let found = self.find(key);
screens::open_card(cx, key, |_| found.clone());
}
}
}
fn focus(&mut self, cx: &Cx, line: &str, item: &str) {
self.hero_focused = line == "hero";
self.since = Instant::now();
if self.hero_focused {
if let Some(t) = self.current() {
let url = cx.api().image(t.backdrop.as_deref(), false);
cx.backdrop(&url, Look::Sharp, &format!("spot:{}", t.id));
}
return;
}
match self.find(item) {
Some(t) => {
let url = cx.api().image(t.backdrop.as_deref(), false);
cx.backdrop(&url, Look::Soft, item);
}
None => cx.backdrop("", Look::Soft, ""),
}
}
fn tick(&mut self, cx: &Cx) {
// The spotlight turns after a while without a key press (any focus
// move restarts the clock): Play always plays what it shows.
if self.spotlight.len() >= 2 && self.since.elapsed().as_secs() >= DWELL_SECS {
self.since = Instant::now();
self.index = (self.index + 1) % self.spotlight.len();
cx.refresh();
if self.hero_focused {
self.focus(cx, "hero", "");
}
}
}
fn shown(&mut self, cx: &Cx) {
self.load(cx);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

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

@@ -0,0 +1,210 @@
//! The browsing screens. Each one describes its page as lines (src/page.rs)
//! and reacts to OK; see app::Screen.
pub mod anime_detail;
pub mod anime_hub;
pub mod detail;
pub mod home;
pub mod mylist;
pub mod search;
pub mod settings;
pub mod source;
use std::collections::HashMap;
use crate::api::{AnimeSummary, Api, ContinueItem, MediaType, TitleState, TitleSummary};
use crate::app::{Cx, Screen};
use crate::format;
use crate::page::{C, L};
/// The screen of a top navigation section.
pub fn section(n: usize) -> Box<dyn Screen> {
match n {
1 => Box::new(source::Source::new(MediaType::Movie)),
2 => Box::new(source::Source::new(MediaType::Tv)),
3 => Box::new(anime_hub::AnimeHub::new()),
4 => Box::new(mylist::MyList::new()),
5 => Box::new(search::Search::new()),
6 => 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>, cx: &Cx) -> Load<T> {
match r {
Ok(t) => Load::Ready(t),
Err(e) => {
if crate::api::is_unauthenticated(&e) {
cx.error("", &e);
}
Load::Failed(crate::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,
}
}
}
/// "t:movie:tt0133093"
pub fn title_key(kind: MediaType, id: &str) -> String {
format!("t:{}:{}", kind.key(), id)
}
pub fn parse_title_key(key: &str) -> Option<(MediaType, String)> {
let mut p = key.splitn(3, ':');
if p.next()? != "t" {
return None;
}
let kind = match p.next()? {
"movie" => MediaType::Movie,
"tv" => MediaType::Tv,
_ => return None,
};
Some((kind, p.next()?.to_string()))
}
/// A movie / series card (poster); `state` adds the watched marks.
pub fn title_card(api: &Api, t: &TitleSummary, state: Option<&TitleState>) -> C {
let mut c = C::new(title_key(t.kind, &t.id), t.title.clone(), api.image(t.poster.as_deref(), false));
c.caption = t.title.clone();
let mut detail = vec![t.year_label.clone().or_else(|| t.year.map(|y| y.to_string())).unwrap_or_default(), t.kind.label().to_string()];
if let Some(r) = t.rating.filter(|r| *r > 0.0) {
detail.push(format!("★ {}", format::rating(r)));
}
c.detail = detail.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
if let Some(hu) = t.hu {
if hu.dub {
c.badge = "Szinkron".into();
c.badge_tone = "dub";
} else if hu.sub {
c.badge = "Felirat".into();
c.badge_tone = "sub";
}
}
if let Some(s) = state {
if s.watched {
c.mark = "check";
} else if s.watched_episodes > 0 && t.kind == MediaType::Tv {
c.detail = format!("{} · {} rész megnézve", c.detail, s.watched_episodes);
}
}
c
}
pub fn title_cards(api: &Api, items: &[TitleSummary], states: &HashMap<String, TitleState>) -> Vec<C> {
items.iter().map(|t| title_card(api, t, states.get(&format!("{}:{}", t.kind.key(), t.id)))).collect()
}
/// "Folytatás" card: landscape art, progress, "S01E02 · még 12 perc".
pub fn continue_card(api: &Api, item: &ContinueItem) -> C {
let t = &item.title;
let ep = item.season.zip(item.episode).filter(|(s, _)| *s > 0 && t.kind == MediaType::Tv);
let id = match ep {
Some((s, e)) => format!("c:{}:{}:{s}:{e}", t.kind.key(), t.id),
None => format!("c:{}:{}", t.kind.key(), t.id),
};
let art = t.backdrop.as_deref().or(t.poster.as_deref());
let mut c = C::new(id, t.title.clone(), api.image(art, false));
c.caption = t.title.clone();
let left = item.duration.map(|d| ((d - item.position) / 60.0).round().max(0.0) as i64);
let what = ep.map(|(s, e)| format::episode_code(s, e)).unwrap_or_else(|| "Film".into());
c.detail = match left {
Some(l) if l > 0 => format!("{what} · még {l} perc"),
_ => what,
};
c.progress = item.duration.filter(|d| *d > 0.0).map(|d| (item.position / d).min(1.0) as f32).unwrap_or(-1.0);
c
}
/// Parses a "Folytatás" card id: (type, id, episode).
pub fn parse_continue(key: &str) -> Option<(MediaType, String, Option<(i32, i32)>)> {
let p: Vec<&str> = key.split(':').collect();
if p.first() != Some(&"c") || p.len() < 3 {
return None;
}
let kind = if p[1] == "tv" { MediaType::Tv } else { MediaType::Movie };
let ep = if p.len() >= 5 { p[3].parse().ok().zip(p[4].parse().ok()) } else { None };
Some((kind, p[2].to_string(), ep))
}
/// An anime card (cover).
pub fn anime_card(api: &Api, a: &AnimeSummary) -> C {
let mut c = C::new(format!("a:{}", a.id), a.title.name(), api.image(a.cover_image.as_deref(), false));
c.caption = a.title.name();
let mut d = vec![format::anime_season(a.season.as_deref(), a.season_year), format::anime_format(a.format.as_deref())];
if let Some(s) = a.average_score.filter(|s| *s > 0.0) {
d.push(format!("★ {}", format::anime_score(s)));
}
c.detail = d.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
c
}
pub fn parse_anime_key(key: &str) -> Option<i64> {
key.strip_prefix("a:")?.split(':').next()?.parse().ok()
}
/// The web app's names for the server's home rows: (title, note).
pub fn row_copy(id: &str) -> Option<(&'static str, &'static str)> {
Some(match id {
"popular-movie" => ("Most felkapott", "Népszerű filmek"),
"ncore-movie" => ("Épp most érkezett", "Friss filmek az nCore-on"),
"ncore-tv" => ("Friss részek, friss évadok", "Új sorozat-feltöltések az nCore-on"),
"popular-tv" => ("Sorozatok, amiket nem tudsz majd letenni", "Népszerű sorozatok"),
"new-movie" => ("Idén mutatták be", "Idei filmek"),
"featured-movie" => ("Kihagyhatatlan filmek", "Kiemelt filmek"),
"featured-tv" => ("Sorozatok, amikbe beleszeretsz", "Kiemelt sorozatok"),
_ => return None,
})
}
/// Opens the page of a card id ("t:…", "c:…", "a:…"); true if it was one.
pub fn open_card(cx: &Cx, key: &str, find: impl Fn(&str) -> Option<TitleSummary>) -> bool {
if let Some((kind, id)) = parse_title_key(key) {
cx.push(Box::new(detail::Detail::new(kind, &id, find(key))));
return true;
}
if let Some((kind, id, ep)) = parse_continue(key) {
// "Folytatás" plays right away, where it stopped.
let summary = find(key);
cx.play(crate::player::Request::title(kind, &id, summary.as_ref().map(|s| s.title.clone()).unwrap_or_default(), ep, summary.and_then(|s| s.backdrop)));
return true;
}
if let Some(id) = key.strip_prefix("ac:").and_then(|r| r.split(':').next()).and_then(|v| v.parse::<i64>().ok()) {
let ep: i32 = key.rsplit(':').next().and_then(|v| v.parse().ok()).unwrap_or(1);
cx.play(crate::player::Request::anime(id, String::new(), ep, None));
return true;
}
if let Some(id) = parse_anime_key(key) {
cx.push(Box::new(anime_detail::AnimeDetail::new(id)));
return true;
}
false
}

559
src/screens/source.rs Normal file
View File

@@ -0,0 +1,559 @@
//! Filmek / Sorozatok: Ajánlott, Könyvtáram, Böngészés (as in the web app's
//! pages/Browse.tsx).
use std::any::Any;
use std::collections::{HashMap, HashSet};
use crate::api::{ContinueItem, Genre, ListItem, MediaType, TitleState, TitleSummary};
use crate::app::{Cx, Look, Screen};
use crate::page::{C, Ch, Frame, GRID, L, Spec, grid_lines};
use crate::screens::{self, Load, continue_card, title_card};
/// Pages in a row that matched nothing before loading stops and asks.
const MAX_EMPTY_STREAK: usize = 3;
const DECADES: [(&str, Option<i32>, Option<i32>); 6] = [
("2020-as évek", Some(2020), None),
("2010-es évek", Some(2010), Some(2019)),
("2000-es évek", Some(2000), Some(2009)),
("1990-es évek", Some(1990), Some(1999)),
("1980-as évek", Some(1980), Some(1989)),
("Régebbi", None, Some(1979)),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tab {
Recommended,
Mine,
All,
}
struct Entry {
title: TitleSummary,
saved: bool,
watched: bool,
last: Option<String>,
added: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
struct Filters {
sort: &'static str,
genre: Option<String>,
yf: Option<i32>,
yt: Option<i32>,
rf: Option<f64>,
rt: Option<f64>,
}
impl Filters {
fn filtered(&self) -> bool {
self.genre.is_some() || self.yf.is_some() || self.yt.is_some() || self.rf.is_some() || self.rt.is_some()
}
fn custom(&self) -> usize {
(self.yf.is_some() || self.yt.is_some()) as usize + (self.rf.is_some() || self.rt.is_some()) as usize
}
}
#[derive(Default)]
struct Catalog {
items: Vec<TitleSummary>,
page: u32,
cursor: Option<String>,
has_more: bool,
loading: bool,
/// Pages loaded; empty ones since `resume_from` count towards the stop.
pages: Vec<usize>,
resume_from: usize,
error: Option<String>,
generation: u64,
}
pub struct Source {
kind: MediaType,
tab: Tab,
started: bool,
genres: Load<Vec<Genre>>,
continuing: Vec<ContinueItem>,
library: Load<Vec<Entry>>,
states: HashMap<String, TitleState>,
rails: Vec<(String, String, String, Load<Vec<TitleSummary>>)>,
rails_started: bool,
// Könyvtáram
show: &'static str,
lib_sort: &'static str,
// Böngészés
f: Filters,
open: bool,
cat: Catalog,
}
fn this_year() -> i32 {
crate::format::today()[0..4].parse().unwrap_or(2026)
}
impl Source {
pub fn new(kind: MediaType) -> Source {
Source {
kind,
tab: Tab::Recommended,
started: false,
genres: Load::Loading,
continuing: Vec::new(),
library: Load::Loading,
states: HashMap::new(),
rails: Vec::new(),
rails_started: false,
show: "all",
lib_sort: "recent",
f: Filters { sort: "popularity", genre: None, yf: None, yt: None, rf: None, rt: None },
open: false,
cat: Catalog::default(),
}
}
fn copy(&self) -> (&'static str, &'static str, &'static str, &'static str, &'static str, &'static str) {
match self.kind {
MediaType::Movie => ("Filmek", "Népszerű most", "A legjobbra értékelt filmek", "Idei bemutatók", "Még egy filmet sem mentettél", "Egy film oldalán a + gombbal mentheted el, és itt vár rád, amikor ráérsz."),
MediaType::Tv => ("Sorozatok", "Népszerű sorozatok most", "A legjobbra értékelt sorozatok", "Idén indult", "Még egy sorozatot sem mentettél", "Egy sorozat oldalán a + gombbal mentheted el. Amit elkezdesz, magától is ide kerül."),
}
}
fn start(&mut self, cx: &Cx) {
let (api, kind) = (cx.api(), self.kind);
cx.spawn::<Source, _>(
move || {
let genres = api.genres(kind);
let cont = api.continue_watching().unwrap_or_default();
let mine = api.my_list();
let history = api.history().unwrap_or_default();
let states = api.list_status().unwrap_or_default();
(genres, cont, mine, history, states)
},
move |s, cx, (genres, cont, mine, history, states)| {
s.genres = Load::from(genres, cx);
s.continuing = cont.into_iter().filter(|c| c.title.kind == s.kind).collect();
s.states = states;
s.library = match mine {
Ok(mine) => Load::Ready(library(s.kind, mine, history)),
Err(e) => Load::Failed(crate::api::describe(&e)),
};
s.start_rails(cx);
},
);
}
fn start_rails(&mut self, cx: &Cx) {
if self.rails_started {
return;
}
let Some(genres) = self.genres.ready().cloned() else { return };
self.rails_started = true;
let (_, popular, rating, fresh, _, _) = self.copy();
let year = this_year();
let mut defs: Vec<(String, String, &'static str, Option<String>, Option<i32>)> = vec![
("popularity".into(), popular.into(), "popularity", None, None),
("rating".into(), rating.into(), "rating", None, None),
("new".into(), fresh.into(), "new", None, Some(year)),
];
for g in genres.iter().take(5) {
defs.push((format!("g:{}", g.id), g.name.clone(), "popularity", Some(g.id.clone()), None));
}
for (id, title, sort, genre, yr) in defs {
self.rails.push((id.clone(), title, genre.clone().unwrap_or_default(), Load::Loading));
let (api, kind) = (cx.api(), self.kind);
cx.spawn::<Source, _>(
move || api.browse(kind, sort, genre.as_deref(), yr, (None, None), (None, None), 1, None),
move |s, cx, r| {
if let Some(rail) = s.rails.iter_mut().find(|x| x.0 == id) {
rail.3 = Load::from(r.map(|p| p.items), cx);
}
},
);
}
}
fn reload_catalog(&mut self, cx: &Cx) {
self.cat = Catalog { generation: self.cat.generation + 1, has_more: true, ..Catalog::default() };
self.next_page(cx);
}
fn next_page(&mut self, cx: &Cx) {
if self.cat.loading || !self.cat.has_more || self.paused() {
return;
}
self.cat.loading = true;
let (api, kind, f, page, cursor, generation) = (cx.api(), self.kind, self.f.clone(), self.cat.page + 1, self.cat.cursor.clone(), self.cat.generation);
cx.spawn::<Source, _>(
move || api.browse(kind, f.sort, f.genre.as_deref(), None, (f.yf, f.yt), (f.rf, f.rt), page, cursor.as_deref()),
move |s, _cx, r| {
if s.cat.generation != generation {
return;
}
s.cat.loading = false;
match r {
Ok(p) => {
let seen: HashSet<String> = s.cat.items.iter().map(|t| t.id.clone()).collect();
let new: Vec<TitleSummary> = p.items.into_iter().filter(|t| !seen.contains(&t.id)).collect();
s.cat.pages.push(new.len());
s.cat.items.extend(new);
s.cat.page = page;
s.cat.cursor = p.cursor;
s.cat.has_more = p.has_more;
s.cat.error = None;
}
Err(e) => s.cat.error = Some(crate::api::describe(&e)),
}
},
);
}
fn paused(&self) -> bool {
let streak = self.cat.pages[self.cat.resume_from.min(self.cat.pages.len())..].iter().rev().take_while(|n| **n == 0).count();
streak >= MAX_EMPTY_STREAK
}
fn find(&self, key: &str) -> Option<TitleSummary> {
let (kind, id) = screens::parse_title_key(key).or_else(|| screens::parse_continue(key).map(|(k, i, _)| (k, i)))?;
let lib = self.library.ready().into_iter().flatten().map(|e| &e.title);
let rails = self.rails.iter().filter_map(|r| r.3.ready()).flatten();
self.cat.items.iter().chain(lib).chain(rails).chain(self.continuing.iter().map(|c| &c.title)).find(|t| t.kind == kind && t.id == id).cloned()
}
fn cards(&self, cx: &Cx, items: &[TitleSummary]) -> Vec<C> {
let api = cx.api();
items.iter().map(|t| title_card(&api, t, self.states.get(&format!("{}:{}", t.kind.key(), t.id)))).collect()
}
fn pick_year(&mut self, cx: &Cx, which: &'static str) {
let current = if which == "yf" { self.f.yf } else { self.f.yt };
let empty = if which == "yf" { "Kezdettől" } else { "Máig" };
let mut items = vec![(empty.to_string(), String::new(), current.is_none())];
let years: Vec<i32> = (1920..=this_year()).rev().collect();
items.extend(years.iter().map(|y| (y.to_string(), String::new(), current == Some(*y))));
cx.select::<Source>(if which == "yf" { "Megjelenés ettől" } else { "Megjelenés eddig" }, items, move |s, cx, i| {
let v = if i == 0 { None } else { years.get(i - 1).copied() };
if which == "yf" {
s.f.yf = v;
if let (Some(a), Some(b)) = (s.f.yf, s.f.yt) {
if a > b {
s.f.yt = Some(a);
}
}
} else {
s.f.yt = v;
if let (Some(a), Some(b)) = (s.f.yf, s.f.yt) {
if a > b {
s.f.yf = Some(b);
}
}
}
s.reload_catalog(cx);
});
}
fn pick_rating(&mut self, cx: &Cx, which: &'static str) {
let current = if which == "rf" { self.f.rf } else { self.f.rt };
let list: Vec<f64> = (0..17).map(|i| 9.5 - i as f64 * 0.5).collect();
let fmt = |v: f64| format!("{v:.1}").replace('.', ",");
let mut items = vec![(if which == "rf" { "Bármennyi" } else { "10-ig" }.to_string(), String::new(), current.is_none())];
items.extend(list.iter().map(|r| (format!("{}{}", fmt(*r), if which == "rf" { "-tól" } else { "-ig" }), String::new(), current == Some(*r))));
cx.select::<Source>(if which == "rf" { "IMDb értékelés legalább" } else { "IMDb értékelés legfeljebb" }, items, move |s, cx, i| {
let v = if i == 0 { None } else { list.get(i - 1).copied() };
if which == "rf" {
s.f.rf = v;
if let (Some(a), Some(b)) = (s.f.rf, s.f.rt) {
if a > b {
s.f.rt = Some(a);
}
}
} else {
s.f.rt = v;
if let (Some(a), Some(b)) = (s.f.rf, s.f.rt) {
if a > b {
s.f.rf = Some(b);
}
}
}
s.reload_catalog(cx);
});
}
}
fn library(kind: MediaType, mine: Vec<ListItem>, history: Vec<ListItem>) -> Vec<Entry> {
let mut out: Vec<Entry> = Vec::new();
for it in mine.into_iter().filter(|i| i.title.kind == kind) {
out.push(Entry { title: it.title, saved: true, watched: false, last: None, added: it.added_at });
}
for it in history.into_iter().filter(|i| i.title.kind == kind) {
match out.iter_mut().find(|e| e.title.id == it.title.id) {
Some(e) => {
e.watched = true;
e.last = it.last_watched_at;
}
None => out.push(Entry { title: it.title, saved: false, watched: true, last: it.last_watched_at, added: None }),
}
}
out
}
fn ts(iso: &Option<String>) -> i64 {
iso.as_deref().and_then(crate::format::parse_iso).unwrap_or(0)
}
impl Screen for Source {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.start(cx);
}
let (title, _, _, _, empty_mine, empty_hint) = self.copy();
let lib_n = self.library.ready().map(|l| l.len()).unwrap_or(0);
let mut lines = vec![
L::page_title("title", title, ""),
L::chips(
"tabs",
"",
vec![
Ch::new("rec", "Ajánlott").active(self.tab == Tab::Recommended),
Ch::new("mine", format!("Könyvtáram ({lib_n})")).active(self.tab == Tab::Mine),
Ch::new("all", "Böngészés").active(self.tab == Tab::All),
],
),
];
let api = cx.api();
match self.tab {
Tab::Recommended => {
if !self.continuing.is_empty() {
lines.push(L::cards("continue", "Folytasd, ahol abbahagytad", "landscape", self.continuing.iter().map(|c| continue_card(&api, c)).collect()).captions());
}
if let Some(lib) = self.library.ready() {
let saved: Vec<TitleSummary> = lib.iter().filter(|e| e.saved).take(30).map(|e| e.title.clone()).collect();
if !saved.is_empty() {
let n = lib.iter().filter(|e| e.saved).count();
lines.push(L::cards("saved", "A könyvtáradból", "poster", self.cards(cx, &saved)).sub(format!("{n} mentett cím")));
}
}
if let Some(st) = self.genres.status("status") {
lines.push(st);
}
for (id, title, _, rail) in &self.rails {
match rail {
Load::Ready(items) if !items.is_empty() => lines.push(L::cards(format!("rail:{id}"), title.clone(), "poster", self.cards(cx, items))),
Load::Loading => lines.push(L::cards(format!("rail:{id}"), title.clone(), "poster", Vec::new())),
_ => {}
}
}
if self.genres.ready().is_some_and(|g| g.len() > 5) {
lines.push(L::chips("browse-all", "", vec![Ch::new("all", "Minden műfaj böngészése").icon("list")]));
}
}
Tab::Mine => {
let filters = [("all", "Minden"), ("saved", "Mentett"), ("watched", "Nézett"), ("unwatched", "Nem nézett")];
lines.push(L::chips("show", "", filters.iter().map(|(id, l)| Ch::new(*id, *l).active(self.show == *id)).collect()));
let sorts = [("recent", "Legutóbbi"), ("oldest", "Legrégebben nézett"), ("title", "Cím"), ("year", "Megjelenés")];
lines.push(L::chips("sort", "RENDEZÉS", sorts.iter().map(|(id, l)| Ch::new(*id, *l).active(self.lib_sort == *id)).collect()));
match &self.library {
Load::Ready(lib) if lib.is_empty() => lines.push(L::notice("empty", "info", empty_mine, empty_hint)),
Load::Ready(lib) => {
let mut shown: Vec<&Entry> = lib
.iter()
.filter(|e| match self.show {
"saved" => e.saved,
"watched" => e.watched,
"unwatched" => !e.watched,
_ => true,
})
.collect();
match self.lib_sort {
"title" => shown.sort_by(|a, b| a.title.title.to_lowercase().cmp(&b.title.title.to_lowercase())),
"year" => shown.sort_by_key(|e| std::cmp::Reverse(e.title.year.unwrap_or(0))),
"oldest" => shown.sort_by_key(|e| if e.last.is_some() { ts(&e.last) } else { i64::MAX }),
_ => shown.sort_by_key(|e| std::cmp::Reverse(ts(&e.added).max(ts(&e.last)))),
}
if shown.is_empty() {
lines.push(L::notice("empty", "info", "Ehhez a szűréshez nincs cím", "Válts a „Minden” nézetre."));
} else {
let items: Vec<TitleSummary> = shown.iter().map(|e| e.title.clone()).collect();
lines.extend(grid_lines("lib", "", "poster", self.cards(cx, &items), GRID));
}
}
other => lines.extend(other.status("status")),
}
}
Tab::All => {
let sorts = [("popularity", "Népszerű"), ("rating", "Legjobbra értékelt"), ("new", "Legújabb")];
let mut chips: Vec<Ch> = sorts.iter().map(|(id, l)| Ch::new(format!("sort:{id}"), *l).active(self.f.sort == *id)).collect();
let custom = self.f.custom();
chips.push(Ch::new("filters", if custom > 0 { format!("Szűrők ({custom})") } else { "Szűrők".into() }).icon("settings").active(self.open || custom > 0));
if self.f.filtered() {
chips.push(Ch::new("reset", "Törlés").icon("close"));
}
lines.push(L::chips("cat-sort", "", chips));
if self.open {
let year = |v: Option<i32>, empty: &str| v.map(|y| y.to_string()).unwrap_or_else(|| empty.to_string());
let mut yc = vec![
Ch::new("yf", format!("Ettől: {}", year(self.f.yf, "kezdettől"))).active(self.f.yf.is_some()),
Ch::new("yt", format!("Eddig: {}", year(self.f.yt, "máig"))).active(self.f.yt.is_some()),
];
yc.extend(DECADES.iter().enumerate().map(|(i, (l, a, b))| Ch::new(format!("dec:{i}"), *l).active(self.f.yf == *a && self.f.yt == *b)));
lines.push(L::chips("cat-year", "MEGJELENÉS", yc));
let r = |v: Option<f64>, suffix: &str, empty: &str| v.map(|v| format!("{}{suffix}", format!("{v:.1}").replace('.', ","))).unwrap_or_else(|| empty.to_string());
let mut rc = vec![
Ch::new("rf", format!("★ {}", r(self.f.rf, "-tól", "Bármennyi"))).active(self.f.rf.is_some()),
Ch::new("rt", r(self.f.rt, "-ig", "10-ig")).active(self.f.rt.is_some()),
];
rc.extend([6.0, 7.0, 8.0].iter().map(|v| Ch::new(format!("rp:{v}"), format!("{v}+")).active(self.f.rf == Some(*v) && self.f.rt.is_none())));
lines.push(L::chips("cat-rating", "IMDB", rc));
}
let mut gc = vec![Ch::new("g:", "Minden műfaj").active(self.f.genre.is_none())];
if let Some(gs) = self.genres.ready() {
gc.extend(gs.iter().map(|g| Ch::new(format!("g:{}", g.id), g.name.clone()).active(self.f.genre.as_deref() == Some(g.id.as_str()))));
}
lines.push(L::chips("cat-genre", "MŰFAJ", gc));
if self.cat.items.is_empty() {
if let Some(e) = &self.cat.error {
lines.push(L::notice("cat-error", "bad", "Nem sikerült betölteni", e.clone()));
lines.push(L::chips("cat-retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")]));
} else if self.cat.loading || self.cat.has_more {
lines.push(L::text("cat-loading", "Betöltés…", "caption"));
} else {
lines.push(L::notice("cat-empty", "info", "Ehhez a szűréshez nincs találat", "Tágítsd az év- vagy az értékelés-tartományt, vagy válassz másik műfajt."));
if self.f.filtered() {
lines.push(L::chips("cat-reset", "", vec![Ch::new("reset", "Szűrők törlése").icon("close")]));
}
}
} else {
lines.extend(grid_lines("cat", "", "poster", self.cards(cx, &self.cat.items.clone()), GRID));
if self.cat.error.is_some() {
lines.push(L::chips("cat-retry", "", vec![Ch::new("retry", "Újrapróbálom").icon("refresh")]));
} else if self.paused() && self.cat.has_more && !self.cat.loading {
lines.push(L::text("cat-deep", "Szűk szűrés: a katalógus mélyén már ritka a találat.", "caption"));
lines.push(L::chips("cat-more", "", vec![Ch::new("more", "Keresés tovább")]));
} else if self.cat.loading {
lines.push(L::text("cat-loading", "Betöltés…", "caption"));
} else if !self.cat.has_more {
lines.push(L::text("cat-end", format!("A lista végére értél · {} cím", self.cat.items.len()), "caption"));
}
}
}
}
Spec { lines, frame: Frame { nav: Some(if self.kind == MediaType::Movie { 1 } else { 2 }), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
match (line, item) {
("tabs", t) | ("browse-all", t) => {
self.tab = match t {
"mine" => Tab::Mine,
"all" => Tab::All,
_ => Tab::Recommended,
};
if self.tab == Tab::All && self.cat.pages.is_empty() && !self.cat.loading {
self.reload_catalog(cx);
}
if line == "browse-all" {
cx.focus_on("tabs", 2);
}
}
("show", v) => {
self.show = match v {
"saved" => "saved",
"watched" => "watched",
"unwatched" => "unwatched",
_ => "all",
}
}
("sort", v) => {
self.lib_sort = match v {
"oldest" => "oldest",
"title" => "title",
"year" => "year",
_ => "recent",
}
}
("cat-sort", "filters") => self.open = !self.open,
("cat-sort", "reset") | ("cat-reset", _) => {
self.f = Filters { sort: self.f.sort, genre: None, yf: None, yt: None, rf: None, rt: None };
self.reload_catalog(cx);
}
("cat-sort", s) => {
self.f.sort = match s.trim_start_matches("sort:") {
"rating" => "rating",
"new" => "new",
_ => "popularity",
};
self.reload_catalog(cx);
}
("cat-year", "yf") => self.pick_year(cx, "yf"),
("cat-year", "yt") => self.pick_year(cx, "yt"),
("cat-year", d) => {
if let Some((_, a, b)) = d.strip_prefix("dec:").and_then(|i| i.parse::<usize>().ok()).and_then(|i| DECADES.get(i)) {
let on = self.f.yf == *a && self.f.yt == *b;
(self.f.yf, self.f.yt) = if on { (None, None) } else { (*a, *b) };
self.reload_catalog(cx);
}
}
("cat-rating", "rf") => self.pick_rating(cx, "rf"),
("cat-rating", "rt") => self.pick_rating(cx, "rt"),
("cat-rating", p) => {
if let Some(v) = p.strip_prefix("rp:").and_then(|v| v.parse::<f64>().ok()) {
let on = self.f.rf == Some(v) && self.f.rt.is_none();
(self.f.rf, self.f.rt) = if on { (None, None) } else { (Some(v), None) };
self.reload_catalog(cx);
}
}
("cat-genre", g) => {
let g = g.trim_start_matches("g:");
self.f.genre = if g.is_empty() || self.f.genre.as_deref() == Some(g) { None } else { Some(g.to_string()) };
self.reload_catalog(cx);
}
("cat-retry", _) => {
self.cat.error = None;
self.next_page(cx);
}
("cat-more", _) => {
self.cat.resume_from = self.cat.pages.len();
self.next_page(cx);
}
(_, key) => {
let found = self.find(key);
screens::open_card(cx, key, |_| found.clone());
}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, item: &str) {
match self.find(item) {
Some(t) => {
let url = cx.api().image(t.backdrop.as_deref(), false);
cx.backdrop(&url, Look::Soft, item);
}
None => cx.backdrop("", Look::Soft, ""),
}
}
fn more(&mut self, cx: &Cx, list: &str) {
if list == "cat" {
self.next_page(cx);
}
}
fn shown(&mut self, cx: &Cx) {
// Progress and lists may have changed on a details page.
let (api, kind) = (cx.api(), self.kind);
cx.spawn::<Source, _>(
move || (api.continue_watching().unwrap_or_default(), api.my_list(), api.history().unwrap_or_default(), api.list_status().unwrap_or_default()),
move |s, _cx, (cont, mine, history, states)| {
s.continuing = cont.into_iter().filter(|c| c.title.kind == kind).collect();
if let Ok(mine) = mine {
s.library = Load::Ready(library(kind, mine, history));
}
s.states = states;
},
);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

49
src/task.rs Normal file
View File

@@ -0,0 +1,49 @@
//! 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);
}
});
});
}
/// Fire and forget (saving progress...): errors are only logged.
pub fn background(what: &'static str, work: impl FnOnce() -> anyhow::Result<()> + Send + 'static) {
std::thread::spawn(move || {
if let Err(e) = work() {
log::warn!("{what}: {e:#}");
}
});
}

320
tools/mock_server.py Normal file
View File

@@ -0,0 +1,320 @@
#!/usr/bin/env python3
"""A stand-in Netflex server for developing the TV app without one.
Real catalog data (Cinemeta, artwork through /api/img) on the same API the
app uses; sign-in with any user name and the password "netflex"; playback
streams a local video file with range requests.
python3 tools/mock_server.py [--port 7880] [--video test.mkv]
NETFLEX_SERVER=http://localhost:7880 cargo run
Standard library only. Not a real server: no torrents, no nCore.
"""
import argparse
import json
import os
import re
import threading
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
CATALOGS = "https://cinemeta-catalogs.strem.io/top/catalog"
CINEMETA = "https://v3-cinemeta.strem.io"
TOKEN = "dev-token"
GENRES = ["Action", "Comedy", "Drama", "Thriller", "Sci-Fi", "Animation", "Crime", "Horror", "Romance", "Documentary"]
GENRE_HU = {"Action": "Akció", "Comedy": "Vígjáték", "Drama": "Dráma", "Thriller": "Thriller", "Sci-Fi": "Sci-fi",
"Animation": "Animáció", "Crime": "Krimi", "Horror": "Horror", "Romance": "Romantikus", "Documentary": "Dokumentum"}
cache = {}
cache_lock = threading.Lock()
my_list = {}
progress = {}
VIDEO = None
def fetch(url, binary=False):
with cache_lock:
if url in cache:
return cache[url]
req = urllib.request.Request(url, headers={"User-Agent": "netflex-mock"})
with urllib.request.urlopen(req, timeout=20) as r:
data = r.read()
value = data if binary else json.loads(data)
with cache_lock:
cache[url] = value
return value
def ctype(t):
return "series" if t == "tv" else "movie"
def summary(t, m):
year_label = m.get("releaseInfo") or m.get("year")
year = None
try:
year = int(str(year_label or m.get("released") or "")[:4])
except ValueError:
pass
try:
rating = float(m.get("imdbRating") or 0) or None
except ValueError:
rating = None
return {
"type": "tv" if m.get("type") == "series" else ("movie" if m.get("type") == "movie" else t),
"id": m.get("imdb_id") or m.get("id"),
"tmdbId": None,
"title": m.get("name") or "Névtelen",
"originalTitle": None,
"overview": m.get("description"),
"poster": m.get("poster"),
"backdrop": m.get("background"),
"logo": m.get("logo"),
"year": year,
"yearLabel": str(year_label).replace("-", "–") if year_label else None,
"rating": rating,
"genres": m.get("genres") or m.get("genre") or [],
}
def catalog(t, genre=None, skip=0):
path = f"{CATALOGS}/{ctype(t)}/top"
extra = []
if genre:
extra.append("genre=" + urllib.parse.quote(genre))
if skip:
extra.append(f"skip={skip}")
url = path + ("/" + "&".join(extra) if extra else "") + ".json"
metas = fetch(url).get("metas", [])
return [summary(t, m) for m in metas]
def episodes(m):
out = []
for v in m.get("videos") or []:
try:
s, e = int(v.get("season")), int(v.get("episode") or v.get("number"))
except (TypeError, ValueError):
continue
out.append({"season": s, "episode": e, "name": v.get("name") or v.get("title"),
"overview": v.get("overview") or v.get("description"),
"airDate": (v.get("released") or v.get("firstAired") or "")[:10] or None,
"runtime": None, "still": v.get("thumbnail"), "rating": None})
return sorted(out, key=lambda x: (x["season"], x["episode"]))
def detail(t, id_):
m = fetch(f"{CINEMETA}/meta/{ctype(t)}/{id_}.json").get("meta") or {}
eps = episodes(m)
seasons = sorted({e["season"] for e in eps if e["season"] > 0})
d = summary(t, m)
try:
runtime = int(re.sub(r"\D", "", str(m.get("runtime") or "")) or 0) or None
except ValueError:
runtime = None
d.update({
"runtime": runtime, "tagline": None, "status": m.get("status"),
"cast": (m.get("cast") or [])[:15], "directors": m.get("director") or [], "trailerKey": None,
"seasons": [{"number": n, "name": f"{n}. évad", "episodeCount": sum(1 for e in eps if e["season"] == n),
"airedCount": sum(1 for e in eps if e["season"] == n), "airDate": None, "poster": None} for n in seasons],
"numberOfSeasons": len(seasons) if t == "tv" else None,
"lastEpisodeToAir": None, "nextEpisodeToAir": None, "huSource": None,
})
return d, eps
class Handler(BaseHTTPRequestHandler):
server_version = "netflex-mock"
def log_message(self, fmt, *args):
print("mock:", self.command, self.path.split("?")[0], fmt % args if "%" in fmt else "")
def authed(self, q):
auth = self.headers.get("Authorization", "")
return auth == f"Bearer {TOKEN}" or q.get("token", [""])[0] == TOKEN
def send_json(self, value, status=200):
body = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def body(self):
n = int(self.headers.get("Content-Length") or 0)
return json.loads(self.rfile.read(n) or b"{}") if n else {}
def do_GET(self):
self.route("GET")
def do_POST(self):
self.route("POST")
def do_PUT(self):
self.route("PUT")
def do_DELETE(self):
self.route("DELETE")
def do_HEAD(self):
self.route("HEAD")
def route(self, method):
url = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(url.query)
p = url.path
try:
if p == "/api/auth/status":
return self.send_json({"setupRequired": False, "user": {"id": 1, "username": "dev", "name": "Dev", "isAdmin": True} if self.authed(q) else None})
if p == "/api/auth/login" and method == "POST":
b = self.body()
if b.get("password") != "netflex":
return self.send_json({"error": "Hibás felhasználónév vagy jelszó"}, 401)
return self.send_json({"token": TOKEN, "user": {"id": 1, "username": b.get("username", "dev"), "name": "Dev", "isAdmin": True}})
if not self.authed(q):
return self.send_json({"error": "Bejelentkezés szükséges", "code": "unauthenticated"}, 401)
if p == "/api/img":
return self.image(q.get("u", [""])[0])
if p.startswith("/api/stream/"):
return self.stream(method)
if p == "/api/settings":
return self.send_json({"subtitleLang": "hu", "autoNext": True})
if p == "/api/home":
movies, series = catalog("movie")[:20], catalog("tv")[:20]
cont = [{"title": series[0], "season": 1, "episode": 2, "position": 900, "duration": 2700, "updatedAt": ""},
{"title": movies[3], "season": None, "episode": None, "position": 3100, "duration": 7200, "updatedAt": ""}]
return self.send_json({"rows": [{"id": "popular-movie", "title": "Népszerű filmek", "items": movies},
{"id": "popular-tv", "title": "Népszerű sorozatok", "items": series},
{"id": "featured-movie", "title": "Kiemelt filmek", "items": catalog("movie", skip=20)[:20]}],
"continueWatching": cont})
if p == "/api/genres":
return self.send_json([{"id": g, "name": GENRE_HU[g]} for g in GENRES])
if p == "/api/browse":
t = q.get("type", ["movie"])[0]
page = int(q.get("page", ["1"])[0])
items = catalog(t, q.get("genre", [None])[0], skip=(page - 1) * 50)
return self.send_json({"page": page, "hasMore": len(items) >= 50, "items": items})
if p == "/api/search":
term = urllib.parse.quote(q.get("q", [""])[0])
items = []
for t in ("movie", "tv"):
metas = fetch(f"{CINEMETA}/catalog/{ctype(t)}/top/search={term}.json").get("metas", [])
items += [summary(t, m) for m in metas[:16]]
return self.send_json({"page": 1, "hasMore": False, "items": items})
m = re.fullmatch(r"/api/title/(movie|tv)/([^/]+)", p)
if m:
return self.send_json(detail(m[1], m[2])[0])
m = re.fullmatch(r"/api/title/tv/([^/]+)/season/(\d+)", p)
if m:
eps = [e for e in detail("tv", m[1])[1] if e["season"] == int(m[2])]
return self.send_json({"number": int(m[2]), "name": f"{m[2]}. évad", "episodes": eps})
m = re.fullmatch(r"/api/progress/(movie|tv)/([^/]+)", p)
if m:
return self.send_json(progress.get(f"{m[1]}:{m[2]}", []))
if p == "/api/progress" and method == "PUT":
b = self.body()
key = f"{b['type']}:{b['titleId']}"
rows = [r for r in progress.get(key, []) if not (r["season"] == b.get("season", 0) and r["episode"] == b.get("episode", 0))]
dur = b.get("duration")
rows.append({"season": b.get("season", 0), "episode": b.get("episode", 0), "position": b["position"], "duration": dur,
"completed": bool(dur and b["position"] / dur >= 0.92), "infoHash": None, "fileIndex": None})
progress[key] = rows
return self.send_json({"ok": True})
if p == "/api/lists/status":
return self.send_json({k: {"listed": True, "watchedEpisodes": 0, "watched": False} for k in my_list})
if p == "/api/lists/mine":
return self.send_json([{"title": v, "addedAt": None, "lastWatchedAt": None, "watchedEpisodes": 0} for v in my_list.values()])
m = re.fullmatch(r"/api/lists/mine/(movie|tv)/([^/]+)", p)
if m:
if method == "PUT":
my_list[f"{m[1]}:{m[2]}"] = summary(m[1], fetch(f"{CINEMETA}/meta/{ctype(m[1])}/{m[2]}.json").get("meta") or {})
else:
my_list.pop(f"{m[1]}:{m[2]}", None)
return self.send_json({"ok": True})
if p.startswith("/api/sources/"):
return self.send_json({"imdbId": None, "searchedBy": "imdb", "candidates": [
{"torrent": {"id": 1, "name": "Mock.Release.2024.1080p.WEB-DL.HUN.ENG", "category": "hd_hun", "size": 4.2e9, "seeders": 42,
"leechers": 1, "uploadedAt": None, "imdbId": None, "imdbRating": None, "freeleech": False},
"parsed": {}, "score": 1, "reasons": [], "pack": False, "local": "seeding"}]})
if p == "/api/play/start":
return self.send_json({"infoHash": "0" * 40, "fileIndex": 0, "fileName": os.path.basename(VIDEO or "none.mkv"), "size": 1})
m = re.fullmatch(r"/api/media/[0-9a-f]{40}/\d+/probe", p)
if m:
if not VIDEO:
return self.send_json({"error": "A mock szervernek nincs videója (--video)"}, 422)
return self.send_json({"durationSec": None, "tracks": [], "audioLangs": [], "subtitleLangs": [], "englishDub": False,
"hungarianDub": False, "attachments": [], "fileName": os.path.basename(VIDEO),
"fileSize": os.path.getsize(VIDEO), "local": True, "audioDelayMs": 0})
if re.fullmatch(r"/api/media/[0-9a-f]{40}/\d+/audio-delay", p):
return self.send_json({"audioDelayMs": self.body().get("ms", 0)})
if p.startswith("/api/torrent/"):
return self.send_json({"ready": True, "fileProgress": 1, "downloadSpeed": 0})
return self.send_json({"error": "Nem található"}, 404)
except Exception as e: # noqa: BLE001 - a dev tool: report everything
print("mock: error", p, e)
return self.send_json({"error": f"mock: {e}"}, 502)
def image(self, u):
if not u.startswith("https://"):
return self.send_json({"error": "bad url"}, 400)
data = fetch(u, binary=True)
self.send_response(200)
self.send_header("Content-Type", "image/jpeg" if data[:2] == b"\xff\xd8" else "image/png")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "public, max-age=31536000")
self.end_headers()
self.wfile.write(data)
def stream(self, method):
if not VIDEO:
return self.send_json({"error": "no video"}, 404)
size = os.path.getsize(VIDEO)
start, end = 0, size - 1
rng = re.match(r"bytes=(\d*)-(\d*)", self.headers.get("Range", ""))
if rng:
if rng[1] == "" and rng[2]:
start = max(0, size - int(rng[2]))
else:
start = int(rng[1] or 0)
if rng[2]:
end = min(int(rng[2]), size - 1)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
else:
self.send_response(200)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Type", "video/x-matroska")
self.send_header("Content-Length", str(end - start + 1))
self.end_headers()
if method == "HEAD":
return
with open(VIDEO, "rb") as f:
f.seek(start)
left = end - start + 1
try:
while left > 0:
chunk = f.read(min(1 << 16, left))
if not chunk:
break
self.wfile.write(chunk)
left -= len(chunk)
except (BrokenPipeError, ConnectionResetError):
pass
def main():
global VIDEO
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port", type=int, default=7880)
ap.add_argument("--video", help="a local video file to stream for every title")
args = ap.parse_args()
VIDEO = args.video
print(f"mock Netflex on http://localhost:{args.port} (password: netflex)")
ThreadingHTTPServer(("0.0.0.0", args.port), Handler).serve_forever()
if __name__ == "__main__":
main()

204
ui/app.slint Normal file
View File

@@ -0,0 +1,204 @@
// Netflex for Fennec OS: the root window.
//
// Screens: "message" (start-up, errors), "page" (every browsing screen: a
// LinePage built by src/page.rs), "player". Over them: the text input
// (sign-in and every text field), 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 } from "types.slint";
import { LinePage } from "page.slint";
import { PlayerScreen } from "player.slint";
import { SignInScreen, MessageScreen } from "signin.slint";
import { SelectOverlay, Toast } from "overlays.slint";
export { Tv, SfText, MenuItem, Line, Chip, Card, Check }
export component App inherits TvWindow {
title: "Netflex";
forward-focus: keys;
// "message", "page", "player"
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" && !self.input-open ? 1 : 0;
animate message-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> player-t: self.screen == "player" ? 1 : 0;
animate player-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;
in property <string> message-action-a <=> message.action-a;
in property <string> message-action-b <=> message.action-b;
in property <int> message-action <=> message.action;
message := MessageScreen {
alpha: root.vis(root.message-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-vpn-label <=> page.vpn-label;
in property <bool> page-vpn-ok <=> page.vpn-ok;
in property <string> page-side-title <=> page.side-title;
in property <[string]> page-side-items <=> page.side-items;
in property <int> page-side-index <=> page.side-index;
in property <int> page-side-focus <=> page.side-focus;
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(); }
}
// ---- player ----
in property <string> player-stage <=> player.stage;
in property <string> player-title <=> player.title;
in property <string> player-heading <=> player.heading;
in property <string> player-info <=> player.info;
in property <string> player-stage-text <=> player.stage-text;
in property <string> player-detail-text <=> player.detail-text;
in property <string> player-error-text <=> player.error-text;
in property <bool> player-osd <=> player.osd;
in property <bool> player-paused <=> player.paused;
in property <bool> player-buffering <=> player.buffering;
in property <string> player-buffer-text <=> player.buffer-text;
in property <float> player-progress <=> player.progress;
in property <float> player-buffered <=> player.buffered;
in property <string> player-time-text <=> player.time-text;
in property <string> player-remaining-text <=> player.remaining-text;
in property <string> player-downloaded-text <=> player.downloaded-text;
in property <bool> player-seeking <=> player.seeking;
in property <string> player-seek-text <=> player.seek-text;
in property <string> player-seek-delta <=> player.seek-delta;
in property <bool> player-seek-back <=> player.seek-back;
in property <int> player-osd-area <=> player.osd-area;
in property <int> player-osd-button <=> player.osd-button;
in property <bool> player-has-prev <=> player.has-prev;
in property <bool> player-has-next <=> player.has-next;
in property <int> player-panel <=> player.panel;
in property <[MenuItem]> player-audio <=> player.audio;
in property <[MenuItem]> player-subs <=> player.subs;
in property <[MenuItem]> player-sync <=> player.sync;
in property <[MenuItem]> player-quality <=> player.quality;
in property <int> player-audio-focus <=> player.audio-focus;
in property <int> player-subs-focus <=> player.subs-focus;
in property <int> player-sync-focus <=> player.sync-focus;
in property <int> player-quality-focus <=> player.quality-focus;
in property <string> player-skip-label <=> player.skip-label;
in property <string> player-next-label <=> player.next-label;
in property <string> player-next-text <=> player.next-text;
player := PlayerScreen {
alpha: root.vis(root.player-t);
visible: self.alpha > 0.001;
}
// ---- text input (sign-in, every text field) ----
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 <bool> input-secret <=> input.secret;
in property <string> input-submit-label <=> input.submit-label;
in property <int> input-min-length <=> input.min-length;
in property <string> input-footer <=> input.footer;
in property <bool> input-busy <=> input.busy;
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 := SignInScreen {
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-message: message.glass;
out property <[GlassRect]> glass-page: page.glass;
out property <[GlassRect]> glass-page-keyboard: page.glass-keyboard;
out property <[GlassRect]> glass-player: player.glass;
out property <[GlassRect]> glass-player-audio: player.glass-audio;
out property <[GlassRect]> glass-player-subs: player.glass-subs;
out property <[GlassRect]> glass-player-sync: player.glass-sync;
out property <[GlassRect]> glass-player-quality: player.glass-quality;
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;
}

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: #e50914;
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];
}

773
ui/page.slint Normal file
View File

@@ -0,0 +1,773 @@
// The page renderer: every screen except the player and the sign-in 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 (main sections) or the settings side list,
// - hero buttons (glass at rest),
// - one focus pill that glides to the focused chip on any other line,
// - 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, Icon, Spinner, Display, Headline, Title, SectionTitle, Body, Item, Label, Caption } from "@sf-ui/sf-ui.slint";
import { Line, Chip, Card, Check } from "types.slint";
// A poster, landscape artwork or season card.
component NfCard inherits Rectangle {
in property <Card> card;
in property <bool> focused;
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); }
art := Rectangle {
y: 0;
height: root.art-h;
transform-scale: 1 + 0.08 * root.f;
Rectangle {
border-radius: 20 * Tv.u;
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: 20 * Tv.u;
clip: true;
if root.card.image.width == 0: Text {
x: 20 * Tv.u;
width: parent.width - 40 * Tv.u;
horizontal-alignment: center;
vertical-alignment: center;
text: root.card.big != "" ? "" : 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;
}
if root.card.big != "": Rectangle {
background: #00000070;
Text {
text: root.card.big;
font-size: 68 * Tv.u;
font-weight: 700;
letter-spacing: -2 * Tv.u;
color: Tv.text;
}
}
Rectangle {
background: #000000;
opacity: 0.22 * (1 - root.f);
}
if root.card.progress >= 0: Rectangle {
x: 12 * Tv.u;
y: parent.height - 18 * Tv.u;
width: parent.width - 24 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff40;
Rectangle {
x: 0;
width: parent.width * clamp(root.card.progress, 0, 1);
border-radius: self.height / 2;
background: root.card.progress >= 0.999 ? Tv.ok : #e50914;
}
}
}
if root.card.badge != "": Rectangle {
x: 12 * Tv.u;
y: 12 * Tv.u;
width: badge-text.preferred-width + 22 * Tv.u;
height: 34 * Tv.u;
border-radius: self.height / 2;
background: root.card.badge-tone == "dub" ? #1f7a4dd8 : root.card.badge-tone == "sub" ? #2b5fa8d8 : root.card.badge-tone == "accent" ? #e50914d8 : #000000b8;
badge-text := Text {
text: root.card.badge;
font-size: 19 * Tv.u;
font-weight: 700;
color: Tv.text;
}
}
if root.card.mark == "check": Rectangle {
x: parent.width - self.width - 12 * Tv.u;
y: 12 * Tv.u;
width: 36 * Tv.u;
height: 36 * Tv.u;
border-radius: self.height / 2;
background: #000000b8;
Icon {
name: "check";
size: 22 * Tv.u;
ink: Tv.ok-ink;
}
}
if root.card.current: Rectangle {
border-radius: 20 * Tv.u;
border-width: 4 * Tv.u;
border-color: #e50914;
}
}
if root.captions: Text {
x: 0;
y: root.art-h + 18 * Tv.u;
width: root.width;
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;
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 NfChip 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 == "include" ? Tv.ok-ink
: root.chip.tone == "exclude" || 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" ? #e5091480
: root.chip.tone == "include" ? #34c75938
: root.chip.tone == "exclude" ? #ff453a38
: 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 != "": Icon {
y: (parent.height - self.height) / 2;
name: root.chip.icon;
size: 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;
}
}
}
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;
in property <string> vpn-label;
in property <bool> vpn-ok;
// Settings side list.
in property <string> side-title;
in property <[string]> side-items;
in property <int> side-index;
in property <int> side-focus: -1;
// 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();
}
property <bool> side: self.side-items.length > 0;
// Content left edge (design px).
property <float> cx: self.side ? 600 : 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.side-focus < 0 && !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
if line.kind == "hero": Rectangle {
if line.logo.width > 0: Image {
x: 0;
y: 40 * Tv.u;
width: 620 * Tv.u;
height: 190 * Tv.u;
source: line.logo;
image-fit: contain;
horizontal-alignment: left;
vertical-alignment: bottom;
}
if line.logo.width == 0: 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;
}
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;
}
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;
}
Label {
x: 0;
y: 312 * Tv.u;
width: 1500 * Tv.u;
text: line.extra;
color: #ff8a8a;
font-weight: 600;
}
Body {
x: 0;
y: (line.extra == "" ? 316 : 352) * Tv.u;
width: 1100 * Tv.u;
height: (line.extra == "" ? 152 : 116) * Tv.u;
text: line.text;
font-size: 26 * Tv.u;
}
for chip[ci] in line.chips: NfChip {
chip: chip;
focused: lf && line.col == ci;
on-glass: true;
}
if line.progress >= 0: Rectangle {
x: 0;
y: (line.h - 22) * Tv.u;
width: 360 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff33;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: #e50914;
}
}
if line.note != "": Caption {
x: 380 * Tv.u;
y: (line.h - 34) * Tv.u;
text: line.note;
}
}
// 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 {
Icon {
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;
}
}
// checks
if line.kind == "checks": Rectangle {
for c[i] in line.checks: Rectangle {
x: mod(i, 2) * parent.width / 2;
y: floor(i / 2) * 84 * Tv.u;
width: parent.width / 2 - 24 * Tv.u;
height: 80 * Tv.u;
Icon {
x: 0;
y: 2 * Tv.u;
size: 28 * Tv.u;
name: c.state == 1 ? "check" : c.state == 0 ? "close" : "info";
ink: c.state == 1 ? Tv.ok-ink : c.state == 0 ? Tv.danger-ink : Tv.warn-ink;
}
Text {
x: 44 * Tv.u;
y: 0;
width: parent.width - 44 * Tv.u;
text: c.label;
font-size: 23 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
Text {
x: 44 * Tv.u;
y: 32 * Tv.u;
width: parent.width - 44 * Tv.u;
height: 48 * Tv.u;
text: c.detail;
font-size: 20 * Tv.u;
color: Tv.text-tertiary;
wrap: word-wrap;
overflow: elide;
}
}
}
// 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: NfChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// item
if line.kind == "item": Rectangle {
property <bool> pic: line.style == "image";
property <length> tx: (self.pic ? 288 : 0) * Tv.u;
if self.pic: Rectangle {
x: 0;
y: 8 * Tv.u;
width: 256 * Tv.u;
height: 144 * Tv.u;
border-radius: 16 * Tv.u;
clip: true;
background: #1b1d24;
Image {
width: 100%;
height: 100%;
source: line.image;
image-fit: cover;
}
if line.progress >= 0: Rectangle {
x: 10 * Tv.u;
y: parent.height - 16 * Tv.u;
width: parent.width - 20 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff40;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: line.progress >= 0.999 ? Tv.ok : #e50914;
}
}
}
if !self.pic && line.progress >= 0: Rectangle {
x: 0;
y: parent.height - 12 * Tv.u;
width: 900 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff26;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: line.tone == "warn" ? Tv.warn : line.tone == "good" ? Tv.ok : #4f8cff;
}
}
Text {
x: parent.tx;
y: 6 * Tv.u;
width: parent.width - parent.tx;
text: line.title;
font-size: 26 * Tv.u;
font-weight: 600;
color: line.tone == "dim" ? Tv.text-tertiary : Tv.text;
overflow: elide;
}
Text {
x: parent.tx;
y: 42 * Tv.u;
width: parent.width - parent.tx;
text: line.meta;
font-size: 21 * Tv.u;
font-weight: 500;
color: line.tone == "bad" ? Tv.danger-ink : line.tone == "warn" ? Tv.warn-ink : Tv.text-tertiary;
overflow: elide;
}
Text {
x: parent.tx;
y: 74 * Tv.u;
width: min(parent.width - parent.tx, 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: NfChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// cards
if line.kind == "cards": Rectangle {
property <float> cw: line.style == "landscape" ? 400 : line.style == "season" ? 168 : 196;
property <float> ch: line.style == "landscape" ? 225 : line.style == "season" ? 252 : 294;
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: 600;
color: lf ? Tv.text : #ffffffc8;
}
if line.subtitle != "": Caption {
x: title-w.preferred-width + 20 * Tv.u;
y: 10 * Tv.u;
text: line.subtitle;
}
title-w := Text {
visible: false;
text: line.title;
font-size: 32 * Tv.u;
font-weight: 600;
}
for card[ci] in line.cards: NfCard {
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;
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(); }
}
}
// ---- settings side list ----
if root.side: Headline {
x: Tv.safe-x;
y: 56 * Tv.u;
text: root.side-title;
opacity: root.alpha;
}
for item[i] in root.side-items: Text {
x: (96 + 28) * Tv.u;
y: (184 + i * 80) * Tv.u;
width: (440 - 56) * Tv.u;
height: 72 * Tv.u;
vertical-alignment: center;
text: item;
font-size: 26 * Tv.u;
font-weight: 600;
color: i == root.side-focus ? Tv.ink : i == root.side-index ? Tv.text : Tv.text-secondary;
opacity: root.alpha;
}
// ---- top navigation ----
property <length> tab-w: 176 * Tv.u;
property <float> nav-a: root.show-nav ? root.alpha * (root.nav-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;
}
}
if root.show-nav && root.vpn-label != "": HorizontalLayout {
x: nav.x + nav.width + 28 * Tv.u;
y: nav.y;
height: nav.height;
spacing: 10 * Tv.u;
opacity: root.nav-a;
Rectangle {
width: 12 * Tv.u;
Rectangle {
y: (parent.height - self.height) / 2;
height: 12 * Tv.u;
border-radius: self.height / 2;
background: root.vpn-ok ? Tv.ok : Tv.danger;
}
}
Text {
vertical-alignment: center;
text: root.vpn-label;
font-size: 22 * Tv.u;
font-weight: 600;
color: root.vpn-ok ? Tv.ok-ink : Tv.danger-ink;
}
}
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; }
out property <float> side-pos: self.side-index;
animate side-pos { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> side-fpos: max(0, self.side-focus);
animate side-fpos { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
// ---- 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: 300ms; 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" ? #e50914 : #ffffff,
tint: c.tone == "primary" ? #e50914.with-alpha(0.42 + 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: 96 * Tv.u,
y: (184 + root.side-pos * 80) * Tv.u,
w: 440 * Tv.u,
h: 72 * Tv.u,
r: 36 * Tv.u,
focus: 0,
alpha: root.side ? root.alpha * (root.side-focus == root.side-index ? 0 : 1) : 0,
blur: 1.2,
glow: #ffffff,
tint: #ffffff14,
group: 0,
},
{
x: 96 * Tv.u,
y: (184 + root.side-fpos * 80) * Tv.u,
w: 440 * Tv.u,
h: 72 * Tv.u,
r: 36 * Tv.u,
focus: 1,
alpha: root.side && root.side-focus >= 0 ? root.alpha : 0,
blur: 1.2,
glow: #ffffff,
tint: #ffffffe0,
group: 0,
},
root.hero-rect(0),
root.hero-rect(1),
root.hero-rect(2),
root.hero-rect(3),
root.hero-rect(4),
root.hero-rect(5),
{
x: root.pill-x * Tv.u,
y: (root.pill-y - root.scroll-anim) * Tv.u,
w: root.pill-w * Tv.u,
h: root.fc.h * Tv.u,
r: root.fc.tone == "field" ? 22 * Tv.u : root.fc.h * Tv.u / 2,
focus: 1,
alpha: root.alpha * root.pill-a,
blur: 1.2,
glow: root.fc.tone == "primary" ? #e50914 : #ffffff,
tint: root.fc.tone == "primary" ? #e50914.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;
}

358
ui/player.slint Normal file
View File

@@ -0,0 +1,358 @@
// Playback. The film itself is the glass backdrop (Rust: glass.set_video),
// so the controls are glass that refracts the picture.
//
// Stages: "prep" (finding the source, starting the torrent), "play",
// "error". With the controls hidden the remote drives playback directly
// (OK = play/pause or the skip prompt, left/right = seek); shown, up/down
// moves between the seek bar and the buttons. All focus state is Rust's.
import { Tv, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, Spinner, Title, Label, Caption, Item, Icon } from "@sf-ui/sf-ui.slint";
export component PlayerScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> stage: "prep";
in property <string> title;
// Accent line above the title ("S01E03 · Pilot", "3. rész", "2024").
in property <string> heading;
// "HEVC 2160p · Magyar (+200 ms) · Angol felirat"
in property <string> info;
in property <string> stage-text;
in property <string> detail-text;
in property <string> error-text;
// Playing.
in property <bool> osd;
in property <bool> paused;
in property <bool> buffering;
in property <string> buffer-text;
in property <float> progress;
in property <float> buffered;
in property <string> time-text;
in property <string> remaining-text;
in property <string> downloaded-text;
// Seeking with left/right: the target and how far it is.
in property <bool> seeking;
in property <string> seek-text;
in property <string> seek-delta;
in property <bool> seek-back;
// Controls: 0 = seek bar, 1 = buttons; which button.
in property <int> osd-area;
in property <int> osd-button;
in property <bool> has-prev;
in property <bool> has-next;
// Track panel: 0 = closed, else the focused column + 1 (audio, subtitles, sync, quality).
in property <int> panel;
in property <[MenuItem]> audio;
in property <[MenuItem]> subs;
in property <[MenuItem]> sync;
in property <[MenuItem]> quality;
in property <int> audio-focus;
in property <int> subs-focus;
in property <int> sync-focus;
in property <int> quality-focus;
// Anime: "Intro átugrása"... while a segment plays.
in property <string> skip-label;
// The end: "Következik" card.
in property <string> next-label;
in property <string> next-text;
out property <float> osd-t: self.stage == "play" && (self.osd || self.paused || self.panel > 0) ? 1 : 0;
animate osd-t { duration: 320ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> panel-t: self.panel > 0 ? 1 : 0;
animate panel-t { duration: 360ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <float> prep-a: self.alpha * (self.stage == "play" ? 0 : 1);
property <float> osd-a: self.alpha * self.osd-t;
property <bool> buttons: self.osd-t > 0.5 && self.osd-area == 1 && self.panel == 0;
// Darkens the film behind the controls (Slint over video is fine).
Rectangle {
y: root.height * 0.5;
height: root.height * 0.5;
background: @linear-gradient(180deg, #00000000 0%, #000000b8 100%);
opacity: root.osd-a;
}
// ---- preparing / error ----
VerticalLayout {
x: Tv.safe-x;
width: root.width - 2 * Tv.safe-x;
y: 330 * Tv.u;
height: 460 * Tv.u;
spacing: 24 * Tv.u;
alignment: start;
opacity: root.prep-a;
if root.stage == "prep": HorizontalLayout {
alignment: center;
Spinner { size: 72 * Tv.u; }
}
if root.stage == "error": HorizontalLayout {
alignment: center;
Icon { name: "warning"; size: 64 * Tv.u; ink: Tv.danger-ink; }
}
Title {
horizontal-alignment: center;
text: root.stage == "error" ? "Nem sikerült elindítani" : root.heading == "" ? root.title : root.title + " · " + root.heading;
}
Label {
horizontal-alignment: center;
text: root.stage == "error" ? root.error-text : root.stage-text;
wrap: word-wrap;
color: Tv.text-secondary;
}
Caption {
horizontal-alignment: center;
text: root.stage == "error" ? "Vissza: vissza az adatlapra" : root.detail-text;
wrap: word-wrap;
}
}
// ---- buffering ----
buf := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
width: 620 * Tv.u;
height: 190 * Tv.u;
radius: 40 * Tv.u;
frost: 3.2;
tint: Tv.smoke.with-alpha(0.4);
alpha: root.stage == "play" && root.buffering && !root.seeking ? root.alpha : 0;
VerticalLayout {
padding: 32 * Tv.u;
spacing: 20 * Tv.u;
alignment: center;
opacity: parent.alpha;
HorizontalLayout {
alignment: center;
Spinner { size: 56 * Tv.u; }
}
Label {
horizontal-alignment: center;
text: root.buffer-text == "" ? "Betöltés…" : root.buffer-text;
overflow: elide;
}
}
}
if root.stage == "play" && root.paused && !root.buffering && root.panel == 0 && !root.seeking && root.next-label == "": Icon {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 60 * Tv.u;
name: "pause";
size: 96 * Tv.u;
opacity: 0.85 * root.alpha;
}
// ---- seek preview ----
seek := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 60 * Tv.u;
width: 520 * Tv.u;
height: 108 * Tv.u;
radius: self.height / 2;
frost: 3.0;
tint: Tv.smoke.with-alpha(0.4);
alpha: root.stage == "play" && root.seeking ? root.alpha : 0;
HorizontalLayout {
alignment: center;
spacing: 18 * Tv.u;
opacity: parent.alpha;
Icon {
y: (parent.height - self.height) / 2;
name: root.seek-back ? "rewind" : "fast-forward";
size: 40 * Tv.u;
}
Text {
vertical-alignment: center;
text: root.seek-text;
font-size: 44 * Tv.u;
font-weight: 700;
color: Tv.text;
}
Text {
vertical-alignment: center;
text: root.seek-delta;
font-size: 26 * Tv.u;
color: Tv.text-secondary;
}
}
}
// ---- skip prompt (anime) ----
skip := GlassButton {
x: root.width - Tv.safe-x - self.width;
y: root.height - (root.osd-t > 0.5 ? 340 : 120) * Tv.u;
text: root.skip-label;
icon: "fast-forward";
primary: true;
accent: #e50914;
focused: root.skip-label != "" && root.osd-t < 0.5 && root.panel == 0;
alpha: root.stage == "play" && root.skip-label != "" && root.panel == 0 && root.next-label == "" ? root.alpha : 0;
}
// ---- up next ----
upnext := GlassPane {
x: root.width - Tv.safe-x - self.width;
y: root.height - 380 * Tv.u;
width: 520 * Tv.u;
height: 168 * Tv.u;
radius: 40 * Tv.u;
frost: 3.2;
tint: Tv.smoke.with-alpha(0.42);
alpha: root.next-label != "" ? root.alpha : 0;
VerticalLayout {
padding: 32 * Tv.u;
spacing: 6 * Tv.u;
opacity: parent.alpha;
Caption { text: "KÖVETKEZIK"; letter-spacing: 2 * Tv.u; }
Title { text: root.next-label; font-size: 34 * Tv.u; }
Label { text: root.next-text; }
}
}
// ---- controls ----
Rectangle {
x: Tv.safe-x;
y: root.height - 360 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
width: root.width - 2 * Tv.safe-x;
height: 300 * Tv.u;
opacity: root.osd-a;
Text {
x: 0;
y: 0;
text: root.heading;
font-size: 24 * Tv.u;
font-weight: 700;
color: #ff8a8a;
}
Text {
x: 0;
y: 34 * Tv.u;
width: parent.width - 420 * Tv.u;
text: root.title;
font-size: 44 * Tv.u;
font-weight: 700;
letter-spacing: -0.8 * Tv.u;
color: Tv.text;
overflow: elide;
}
Caption {
x: 0;
y: 96 * Tv.u;
width: parent.width - 420 * Tv.u;
text: root.info;
color: Tv.text-secondary;
}
Caption {
x: parent.width - 400 * Tv.u;
y: 96 * Tv.u;
width: 400 * Tv.u;
horizontal-alignment: right;
text: root.downloaded-text;
}
Text {
x: 0;
y: 172 * Tv.u;
text: root.time-text;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text;
}
Text {
x: parent.width - 300 * Tv.u;
y: 172 * Tv.u;
width: 300 * Tv.u;
horizontal-alignment: right;
text: root.remaining-text;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text-secondary;
}
}
bar := ProgressBar {
x: Tv.safe-x;
y: root.height - 222 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
width: root.width - 2 * Tv.safe-x;
height: (root.osd-area == 0 && root.panel == 0 ? 14 : 10) * Tv.u;
value: root.progress;
buffered: root.buffered;
fill: root.seeking ? #e50914 : Tv.text;
nested: false;
alpha: root.osd-a;
}
HorizontalLayout {
x: Tv.safe-x;
y: root.height - 146 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
height: 72 * Tv.u;
spacing: 20 * Tv.u;
alignment: start;
b0 := GlassButton { icon: root.paused ? "play" : "pause"; focused: root.buttons && root.osd-button == 0; alpha: root.osd-a; }
b1 := GlassButton { icon: "rewind"; text: "10 mp"; focused: root.buttons && root.osd-button == 1; alpha: root.osd-a; }
b2 := GlassButton { icon: "fast-forward"; text: "10 mp"; focused: root.buttons && root.osd-button == 2; alpha: root.osd-a; }
b3 := GlassButton { icon: "previous"; text: "Előző rész"; enabled: root.has-prev; focused: root.buttons && root.osd-button == 3; alpha: root.has-prev ? root.osd-a : 0; visible: root.has-prev; }
b4 := GlassButton { icon: "next"; text: "Következő rész"; enabled: root.has-next; focused: root.buttons && root.osd-button == 4; alpha: root.has-next ? root.osd-a : 0; visible: root.has-next; }
}
b5 := GlassButton {
x: root.width - Tv.safe-x - self.width;
y: root.height - 146 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
icon: "subtitles";
text: "Hang és felirat";
focused: root.buttons && root.osd-button == 5;
alpha: root.osd-a;
}
// ---- tracks panel ----
property <length> col-w: 400 * Tv.u;
property <length> panel-y: root.height - 400 * Tv.u;
property <bool> has-quality: root.quality.length > 0;
m-audio := GlassMenu {
x: Tv.safe-x;
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: root.col-w;
title: "Hang";
items: root.audio;
focused-index: root.audio-focus;
active: root.panel == 1;
alpha: root.alpha * root.panel-t;
accent: #e50914;
visible-rows: 6;
}
m-subs := GlassMenu {
x: Tv.safe-x + root.col-w + 28 * Tv.u;
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: root.col-w;
title: "Felirat";
items: root.subs;
focused-index: root.subs-focus;
active: root.panel == 2;
alpha: root.alpha * root.panel-t;
accent: #e50914;
visible-rows: 6;
}
m-sync := GlassMenu {
x: Tv.safe-x + 2 * (root.col-w + 28 * Tv.u);
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: 320 * Tv.u;
title: "Hangkésés";
items: root.sync;
focused-index: root.sync-focus;
active: root.panel == 3;
alpha: root.alpha * root.panel-t;
accent: #e50914;
visible-rows: 6;
}
m-quality := GlassMenu {
x: Tv.safe-x + 2 * (root.col-w + 28 * Tv.u) + 348 * Tv.u;
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: 330 * Tv.u;
title: "Minőség";
items: root.quality;
focused-index: root.quality-focus;
active: root.panel == 4;
alpha: root.has-quality ? root.alpha * root.panel-t : 0;
accent: #e50914;
visible-rows: 6;
}
out property <[GlassRect]> glass: [buf.glass, seek.glass, bar.glass, b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, skip.glass, upnext.glass];
out property <[GlassRect]> glass-audio: m-audio.glass;
out property <[GlassRect]> glass-subs: m-subs.glass;
out property <[GlassRect]> glass-sync: m-sync.glass;
out property <[GlassRect]> glass-quality: m-quality.glass;
}

132
ui/signin.slint Normal file
View File

@@ -0,0 +1,132 @@
// Sign-in (server address, user name, password) on a modal glass pane with
// the on-screen keyboard, and a plain message screen (loading, errors).
import { Tv, GlassRect, GlassPane, GlassButton, Keyboard, Spinner, Title, Label, Caption, Icon } from "@sf-ui/sf-ui.slint";
export component SignInScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> title: "Bejelentkezés";
in property <string> subtitle;
in property <string> placeholder;
in property <bool> secret;
in property <string> submit-label: "Tovább";
in property <int> min-length: 1;
in property <string> footer;
in property <bool> busy;
in-out property <string> text;
in-out property <string> error;
callback submitted(string);
callback cancelled();
public function key(event: KeyEvent) -> EventResult {
if root.busy {
return accept;
}
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: #e50914;
alpha: root.alpha;
kb := Keyboard {
x: 0;
y: 72 * Tv.u;
width: parent.width;
title: root.title;
subtitle: root.subtitle;
placeholder: root.placeholder;
secret: root.secret;
submit-label: root.submit-label;
min-length: root.min-length;
max-length: 200;
alpha: root.alpha * (root.busy ? 0.4 : 1);
active: !root.busy;
text <=> root.text;
error <=> root.error;
submitted(t) => { root.submitted(t); }
cancelled => { root.cancelled(); }
}
}
HorizontalLayout {
x: pane.x;
y: pane.y + pane.height + 28 * Tv.u;
width: pane.width;
height: 48 * Tv.u;
alignment: center;
spacing: 16 * Tv.u;
opacity: root.alpha;
if root.busy: Spinner { size: 40 * Tv.u; }
Caption {
vertical-alignment: center;
text: root.footer;
}
}
out property <[GlassRect]> glass: [pane.glass];
out property <[GlassRect]> glass-keyboard: kb.glass;
}
// Loading and errors, with up to two buttons.
export component MessageScreen inherits Rectangle {
in property <float> alpha: 1;
in property <bool> busy;
in property <string> title;
in property <string> text;
in property <string> action-a;
in property <string> action-b;
in property <int> action;
VerticalLayout {
x: Tv.safe-x;
width: root.width - 2 * Tv.safe-x;
y: 320 * Tv.u;
height: 440 * 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;
}
HorizontalLayout {
alignment: center;
spacing: 24 * Tv.u;
padding-top: 24 * Tv.u;
a := GlassButton {
text: root.action-a;
focused: root.action == 0;
alpha: root.action-a != "" ? root.alpha : 0;
visible: root.action-a != "";
}
b := GlassButton {
text: root.action-b;
focused: root.action == 1;
alpha: root.action-b != "" ? root.alpha : 0;
visible: root.action-b != "";
}
}
}
out property <[GlassRect]> glass: [a.glass, b.glass];
}

82
ui/types.slint Normal file
View File

@@ -0,0 +1,82 @@
// 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) | "include" | "exclude" | "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 watched; negative = no bar.
progress: float,
// Small pill over the top-left corner, and its tone ("dub", "sub", "accent", "").
badge: string,
badge-tone: string,
// "check" = watched mark (top-right).
mark: string,
// Big number over a dimmed picture (a season without its own poster).
big: string,
// Highlighted (the current season / franchise entry).
current: bool,
}
// One line of a checks list: state 1 = ok, 0 = failed, -1 = unknown.
export struct Check {
state: int,
label: string,
detail: string,
}
// One line of a page.
// hero big title block with buttons (detail pages, spotlight)
// 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 "poster" | "landscape" | "season"; captions under them)
// item list row: optional picture, title, meta, text, progress, chips
// 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,
progress: float,
col: int,
captions: bool,
cards: [Card],
chips: [Chip],
checks: [Check],
}