Initial Netflex TV app
This commit is contained in:
1693
src/api.rs
Normal file
1693
src/api.rs
Normal file
File diff suppressed because it is too large
Load Diff
1293
src/app.rs
Normal file
1293
src/app.rs
Normal file
File diff suppressed because it is too large
Load Diff
98
src/config.rs
Normal file
98
src/config.rs
Normal 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
572
src/detail.rs
Normal 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
399
src/format.rs
Normal 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 & <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(""", "\"").replace("&", "&").replace("'", "'").replace("<", "<").replace(">", ">");
|
||||
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
823
src/home.rs
Normal 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
62
src/main.rs
Normal 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
963
src/page.rs
Normal 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
714
src/player.rs
Normal 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
608
src/screens/detail.rs
Normal 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
283
src/screens/home.rs
Normal 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
210
src/screens/mod.rs
Normal 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
559
src/screens/source.rs
Normal 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
49
src/task.rs
Normal 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:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user