From af4e21ee6fd0d8877b32bb588bbb75aa40435295 Mon Sep 17 00:00:00 2001 From: Tamas Csikel Date: Sun, 1 Nov 2026 18:33:29 +0100 Subject: [PATCH] Netflex 0.1.2: new screens, and an ARM build for the Raspberry Pi - Pages from the web app: search, my list, anime hub and anime details, settings; the home and detail screens moved under src/screens on the shared page model (src/page.rs, ui/page.slint). - package.sh --arm cross-compiles support.bluefox.netflex--aarch64.tar.zst, which Fennec OS on ARM installs (docs/store.md). The release CI builds both: the GStreamer dev packages of amd64 and arm64 can't be installed together, so it swaps them between the two builds. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/release.yml | 28 +- AGENTS.md | 39 +- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 22 +- app.toml | 2 +- package.sh | 54 +- src/app.rs | 25 +- src/config.rs | 5 +- src/detail.rs | 572 ---------------- src/format.rs | 19 - src/home.rs | 823 ----------------------- src/main.rs | 17 +- src/page.rs | 44 +- src/player.rs | 1214 ++++++++++++++++++++++++++-------- src/screens/anime_detail.rs | 519 +++++++++++++++ src/screens/anime_hub.rs | 544 +++++++++++++++ src/screens/home.rs | 8 +- src/screens/mylist.rs | 123 ++++ src/screens/search.rs | 85 +++ src/screens/settings.rs | 1092 ++++++++++++++++++++++++++++++ tools/mock_server.py | 251 +++++++ ui/page.slint | 3 +- ui/player.slint | 3 + 24 files changed, 3696 insertions(+), 1800 deletions(-) delete mode 100644 src/detail.rs delete mode 100644 src/home.rs create mode 100644 src/screens/anime_detail.rs create mode 100644 src/screens/anime_hub.rs create mode 100644 src/screens/mylist.rs create mode 100644 src/screens/search.rs create mode 100644 src/screens/settings.rs diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index c91d0e3..6574e51 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,5 +1,6 @@ -# On a tag (v1.2.3): build the app and publish a release with the two store -# assets. sf-ui and sf-pack come from the Fennec SDK (public). +# On a tag (v1.2.3): build the app and publish a release with the store +# assets: app.toml, the x86-64 package and the aarch64 one (Raspberry Pi, +# docs/store.md in Fennec OS). sf-ui and sf-pack come from the Fennec SDK (public). # # Runner hygiene (shared host, little disk): runs in the runner image that is # already on the host (no image pull), uses no `uses:` actions (no action @@ -33,17 +34,34 @@ jobs: - name: Toolchain run: | export DEBIAN_FRONTEND=noninteractive + # arm64 libraries for the Raspberry Pi build (package.sh --arm): + # Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only. + . /etc/os-release + dpkg --add-architecture arm64 + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then + sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources + fi + [ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list + printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \ + "$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources apt-get update -qq + # Multiarch dev packages: both architectures at once. The GStreamer + # ones can't be: amd64 now, swapped to arm64 in the Build step. + libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libglib2.0-dev" apt-get install -y -qq --no-install-recommends build-essential pkg-config \ - libfontconfig1-dev libfreetype-dev libxkbcommon-dev \ + gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \ + $libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) \ libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev >/dev/null - rm -rf /var/lib/apt/lists/* - curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu "$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack - name: Build run: | export PATH="$CARGO_HOME/bin:$PATH" "$W/src/package.sh" + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \ + libgstreamer1.0-dev:arm64 libgstreamer-plugins-base1.0-dev:arm64 >/dev/null + rm -rf /var/lib/apt/lists/* + "$W/src/package.sh" --arm - name: Release env: TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/AGENTS.md b/AGENTS.md index d786d9b..50e2eb8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,17 +7,28 @@ Read first: ## 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) +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: screen stack, keys, input/picker/toast overlays, backdrop, start-up, sign-in +src/page.rs the line-based page engine: lines (L) and chips (Ch) -> layout, focus, scroll, lazy images +src/screens/mod.rs sections of the top nav, shared cards, Load, opening a card +src/screens/home.rs Kezdőlap: admin setup checklist, spotlight, Folytatás, the server's rows +src/screens/source.rs Filmek / Sorozatok: Ajánlott, Könyvtáram, Böngészés (genre, year, rating, sort) +src/screens/detail.rs film / series page: Play/Continue, My List, season cards, episodes, nCore versions +src/screens/anime_hub.rs Anime: Ajánlott, Könyvtáram, Böngészés (AniList filters) +src/screens/anime_detail.rs anime page: franchise seasons, release group, episodes, nyaa versions +src/screens/mylist.rs Listám: saved and history +src/screens/search.rs Keresés: embedded keyboard, results +src/screens/settings.rs Beállítások: account, users, server; admin: VPN, nCore, seeding, sources, anime, TMDB; player; look +src/player.rs source -> torrent -> probe -> sf_ui::video::Player; tracks, quality, prev/next, up next, skip intro +src/api.rs Netflex HTTP API (mirrors netflex/packages/client/src/api.ts) +src/config.rs server + token (config.toml), per-TV settings (device.toml: glass look, anime release groups) +src/format.rs Hungarian texts: times, dates, languages, genres +src/task.rs blocking work on a thread, result on the UI thread +ui/app.slint root: screen fades, one FocusScope -> Rust `key`, glass exports +ui/page.slint LinePage: draws the lines Rust lays out (nav, side list, keyboard) +ui/{player,signin,overlays,types}.slint +tools/mock_server.py stand-in server: Cinemeta + AniList data, admin pages, password "netflex", --video file ``` ## Rules of this codebase @@ -25,7 +36,11 @@ tools/mock_server.py stand-in server (real Cinemeta data, password "netflex", - - **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). +- **A new page** is a `Screen` (src/app.rs): `spec` returns lines, `activate` gets (line id, chip id). Never draw focus in Slint; the page engine does it. +- **Feature parity:** every screen follows a page of the web app (`netflex/apps/web/src`); the module docs name it. Check there first. +- **Texts are Hungarian.** Follow the Netflex web app's behaviour (resume rules, track picking, skip segments: `player.rs` tests). +- **Free-standing `GlassButton`** (outside a layout) needs `width: self.preferred-width`, else it fills its parent. +- **`match state.borrow().x { ... }` keeps the borrow for the whole match:** copy the value out first. ## Check your change diff --git a/Cargo.lock b/Cargo.lock index 1032101..81b1201 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3402,7 +3402,7 @@ dependencies = [ [[package]] name = "netflex-tv" -version = "0.1.1" +version = "0.1.2" dependencies = [ "anyhow", "env_logger", diff --git a/Cargo.toml b/Cargo.toml index 24b4702..1f6e47c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "netflex-tv" description = "Netflex for SmartFox: native TV client with Liquid Glass and hardware video playback" -version = "0.1.1" +version = "0.1.2" edition = "2024" # sf-ui (and Slint) are GPL-3.0 on a TV box. license = "GPL-3.0-only" diff --git a/README.md b/README.md index 67c7648..0e4f9fa 100644 --- a/README.md +++ b/README.md @@ -3,33 +3,35 @@ 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. +- **Képernyők:** ugyanaz, mint a webes felületen. Kezdőlap (az admin beállítási listája, kiemelt tartalom, Folytatás, a szerver sorai), Filmek és Sorozatok (Ajánlott, Könyvtáram, Böngészés műfajjal, évvel, értékeléssel), Anime (AniList: ajánlott, könyvtár, szűrők; adatlap évadokkal, kiadócsoport-választással), Listám (mentett és előzmények), Keresés képernyő-billentyűzettel, adatlap évadkártyákkal és epizódokkal, nCore verziók hangsávokkal. +- **Beállítások:** Fiók (eszközök, kijelentkezés), Szerver, Lejátszás, Megjelenés mindenkinek; az adminnak még Felhasználók, VPN (WireGuard, port forwarding, ellenőrzések), nCore, Visszatöltés (szabályok, torrentek), Források, Anime és Magyar szövegek (TMDB). +- **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. Minden hang- és feliratsáv választható, a hangkésés állítható és a szerveren megmarad, a minőség (HD / FHD / 4K) lejátszás közben váltható. Előző / következő rész, „Következik” visszaszámlálással, animénél intro- és összefoglaló-átugrás (AniSkip). A haladás 15 másodpercenként mentődik. - **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`). +Az sf-ui a [Fennec SDK](https://gitea.bluefox.support/fennec/sdk)-ból jön, git-függőségként (tag). A repó bárhol élhet, a Fennec OS forráskódja nem kell hozzá. Ha az sf-ui-t is fejleszted mellette, tedd a `.cargo/config.toml` fájlba (ne commitold): +```toml +[patch."https://gitea.bluefox.support/fennec/sdk"] +sf-ui = { path = "../sdk/sf-ui" } +``` ```sh -# Mock szerver: valódi Cinemeta katalógus, jelszó: netflex +# Mock szerver: valódi Cinemeta és AniList adatok, admin oldalak, 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). +- **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 az SDK `docs/sf-ui.md` fájljának 11. fejezetét). ## 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, és release-t csinál a két store-fájllal. +3. A Gitea CI (`.gitea/workflows/release.yml`) megépíti, és release-t csinál a két store-fájllal. Secret nem kell hozzá. -CI secret: -- `SMARTFOX_TOKEN`: olvasási jog a `bluefox/fox-in-the-box` repóhoz. - -Helyben: `./package.sh`. +Helyben: `./package.sh` (kell hozzá az `sf-pack`, lásd a script fejlécét). A TV-n: Store → Források → a repó címe. diff --git a/app.toml b/app.toml index 54698d9..dfbd073 100644 --- a/app.toml +++ b/app.toml @@ -2,7 +2,7 @@ id = "support.bluefox.netflex" name = "Netflex" # Release versions only (1.2.3). Bump it (and Cargo.toml) for every release. -version = "0.1.1" +version = "0.1.2" 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." diff --git a/package.sh b/package.sh index f5ba052..1141a47 100755 --- a/package.sh +++ b/package.sh @@ -1,19 +1,55 @@ #!/usr/bin/env bash -# Builds the two store release assets into dist/: app.toml and -# support.bluefox.netflex-.tar.zst. +# Builds the store release assets into dist/: +# +# ./package.sh app.toml and support.bluefox.netflex-.tar.zst +# (x86-64; dist/ is emptied first) +# ./package.sh --arm adds support.bluefox.netflex--aarch64.tar.zst +# (Raspberry Pi, cross-compiled) # # Build on Debian trixie or older (the TV's glibc), with the GStreamer dev # packages (libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev) and # sf-pack from the Fennec SDK: # cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.0 sf-pack +# --arm needs gcc-aarch64-linux-gnu and the arm64 (multiarch) dev packages +# instead. The GStreamer dev packages of the two architectures can't be +# installed together: swap them between the two runs, as +# .gitea/workflows/release.yml does. 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 build pkg dist -sf-pack verify dist +id=$(sed -n 's/^id *= *"\(.*\)".*/\1/p' app.toml | head -1) +version=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' app.toml | head -1) + +# pack : the package with this binary. +pack() { + rm -rf pkg + mkdir -p pkg/bin + cp app.toml icon.png pkg/ + install -m755 "$1" pkg/bin/netflex-tv + sf-pack build pkg "$2" + sf-pack verify "$2" + rm -rf pkg +} + +if [ "${1:-}" != --arm ]; then + cargo build --release --locked + rm -rf dist + pack "$target/release/netflex-tv" dist +else + t=aarch64-unknown-linux-gnu + export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc + export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++ + export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/ + export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig + rustup target list --installed | grep -qx "$t" || rustup target add "$t" + cargo build --release --locked --target "$t" + rm -rf dist-arm + pack "$target/$t/release/netflex-tv" dist-arm + # Fennec OS on ARM looks for --aarch64.tar.zst (docs/store.md). + mkdir -p dist + mv "dist-arm/$id-$version.tar.zst" "dist/$id-$version-aarch64.tar.zst" + [ -f dist/app.toml ] || mv dist-arm/app.toml dist/ + rm -rf dist-arm +fi +ls -l dist diff --git a/src/app.rs b/src/app.rs index 81ae4eb..85490dc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -115,9 +115,7 @@ type SelectDone = Box; enum Effect { Push(Box), - Pop, Refresh, - Section(usize), Play(player::Request), } @@ -190,9 +188,6 @@ impl<'a> Cx<'a> { pub fn api(&self) -> Api { self.c.api() } - pub fn api_base_image(&self, url: Option<&str>) -> String { - self.c.state.borrow().api.image(url, false) - } pub fn user(&self) -> User { self.c.state.borrow().user.clone() } @@ -235,15 +230,9 @@ impl<'a> Cx<'a> { pub fn push(&self, s: Box) { self.c.effects.borrow_mut().push(Effect::Push(s)); } - pub fn pop(&self) { - self.c.effects.borrow_mut().push(Effect::Pop); - } pub fn refresh(&self) { self.c.effects.borrow_mut().push(Effect::Refresh); } - pub fn section(&self, n: usize) { - self.c.effects.borrow_mut().push(Effect::Section(n)); - } pub fn play(&self, r: player::Request) { self.c.effects.borrow_mut().push(Effect::Play(r)); } @@ -282,10 +271,6 @@ impl<'a> Cx<'a> { e.view.focus_on(line, col); } } - /// Physical pixels per design pixel. - pub fn px(&self) -> f32 { - self.c.px() - } } impl Controller { @@ -370,11 +355,8 @@ impl Controller { self.state.borrow().api.clone() } - pub fn is_admin(&self) -> bool { - self.state.borrow().user.is_admin - } - fn show(&self, screen: &'static str) { + pub fn show(&self, screen: &'static str) { self.state.borrow_mut().screen = screen; if let Some(ui) = self.ui() { ui.set_screen(screen.into()); @@ -886,9 +868,7 @@ impl Controller { for e in effects { match e { Effect::Push(s) => self.push_now(s), - Effect::Pop => self.pop_now(), Effect::Refresh => refresh = true, - Effect::Section(n) => self.section_now(n), Effect::Play(r) => player::play(self, r), } } @@ -1050,7 +1030,8 @@ impl Controller { if self.state.borrow().select.is_some() { return self.select_key(a); } - match self.state.borrow().screen { + let screen = self.state.borrow().screen; + match screen { "message" => return self.message_key(a), "player" => return player::key(self, a, repeat), _ => {} diff --git a/src/config.rs b/src/config.rs index c2bef7b..09130b3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -58,6 +58,9 @@ pub struct Local { /// "auto" | "full" | "light" | "off" #[serde(default = "auto")] pub glass: String, + /// The release group picked per anime (AniList id -> "SubsPlease|1080"). + #[serde(default)] + pub anime_groups: std::collections::HashMap, } fn auto() -> String { @@ -66,7 +69,7 @@ fn auto() -> String { impl Default for Local { fn default() -> Self { - Local { glass: auto() } + Local { glass: auto(), anime_groups: Default::default() } } } diff --git a/src/detail.rs b/src/detail.rs deleted file mode 100644 index a2291a8..0000000 --- a/src/detail.rs +++ /dev/null @@ -1,572 +0,0 @@ -//! 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, - progress: Vec, - listed: bool, - /// The season whose episodes are shown. - season: i32, - episodes: Vec, - ep_model: Rc>, - /// 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 = 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 = d.ep_model.iter().collect(); - let eps: Vec = 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")); - } -} diff --git a/src/format.rs b/src/format.rs index 74406ef..f5ab767 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,7 +1,5 @@ //! 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 }; @@ -28,23 +26,6 @@ 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 = 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::>().join(", ")); - } - parts.join(" · ") -} /// Cinemeta's English genre names in Hungarian. pub fn genre(g: &str) -> String { diff --git a/src/home.rs b/src/home.rs deleted file mode 100644 index 95a77e5..0000000 --- a/src/home.rs +++ /dev/null @@ -1,823 +0,0 @@ -//! 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, - /// 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, cursor: Option, page: u32 }, -} - -struct RowData { - title: String, - landscape: bool, - items: Vec, - model: Rc>, - col: usize, - requested: HashSet, - more: More, - loading_more: bool, -} - -impl RowData { - fn new(title: &str, landscape: bool, items: Vec, more: More) -> RowData { - let model = Rc::new(VecModel::from(items.iter().map(Item::card).collect::>())); - 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, - row: usize, - model: Rc>, - /// Bumped on every tab load: late answers for an old tab are dropped. - generation: u64, - genres: Vec, - 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>>, - /// 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 = 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 = 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) -> Vec { - let mut rows = Vec::new(); - let mut it = items.into_iter().peekable(); - while it.peek().is_some() { - let chunk: Vec = 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, 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::>()); - 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>, - 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 = 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::>(), - 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 = 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); -} diff --git a/src/main.rs b/src/main.rs index 8c74246..b9e9c6b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,10 +12,10 @@ mod api; mod app; mod config; -mod detail; mod format; -mod home; +mod page; mod player; +mod screens; mod task; use slint::{ComponentHandle, Model}; @@ -39,16 +39,17 @@ fn main() -> anyhow::Result<()> { 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_page().iter()); + p.extend(ui.get_glass_page_keyboard().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()); + p.extend(ui.get_glass_player_quality().iter()); + p.extend(ui.get_glass_input().iter()); + p.extend(ui.get_glass_input_keyboard().iter()); + p.extend(ui.get_glass_select().iter()); + p.extend(ui.get_glass_toast().iter()); })?; glass.set_palette(sf_ui::Palette::from_hex(["#ff4a3d", "#8c0b14", "#120305"])); diff --git a/src/page.rs b/src/page.rs index 91c7eec..1146b26 100644 --- a/src/page.rs +++ b/src/page.rs @@ -17,8 +17,6 @@ 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)] @@ -32,7 +30,6 @@ pub enum Kind { Item, Checks, Keyboard, - Gap, } impl Kind { @@ -47,7 +44,6 @@ impl Kind { Kind::Item => "item", Kind::Checks => "checks", Kind::Keyboard => "keyboard", - Kind::Gap => "gap", } } } @@ -99,8 +95,19 @@ impl Ch { 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(); + // Onest 23/600: about 13.4 px per character (measured on the TV + // screenshots); capitals and wide letters more, narrow ones less. + let chars: f32 = self + .text + .chars() + .map(|c| match c { + 'i' | 'l' | 'í' | 'j' | '.' | ',' | ':' | '·' | '(' | ')' | ' ' => 7.5, + 'm' | 'w' | 'M' | 'W' => 20.0, + c if c.is_uppercase() || c.is_ascii_digit() => 16.0, + _ => 13.4, + }) + .sum::() + + 6.0; if self.text.is_empty() { return 64.0; } @@ -240,11 +247,6 @@ impl L { 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) -> L { self.subtitle = s.into(); self @@ -254,14 +256,6 @@ impl L { 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 @@ -456,13 +450,11 @@ fn layout(lines: &[L], side: bool) -> (Vec, f32) { 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, @@ -573,12 +565,6 @@ impl View { (l.id.clone(), item.unwrap_or_default()) } - pub fn focused_kind(&self) -> Option { - 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 { @@ -887,10 +873,6 @@ impl View { None } - /// Replaces one card's picture (a backdrop loaded elsewhere...). - pub fn line_index(&self, id: &str) -> Option { - self.lines.iter().position(|l| l.id == id) - } } pub fn card_size(style: &str) -> (f32, f32) { diff --git a/src/player.rs b/src/player.rs index 80cbcb5..2065457 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,51 +1,112 @@ -//! 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. +//! Playback, for films and series (nCore) and anime (nyaa): pick a source, +//! start the torrent on the server, probe the file, then GStreamer plays the +//! server's raw stream (`/api/stream`, range requests) while the torrent +//! keeps downloading. As the web app's player/PlayerPage.tsx, +//! AnimePlayerPage.tsx and VideoPlayer.tsx. //! //! 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. +//! +//! Remote, controls hidden: OK = play/pause (or the skip prompt), +//! left/right = seek (held: faster), up = tracks, down = buttons, Back = leave. +//! Controls shown: the seek bar (left/right seeks) or the button row +//! (play, -10, +10, previous, next, tracks); Back hides them. +use std::collections::HashSet; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, 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}; +use crate::api::{self, AnimeSource, Api, MediaTrack, MediaType, ProbeInfo, SkipTime, SourceCandidate, TorrentStatus}; +use crate::app::{Action, Controller}; +use crate::{MenuItem, config, 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)] +pub enum Target { + Title { kind: MediaType, id: String, ep: Option<(i32, i32)> }, + Anime { id: i64, episode: i32 }, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone)] +pub struct Request { + pub target: Target, + /// Known before the details load (for the preparing screen). + pub title: String, + pub backdrop: Option, + /// The nCore torrent / nyaa upload picked by hand. + pub pinned: Option, + /// "auto", "hd", "fhd", "4k" (films and series). + pub quality: &'static str, + /// Start here (a quality switch); None: where the user stopped. + pub resume: Option, +} + +impl Request { + pub fn title(kind: MediaType, id: &str, title: String, ep: Option<(i32, i32)>, backdrop: Option) -> Request { + let ep = if kind == MediaType::Tv { ep } else { None }; + Request { target: Target::Title { kind, id: id.into(), ep }, title, backdrop, pinned: None, quality: "auto", resume: None } + } + + pub fn anime(id: i64, name: String, episode: i32, banner: Option) -> Request { + Request { target: Target::Anime { id, episode: episode.max(1) }, title: name, backdrop: banner, pinned: None, quality: "auto", resume: None } + } + + fn with_target(&self, target: Target) -> Request { + Request { target, pinned: None, resume: None, ..self.clone() } + } +} + +const QUALITIES: [(&str, &str); 4] = [("auto", "Automatikus"), ("hd", "HD · 720p"), ("fhd", "FHD · 1080p"), ("4k", "4K · 2160p")]; + +fn release_quality(c: &SourceCandidate) -> Option<&'static str> { + match c.parsed.resolution { + Some(r) if r >= 2160 => Some("4k"), + Some(r) if r >= 1080 => Some("fhd"), + Some(r) if r >= 720 => Some("hd"), + _ => None, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Stage { Prep, Play, Error, } +#[derive(Debug, Clone)] struct Media { hash: String, file: i64, probe: ProbeInfo, } +/// An opening / recap / ending (AniSkip). +#[derive(Debug, Clone, PartialEq)] +struct Skip { + kind: &'static str, + start: f64, + end: f64, +} + +/// Everything the prep task finds out. +struct Prepared { + media: Media, + title: String, + heading: String, + resume: f64, + next: Option, + prev: Option, + next_label: String, + /// Qualities with a source (films and series). + qualities: Vec<&'static str>, + skips: Vec, + /// Anime with "prefer dub": English audio first. + prefer_audio: Option, +} + /// 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)] @@ -59,26 +120,49 @@ struct Track { } const SYNC_STEPS: [i64; 13] = [-2000, -1000, -500, -300, -200, -100, 0, 100, 200, 300, 500, 1000, 2000]; -const OSD_SECONDS: u64 = 4; +const OSD: Duration = Duration::from_secs(5); const SAVE_EVERY: Duration = Duration::from_secs(15); +const STATUS_EVERY: Duration = Duration::from_secs(3); +const KEEPALIVE_EVERY: Duration = Duration::from_secs(30); +/// A skip prompt shows by itself this long, then only with the controls. +const SKIP_PROMPT: Duration = Duration::from_secs(8); +const NEXT_COUNTDOWN: u64 = 8; const COMMENTARY: [&str; 3] = ["commentary", "kommentár", "director"]; const FORCED: [&str; 3] = ["forced", "kényszerített", "sign"]; +#[cfg(target_os = "linux")] +type Video = sf_ui::video::Player; + +/// No player off Linux (UI work on Windows): playback stops at an error. +#[cfg(not(target_os = "linux"))] +struct Video; +#[cfg(not(target_os = "linux"))] +impl Video { + fn toggle(&mut self) -> bool { + false + } + fn set_audio(&self, _: i32) {} + fn set_text(&self, _: Option) {} + fn set_audio_offset_ms(&self, _: i64) {} +} + pub struct Player { req: Request, generation: u64, cancel: Arc, stage: Stage, - media: Option, - #[cfg(target_os = "linux")] - video: Option, + prep: Option, + video: Option