YouTube 2.0.0: native client without ads
All checks were successful
release / release (push) Successful in 10m13s
All checks were successful
release / release (push) Successful in 10m13s
Replaces the web app (youtube.com/tv in Chromium) with a native Rust + Slint client on sf-ui, built on Netflex TV's page engine. - InnerTube: web client for public pages, the TV client with the account's OAuth token for personal ones, visionOS (direct URLs) for streams, the TV client with yt-dlp's ejs solver (QuickJS) as fallback. - One version, no ads: ad breaks are never requested, ad renderers are skipped in feeds. SponsorBlock skips sponsored parts. - Sign-in with a QR code / youtube.com/activate (OAuth device flow). - Signed out: subscriptions and history on the TV; a home filled with this week's popular Hungarian videos when YouTube's is empty. - Playback: one-quality DASH manifest for GStreamer, H.264 up to 1080p or AV1 up to 4K, captions, quality switching, up next, resume. - Release builds for x86-64 and the Raspberry Pi (aarch64). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
959
src/app.rs
Normal file
959
src/app.rs
Normal file
@@ -0,0 +1,959 @@
|
||||
//! The controller: the screen stack, keys, overlays (QR sign-in, toast),
|
||||
//! the backdrop. (Its page and screen model comes from Netflex TV.)
|
||||
//!
|
||||
//! Browsing screens implement `Screen`: they describe their page as lines
|
||||
//! (`spec`) and react to activation. While one of their methods runs it is
|
||||
//! taken out of the stack, so methods may freely start tasks and request
|
||||
//! effects (push, play...), which run when the method returns.
|
||||
|
||||
use std::any::Any;
|
||||
use std::cell::{Cell, Ref, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use slint::platform::Key;
|
||||
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
|
||||
|
||||
use crate::config::{self, Account, Library, Settings};
|
||||
use crate::page::{Focus, Kind, Spec, View};
|
||||
use crate::yt::{self, Client};
|
||||
use crate::{App, player, screens, task};
|
||||
|
||||
/// A remote / keyboard key, as screens see it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
Ok,
|
||||
Back,
|
||||
PlayPause,
|
||||
}
|
||||
|
||||
fn action(text: &str) -> Option<Action> {
|
||||
let is = |k: Key| text == SharedString::from(k).as_str();
|
||||
Some(if is(Key::UpArrow) {
|
||||
Action::Up
|
||||
} else if is(Key::DownArrow) {
|
||||
Action::Down
|
||||
} else if is(Key::LeftArrow) {
|
||||
Action::Left
|
||||
} else if is(Key::RightArrow) {
|
||||
Action::Right
|
||||
} else if is(Key::Return) {
|
||||
Action::Ok
|
||||
} else if is(Key::Escape) || is(Key::Backspace) || is(Key::Back) {
|
||||
Action::Back
|
||||
} else if text == " " {
|
||||
Action::PlayPause
|
||||
} else {
|
||||
return None;
|
||||
})
|
||||
}
|
||||
|
||||
/// Top navigation sections.
|
||||
pub const SECTIONS: [&str; 5] = ["Kezdőlap", "Feliratkozások", "Könyvtár", "Keresés", "Beállítások"];
|
||||
pub const SETTINGS: usize = 4;
|
||||
|
||||
pub const PALETTE: [&str; 3] = ["#ff6a5c", "#a3121c", "#16070a"];
|
||||
|
||||
/// A browsing screen.
|
||||
pub trait Screen: Any {
|
||||
/// The page: lines and frame.
|
||||
fn spec(&mut self, cx: &Cx) -> Spec;
|
||||
/// OK on an element of a line.
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str);
|
||||
/// The focus moved (backdrop...).
|
||||
fn focus(&mut self, _cx: &Cx, _line: &str, _item: &str) {}
|
||||
/// Back; true = handled (the screen stays).
|
||||
fn back(&mut self, _cx: &Cx) -> bool {
|
||||
false
|
||||
}
|
||||
/// The focus is near the end of list `list`.
|
||||
fn more(&mut self, _cx: &Cx, _list: &str) {}
|
||||
/// On top again (back from a child or the player).
|
||||
fn shown(&mut self, _cx: &Cx) {}
|
||||
/// Settings side list: tab `i`.
|
||||
fn side(&mut self, _cx: &Cx, _i: usize) {}
|
||||
/// The search keyboard's text changed (`submit`: the search key).
|
||||
fn query(&mut self, _cx: &Cx, _text: &str, _submit: bool) {}
|
||||
fn as_any(&mut self) -> &mut dyn Any;
|
||||
}
|
||||
|
||||
enum Effect {
|
||||
Push(Box<dyn Screen>),
|
||||
Refresh,
|
||||
Play(player::Request),
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
id: u64,
|
||||
screen: Option<Box<dyn Screen>>,
|
||||
view: View,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub client: Client,
|
||||
pub account: Account,
|
||||
pub settings: Settings,
|
||||
pub library: Library,
|
||||
stack: Vec<Entry>,
|
||||
next_id: u64,
|
||||
/// "page", "player"
|
||||
pub screen: &'static str,
|
||||
pub player: Option<player::Player>,
|
||||
/// The QR sign-in running (its generation).
|
||||
link: Option<u64>,
|
||||
}
|
||||
|
||||
pub struct Inner {
|
||||
pub ui: slint::Weak<App>,
|
||||
pub glass: sf_ui::Glass,
|
||||
pub images: sf_ui::images::Images,
|
||||
pub state: RefCell<State>,
|
||||
effects: RefCell<Vec<Effect>>,
|
||||
toast_timer: slint::Timer,
|
||||
backdrop_timer: slint::Timer,
|
||||
backdrop_key: RefCell<String>,
|
||||
pub colours: Rc<RefCell<HashMap<String, slint::Color>>>,
|
||||
search_timer: slint::Timer,
|
||||
link_timer: slint::Timer,
|
||||
link_polling: Cell<bool>,
|
||||
link_gen: Cell<u64>,
|
||||
}
|
||||
|
||||
/// Cheap to clone; every callback holds one.
|
||||
#[derive(Clone)]
|
||||
pub struct Controller(pub Rc<Inner>);
|
||||
|
||||
impl std::ops::Deref for Controller {
|
||||
type Target = Inner;
|
||||
fn deref(&self) -> &Inner {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// What a screen's methods get: the controller and the screen's own id.
|
||||
pub struct Cx<'a> {
|
||||
pub c: &'a Controller,
|
||||
pub id: u64,
|
||||
}
|
||||
|
||||
/// How the backdrop picture shows.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Look {
|
||||
/// Channel pages: sharp, dark towards the left and bottom.
|
||||
Sharp,
|
||||
/// Browsing: blurred and dim behind the rows.
|
||||
Soft,
|
||||
}
|
||||
|
||||
impl<'a> Cx<'a> {
|
||||
pub fn client(&self) -> Client {
|
||||
self.c.client()
|
||||
}
|
||||
pub fn signed_in(&self) -> bool {
|
||||
self.c.state.borrow().account.signed_in()
|
||||
}
|
||||
pub fn settings(&self) -> Settings {
|
||||
self.c.state.borrow().settings.clone()
|
||||
}
|
||||
pub fn set_settings(&self, s: Settings) {
|
||||
s.save();
|
||||
self.c.state.borrow_mut().settings = s;
|
||||
}
|
||||
pub fn account(&self) -> Account {
|
||||
self.c.state.borrow().account.clone()
|
||||
}
|
||||
pub fn library(&self) -> Ref<'_, Library> {
|
||||
Ref::map(self.c.state.borrow(), |s| &s.library)
|
||||
}
|
||||
/// Changes the library and saves it.
|
||||
pub fn update_library<R>(&self, f: impl FnOnce(&mut Library) -> R) -> R {
|
||||
self.c.update_library(f)
|
||||
}
|
||||
|
||||
/// Runs `work` on a thread; `done` gets this screen back (if it still
|
||||
/// exists) on the UI thread. The page is rebuilt afterwards.
|
||||
pub fn spawn<T: Screen, R: Send + 'static>(&self, work: impl FnOnce() -> R + Send + 'static, done: impl FnOnce(&mut T, &Cx, R) + 'static) {
|
||||
let c = self.c.clone();
|
||||
let id = self.id;
|
||||
task::spawn(work, move |r| c.with::<T>(id, move |s, cx| done(s, cx, r)));
|
||||
}
|
||||
|
||||
/// Fire and forget, then rebuild this screen's page (and run `then`).
|
||||
pub fn call<T: Screen>(&self, what: &'static str, work: impl FnOnce() -> anyhow::Result<()> + Send + 'static, then: impl FnOnce(&mut T, &Cx, bool) + 'static) {
|
||||
self.spawn::<T, _>(work, move |s, cx, r| {
|
||||
let ok = r.is_ok();
|
||||
if let Err(e) = r {
|
||||
cx.error(what, &e);
|
||||
}
|
||||
then(s, cx, ok);
|
||||
});
|
||||
}
|
||||
|
||||
/// Shows an error (or signs out when the account's token is gone).
|
||||
pub fn error(&self, what: &str, e: &anyhow::Error) {
|
||||
self.c.error(what, e);
|
||||
}
|
||||
|
||||
pub fn push(&self, s: Box<dyn Screen>) {
|
||||
self.c.effects.borrow_mut().push(Effect::Push(s));
|
||||
}
|
||||
pub fn refresh(&self) {
|
||||
self.c.effects.borrow_mut().push(Effect::Refresh);
|
||||
}
|
||||
pub fn play(&self, r: player::Request) {
|
||||
self.c.effects.borrow_mut().push(Effect::Play(r));
|
||||
}
|
||||
pub fn toast(&self, text: &str) {
|
||||
self.c.toast(text, false);
|
||||
}
|
||||
pub fn backdrop(&self, url: &str, look: Look, key: &str) {
|
||||
self.c.backdrop(url, look, key);
|
||||
}
|
||||
}
|
||||
|
||||
impl Controller {
|
||||
pub fn new(ui: &App, glass: sf_ui::Glass, images: sf_ui::images::Images) -> Controller {
|
||||
let account = Account::load();
|
||||
let settings = Settings::load();
|
||||
let client = Client::new(account.signed_in().then(|| account.refresh_token.clone()));
|
||||
let state = State {
|
||||
client,
|
||||
account,
|
||||
settings,
|
||||
library: Library::load(),
|
||||
stack: Vec::new(),
|
||||
next_id: 1,
|
||||
screen: "page",
|
||||
player: None,
|
||||
link: None,
|
||||
};
|
||||
let c = Controller(Rc::new(Inner {
|
||||
ui: ui.as_weak(),
|
||||
glass,
|
||||
images,
|
||||
state: RefCell::new(state),
|
||||
effects: RefCell::default(),
|
||||
toast_timer: slint::Timer::default(),
|
||||
backdrop_timer: slint::Timer::default(),
|
||||
backdrop_key: RefCell::default(),
|
||||
colours: Rc::default(),
|
||||
search_timer: slint::Timer::default(),
|
||||
link_timer: slint::Timer::default(),
|
||||
link_polling: Cell::new(false),
|
||||
link_gen: Cell::new(0),
|
||||
}));
|
||||
config::apply_look(&c.glass, &c.state.borrow().settings.glass);
|
||||
|
||||
let k = c.clone();
|
||||
ui.on_key(move |text, repeat| match action(&text) {
|
||||
Some(a) => {
|
||||
k.key(a, repeat);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
let k = c.clone();
|
||||
ui.on_search_submitted(move |t| k.search(t.to_string(), true));
|
||||
let k = c.clone();
|
||||
ui.on_search_changed(move |t| k.search(t.to_string(), false));
|
||||
let k = c.clone();
|
||||
ui.on_search_exit_down(move || k.leave_keyboard(true));
|
||||
let k = c.clone();
|
||||
ui.on_search_exit_up(move || k.leave_keyboard(false));
|
||||
let k = c.clone();
|
||||
ui.on_search_cancelled(move || k.leave_keyboard(false));
|
||||
ui.set_page_nav_items(ModelRc::new(VecModel::from(SECTIONS.iter().map(|s| SharedString::from(*s)).collect::<Vec<_>>())));
|
||||
c
|
||||
}
|
||||
|
||||
pub fn ui(&self) -> Option<App> {
|
||||
self.ui.upgrade()
|
||||
}
|
||||
|
||||
pub fn px(&self) -> f32 {
|
||||
self.ui()
|
||||
.map(|ui| {
|
||||
let s = ui.window().size();
|
||||
(s.width as f32 / 1920.0).min(s.height as f32 / 1080.0).max(0.5)
|
||||
})
|
||||
.unwrap_or(1.0)
|
||||
}
|
||||
|
||||
pub fn client(&self) -> Client {
|
||||
self.state.borrow().client.clone()
|
||||
}
|
||||
|
||||
pub fn update_library<R>(&self, f: impl FnOnce(&mut Library) -> R) -> R {
|
||||
let mut st = self.state.borrow_mut();
|
||||
let r = f(&mut st.library);
|
||||
st.library.save();
|
||||
r
|
||||
}
|
||||
|
||||
pub fn show(&self, screen: &'static str) {
|
||||
self.state.borrow_mut().screen = screen;
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_screen(screen.into());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
self.account_label();
|
||||
self.section_now(0);
|
||||
if self.state.borrow().account.signed_in() {
|
||||
// The name may have changed; this also checks the token.
|
||||
let client = self.client();
|
||||
let c = self.clone();
|
||||
task::spawn(move || client.account(), move |r| match r {
|
||||
Ok((name, photo)) if !name.is_empty() => {
|
||||
let mut st = c.state.borrow_mut();
|
||||
st.account.name = name;
|
||||
st.account.photo = photo;
|
||||
st.account.save();
|
||||
drop(st);
|
||||
c.account_label();
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => c.error("account", &e),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
player::stop(self, true);
|
||||
}
|
||||
|
||||
/// Shows an error; a lost sign-in signs out.
|
||||
pub fn error(&self, what: &str, e: &anyhow::Error) {
|
||||
let lost = e.chain().any(|c| c.downcast_ref::<yt::YtError>().is_some_and(|y| y.status == 401)) && self.state.borrow().account.signed_in();
|
||||
if lost {
|
||||
let c = self.clone();
|
||||
slint::Timer::single_shot(Duration::from_millis(1), move || c.signed_out(true));
|
||||
return;
|
||||
}
|
||||
log::warn!("{what}: {e:#}");
|
||||
self.toast(&yt::describe(e), true);
|
||||
}
|
||||
|
||||
fn account_label(&self) {
|
||||
let (on, name) = {
|
||||
let st = self.state.borrow();
|
||||
(st.account.signed_in(), st.account.name.clone())
|
||||
};
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_page_account_label(if on { (if name.is_empty() { "Bejelentkezve".to_string() } else { name }).into() } else { "".into() });
|
||||
ui.set_page_account_ok(on);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- QR sign-in ----
|
||||
|
||||
/// Shows a code and a QR code; the user confirms on a phone.
|
||||
pub fn sign_in(&self) {
|
||||
let generation = self.link_gen.get() + 1;
|
||||
self.link_gen.set(generation);
|
||||
self.state.borrow_mut().link = Some(generation);
|
||||
self.link_timer.stop();
|
||||
self.link_polling.set(false);
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_link_code("".into());
|
||||
ui.set_link_url("".into());
|
||||
ui.set_link_qr(Default::default());
|
||||
ui.set_link_status("Kód kérése a YouTube-tól…".into());
|
||||
ui.set_link_busy(true);
|
||||
ui.set_link_open(true);
|
||||
}
|
||||
let client = self.client();
|
||||
let c = self.clone();
|
||||
task::spawn(move || yt::auth::start(&client.agent), move |r| {
|
||||
if c.state.borrow().link != Some(generation) {
|
||||
return;
|
||||
}
|
||||
match r {
|
||||
Ok(code) => c.link_show(generation, code),
|
||||
Err(e) => c.link_status(&format!("{} · OK: újra", yt::describe(&e)), false),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn link_status(&self, text: &str, busy: bool) {
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_link_status(text.into());
|
||||
ui.set_link_busy(busy);
|
||||
}
|
||||
}
|
||||
|
||||
fn link_show(&self, generation: u64, code: yt::auth::DeviceCode) {
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_link_code(code.user_code.clone().into());
|
||||
ui.set_link_url(code.url.trim_start_matches("https://").trim_start_matches("www.").into());
|
||||
ui.set_link_qr(crate::qr::image(&code.qr_link()));
|
||||
}
|
||||
self.link_status("Várakozás a megerősítésre…", true);
|
||||
let deadline = Instant::now() + Duration::from_secs(code.expires_in);
|
||||
let code = Rc::new(code);
|
||||
let c = self.clone();
|
||||
self.link_timer.start(slint::TimerMode::Repeated, Duration::from_secs(code.interval), move || {
|
||||
if c.state.borrow().link != Some(generation) || c.link_polling.get() {
|
||||
return;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return c.sign_in();
|
||||
}
|
||||
c.link_polling.set(true);
|
||||
let client = c.client();
|
||||
let code2 = (*code).clone();
|
||||
let c2 = c.clone();
|
||||
task::spawn(move || yt::auth::poll(&client.agent, &code2), move |r| {
|
||||
c2.link_polling.set(false);
|
||||
if c2.state.borrow().link != Some(generation) {
|
||||
return;
|
||||
}
|
||||
match r {
|
||||
Ok(yt::auth::Poll::Pending | yt::auth::Poll::SlowDown) => {}
|
||||
Ok(yt::auth::Poll::Done { refresh, access, expires_in }) => c2.signed_in(refresh, access, expires_in),
|
||||
Ok(yt::auth::Poll::Expired) => c2.sign_in(),
|
||||
Ok(yt::auth::Poll::Denied) => {
|
||||
c2.link_timer.stop();
|
||||
c2.link_status("A bejelentkezést elutasítottad. · OK: új kód", false);
|
||||
}
|
||||
Err(e) => log::warn!("sign-in poll: {e:#}"),
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn signed_in(&self, refresh: String, access: String, expires_in: u64) {
|
||||
self.link_timer.stop();
|
||||
self.link_status("Bejelentkezés…", true);
|
||||
let client = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.account = Account { refresh_token: refresh.clone(), ..Account::default() };
|
||||
st.account.save();
|
||||
st.client.set_session(Some(yt::Session { refresh_token: refresh, access_token: access, expires: yt::now() + expires_in }));
|
||||
st.client.clone()
|
||||
};
|
||||
let c = self.clone();
|
||||
task::spawn(move || client.account(), move |r| {
|
||||
let name = match r {
|
||||
Ok((name, photo)) => {
|
||||
let mut st = c.state.borrow_mut();
|
||||
st.account.name = name.clone();
|
||||
st.account.photo = photo;
|
||||
st.account.save();
|
||||
name
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("account: {e:#}");
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
c.link_close();
|
||||
c.account_label();
|
||||
c.toast(&if name.is_empty() { "Bejelentkeztél".to_string() } else { format!("Bejelentkeztél: {name}") }, false);
|
||||
c.section_now(0);
|
||||
});
|
||||
}
|
||||
|
||||
fn link_close(&self) {
|
||||
self.state.borrow_mut().link = None;
|
||||
self.link_timer.stop();
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_link_open(false);
|
||||
}
|
||||
}
|
||||
|
||||
fn link_key(&self, a: Action) {
|
||||
let busy = self.ui().is_some_and(|ui| ui.get_link_busy());
|
||||
match a {
|
||||
Action::Back => self.link_close(),
|
||||
Action::Ok if !busy => self.sign_in(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs out (Beállítások → Fiók); `lost`: the token stopped working.
|
||||
pub fn signed_out(&self, lost: bool) {
|
||||
let (client, token) = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
let token = std::mem::take(&mut st.account.refresh_token);
|
||||
st.account = Account::default();
|
||||
st.account.save();
|
||||
st.client.set_session(None);
|
||||
(st.client.clone(), token)
|
||||
};
|
||||
if !lost && !token.is_empty() {
|
||||
task::background("revoke", move || {
|
||||
yt::auth::revoke(&client.agent, &token);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
self.account_label();
|
||||
self.toast(if lost { "A YouTube-bejelentkezés lejárt, jelentkezz be újra." } else { "Kijelentkeztél" }, lost);
|
||||
let n = self.state.borrow().stack.first().and_then(|e| e.view.frame.nav).unwrap_or(0);
|
||||
self.section_now(n);
|
||||
}
|
||||
|
||||
// ---- toast ----
|
||||
|
||||
pub fn toast(&self, text: &str, bad: bool) {
|
||||
let Some(ui) = self.ui() else { return };
|
||||
ui.set_toast_text(text.into());
|
||||
ui.set_toast_bad(bad);
|
||||
let w = self.ui.clone();
|
||||
self.toast_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(if bad { 5000 } else { 2600 }), move || {
|
||||
if let Some(ui) = w.upgrade() {
|
||||
ui.set_toast_text("".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- backdrop ----
|
||||
|
||||
/// The backdrop picture `url` (after the focus settles), or the gradient.
|
||||
pub fn backdrop(&self, url: &str, look: Look, key: &str) {
|
||||
if *self.backdrop_key.borrow() == key && !key.is_empty() {
|
||||
return;
|
||||
}
|
||||
*self.backdrop_key.borrow_mut() = key.to_string();
|
||||
if let Some(col) = self.colours.borrow().get(key).copied() {
|
||||
self.glass.set_palette(sf_ui::Palette::from_color(col));
|
||||
}
|
||||
if url.is_empty() {
|
||||
self.backdrop_timer.stop();
|
||||
self.glass.set_backdrop(None);
|
||||
return;
|
||||
}
|
||||
let (c, url, key) = (self.clone(), url.to_string(), key.to_string());
|
||||
self.backdrop_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(350), move || {
|
||||
let px = c.px();
|
||||
let size = if look == Look::Soft { ((960.0 * px) as u32, (540.0 * px) as u32) } else { ((1920.0 * px) as u32, (1080.0 * px) as u32) };
|
||||
let c2 = c.clone();
|
||||
let key2 = key.clone();
|
||||
c.images.load_pixels(&url, size, move |pixels| {
|
||||
if *c2.backdrop_key.borrow() != key2 || c2.state.borrow().screen == "player" {
|
||||
return;
|
||||
}
|
||||
c2.colours.borrow_mut().insert(key2.clone(), sf_ui::images::average_color(pixels));
|
||||
if let Some(col) = c2.colours.borrow().get(&key2).copied() {
|
||||
c2.glass.set_palette(sf_ui::Palette::from_color(col));
|
||||
}
|
||||
let b = sf_ui::Backdrop::new(pixels.clone());
|
||||
let b = match look {
|
||||
Look::Sharp => b.dim(0.3).fade_left(1.0).fade_bottom(0.9).align(0.6, 0.2),
|
||||
Look::Soft => b.dim(0.6).fade_left(0.6).fade_bottom(0.8).soft(),
|
||||
};
|
||||
c2.glass.set_backdrop(Some(b));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn clear_backdrop(&self) {
|
||||
self.backdrop_key.borrow_mut().clear();
|
||||
self.backdrop_timer.stop();
|
||||
self.glass.set_backdrop(None);
|
||||
}
|
||||
|
||||
// ---- the screen stack ----
|
||||
|
||||
/// Runs `f` on screen `id` (if it still exists), then the effects and a
|
||||
/// rebuild of the top page.
|
||||
pub fn with<T: Screen>(&self, id: u64, f: impl FnOnce(&mut T, &Cx)) {
|
||||
let taken = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.stack.iter_mut().find(|e| e.id == id).and_then(|e| e.screen.take())
|
||||
};
|
||||
let Some(mut screen) = taken else { return };
|
||||
{
|
||||
let cx = Cx { c: self, id };
|
||||
if let Some(s) = screen.as_any().downcast_mut::<T>() {
|
||||
f(s, &cx);
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
if let Some(e) = st.stack.iter_mut().find(|e| e.id == id) {
|
||||
e.screen = Some(screen);
|
||||
}
|
||||
}
|
||||
let top = self.state.borrow().stack.last().map(|e| e.id);
|
||||
if top == Some(id) {
|
||||
self.effects.borrow_mut().push(Effect::Refresh);
|
||||
}
|
||||
self.run_effects();
|
||||
}
|
||||
|
||||
/// Runs a `Screen` method on the top screen.
|
||||
fn top<R>(&self, f: impl FnOnce(&mut dyn Screen, &Cx) -> R) -> Option<R> {
|
||||
let (id, taken) = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
let e = st.stack.last_mut()?;
|
||||
(e.id, e.screen.take())
|
||||
};
|
||||
let mut screen = taken?;
|
||||
let r = {
|
||||
let cx = Cx { c: self, id };
|
||||
f(screen.as_mut(), &cx)
|
||||
};
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
if let Some(e) = st.stack.iter_mut().find(|e| e.id == id) {
|
||||
e.screen = Some(screen);
|
||||
}
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
|
||||
fn run_effects(&self) {
|
||||
loop {
|
||||
let effects: Vec<Effect> = std::mem::take(&mut *self.effects.borrow_mut());
|
||||
if effects.is_empty() {
|
||||
break;
|
||||
}
|
||||
let mut refresh = false;
|
||||
for e in effects {
|
||||
match e {
|
||||
Effect::Push(s) => self.push_now(s),
|
||||
Effect::Refresh => refresh = true,
|
||||
Effect::Play(r) => player::play(self, r),
|
||||
}
|
||||
}
|
||||
if refresh && self.state.borrow().screen == "page" {
|
||||
self.rebuild();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_now(&self, s: Box<dyn Screen>) {
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
let id = st.next_id;
|
||||
st.next_id += 1;
|
||||
st.stack.push(Entry { id, screen: Some(s), view: View::default() });
|
||||
}
|
||||
self.clear_backdrop();
|
||||
self.attach();
|
||||
self.rebuild();
|
||||
self.after_focus();
|
||||
}
|
||||
|
||||
fn pop_now(&self) {
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
if st.stack.len() > 1 {
|
||||
st.stack.pop();
|
||||
}
|
||||
}
|
||||
self.clear_backdrop();
|
||||
self.attach();
|
||||
self.top(|s, cx| s.shown(cx));
|
||||
self.rebuild();
|
||||
self.after_focus();
|
||||
}
|
||||
|
||||
/// Replaces the stack with a section's screen.
|
||||
pub fn section_now(&self, n: usize) {
|
||||
let keep_nav = self.state.borrow().stack.last().is_some_and(|e| e.view.focus == Focus::Nav);
|
||||
self.state.borrow_mut().stack.clear();
|
||||
let screen = screens::section(n);
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
let id = st.next_id;
|
||||
st.next_id += 1;
|
||||
let mut view = View::default();
|
||||
view.nav_index = n;
|
||||
if keep_nav {
|
||||
view.focus = Focus::Nav;
|
||||
}
|
||||
st.stack.push(Entry { id, screen: Some(screen), view });
|
||||
}
|
||||
self.clear_backdrop();
|
||||
self.glass.set_palette(sf_ui::Palette::from_hex(PALETTE));
|
||||
self.attach();
|
||||
self.rebuild();
|
||||
self.after_focus();
|
||||
}
|
||||
|
||||
/// Points Slint at the top view's model and shows the page.
|
||||
fn attach(&self) {
|
||||
let model = self.state.borrow().stack.last().map(|e| e.view.model());
|
||||
if let (Some(ui), Some(m)) = (self.ui(), model) {
|
||||
ui.set_page_lines(m);
|
||||
}
|
||||
if self.state.borrow().screen != "player" {
|
||||
self.show("page");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds the top page from its screen.
|
||||
pub fn rebuild(&self) {
|
||||
let spec = self.top(|s, cx| s.spec(cx));
|
||||
let Some(spec) = spec else { return };
|
||||
let px = self.px();
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
if let Some(e) = st.stack.last_mut() {
|
||||
e.view.set(spec, &self.images, px);
|
||||
}
|
||||
}
|
||||
self.sync();
|
||||
}
|
||||
|
||||
/// Focus, scroll and frame to Slint; pictures around the focus.
|
||||
fn sync(&self) {
|
||||
let Some(ui) = self.ui() else { return };
|
||||
let px = self.px();
|
||||
let mut st = self.state.borrow_mut();
|
||||
let Some(e) = st.stack.last_mut() else { return };
|
||||
let v = &mut e.view;
|
||||
v.sync_cols();
|
||||
ui.set_page_focus(if v.focus == Focus::Line { v.line as i32 } else { -1 });
|
||||
ui.set_page_scroll(v.scroll);
|
||||
ui.set_page_show_nav(v.frame.nav.is_some());
|
||||
ui.set_page_nav_index(v.frame.nav.unwrap_or(0) as i32);
|
||||
ui.set_page_nav_focused(v.focus == Focus::Nav);
|
||||
match &v.frame.side {
|
||||
Some((title, items, cur)) => {
|
||||
ui.set_page_side_title(title.clone().into());
|
||||
ui.set_page_side_items(ModelRc::new(VecModel::from(items.iter().map(|s| SharedString::from(s.as_str())).collect::<Vec<_>>())));
|
||||
ui.set_page_side_index(*cur as i32);
|
||||
ui.set_page_side_focus(if v.focus == Focus::Side { v.side_focus as i32 } else { -1 });
|
||||
}
|
||||
None => {
|
||||
ui.set_page_side_items(ModelRc::default());
|
||||
ui.set_page_side_focus(-1);
|
||||
}
|
||||
}
|
||||
let kb_line = v.lines.iter().position(|l| l.kind == Kind::Keyboard);
|
||||
match (kb_line, &v.frame.keyboard) {
|
||||
(Some(i), Some(ph)) => {
|
||||
ui.set_page_kb_y(v.line_y(i));
|
||||
ui.set_page_kb_placeholder(ph.clone().into());
|
||||
ui.set_page_kb_focused(v.focus == Focus::Line && v.line == i);
|
||||
}
|
||||
_ => {
|
||||
ui.set_page_kb_y(-1.0);
|
||||
ui.set_page_kb_focused(false);
|
||||
}
|
||||
}
|
||||
v.load_images(&self.images, px);
|
||||
}
|
||||
|
||||
fn after_focus(&self) {
|
||||
let target = {
|
||||
let st = self.state.borrow();
|
||||
st.stack.last().map(|e| (e.view.target(), e.view.near_end(), e.view.focus.clone()))
|
||||
};
|
||||
let Some(((line, item), near, focus)) = target else { return };
|
||||
if focus == Focus::Line {
|
||||
self.top(|s, cx| s.focus(cx, &line, &item));
|
||||
if let Some(list) = near {
|
||||
self.top(|s, cx| s.more(cx, &list));
|
||||
}
|
||||
}
|
||||
self.run_effects();
|
||||
}
|
||||
|
||||
// ---- keys ----
|
||||
|
||||
fn key(&self, a: Action, repeat: bool) {
|
||||
if self.state.borrow().link.is_some() {
|
||||
return self.link_key(a);
|
||||
}
|
||||
let screen = self.state.borrow().screen;
|
||||
if screen == "player" {
|
||||
return player::key(self, a, repeat);
|
||||
}
|
||||
self.page_key(a);
|
||||
}
|
||||
|
||||
fn page_key(&self, a: Action) {
|
||||
enum Then {
|
||||
Moved,
|
||||
Activate(String, String),
|
||||
Back,
|
||||
Section(usize),
|
||||
Side(usize),
|
||||
Nothing,
|
||||
Quit,
|
||||
}
|
||||
let then = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
let Some(e) = st.stack.last_mut() else { return };
|
||||
let v = &mut e.view;
|
||||
let has_side = v.frame.side.is_some();
|
||||
let has_nav = v.frame.nav.is_some();
|
||||
match v.focus {
|
||||
Focus::Nav => match a {
|
||||
Action::Left if v.frame.nav.unwrap_or(0) > 0 => Then::Section(v.frame.nav.unwrap() - 1),
|
||||
Action::Right if v.frame.nav.unwrap_or(0) + 1 < SECTIONS.len() => Then::Section(v.frame.nav.unwrap() + 1),
|
||||
Action::Down | Action::Ok => {
|
||||
if v.has_lines() && v.lines.iter().any(|l| matches!(l.kind, Kind::Chips | Kind::Cards | Kind::Item | Kind::Hero | Kind::Keyboard)) {
|
||||
v.focus = if has_side { Focus::Side } else { Focus::Line };
|
||||
v.clamp_scroll();
|
||||
Then::Moved
|
||||
} else {
|
||||
Then::Nothing
|
||||
}
|
||||
}
|
||||
Action::Back if v.frame.nav.unwrap_or(0) != 0 => Then::Section(0),
|
||||
Action::Back => Then::Quit,
|
||||
_ => Then::Nothing,
|
||||
},
|
||||
Focus::Side => {
|
||||
let n = v.frame.side.as_ref().map(|s| s.1.len()).unwrap_or(0);
|
||||
match a {
|
||||
Action::Up if v.side_focus > 0 => {
|
||||
v.side_focus -= 1;
|
||||
Then::Side(v.side_focus)
|
||||
}
|
||||
Action::Up if has_nav => {
|
||||
v.focus = Focus::Nav;
|
||||
Then::Moved
|
||||
}
|
||||
Action::Down if v.side_focus + 1 < n => {
|
||||
v.side_focus += 1;
|
||||
Then::Side(v.side_focus)
|
||||
}
|
||||
Action::Right | Action::Ok => {
|
||||
if v.lines.iter().any(|l| matches!(l.kind, Kind::Chips | Kind::Cards | Kind::Item | Kind::Hero)) {
|
||||
v.focus = Focus::Line;
|
||||
v.clamp_scroll();
|
||||
}
|
||||
Then::Moved
|
||||
}
|
||||
Action::Back => Then::Back,
|
||||
_ => Then::Nothing,
|
||||
}
|
||||
}
|
||||
Focus::Line => match a {
|
||||
Action::Up => {
|
||||
if !v.vertical(false) {
|
||||
if has_side {
|
||||
v.focus = Focus::Side;
|
||||
} else if has_nav {
|
||||
v.focus = Focus::Nav;
|
||||
v.scroll = 0.0;
|
||||
}
|
||||
}
|
||||
Then::Moved
|
||||
}
|
||||
Action::Down => {
|
||||
v.vertical(true);
|
||||
Then::Moved
|
||||
}
|
||||
Action::Left => {
|
||||
if !v.horizontal(false) && has_side {
|
||||
v.focus = Focus::Side;
|
||||
}
|
||||
Then::Moved
|
||||
}
|
||||
Action::Right => {
|
||||
v.horizontal(true);
|
||||
Then::Moved
|
||||
}
|
||||
Action::Ok | Action::PlayPause => {
|
||||
let (l, i) = v.target();
|
||||
Then::Activate(l, i)
|
||||
}
|
||||
Action::Back => Then::Back,
|
||||
},
|
||||
}
|
||||
};
|
||||
match then {
|
||||
Then::Nothing => {}
|
||||
Then::Quit => {
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
Then::Moved => {
|
||||
self.sync();
|
||||
self.after_focus();
|
||||
}
|
||||
Then::Section(n) => self.section_now(n),
|
||||
Then::Side(i) => {
|
||||
self.top(|s, cx| s.side(cx, i));
|
||||
self.rebuild();
|
||||
self.run_effects();
|
||||
}
|
||||
Then::Activate(l, i) => {
|
||||
self.top(|s, cx| s.activate(cx, &l, &i));
|
||||
self.effects.borrow_mut().push(Effect::Refresh);
|
||||
self.run_effects();
|
||||
self.after_focus();
|
||||
}
|
||||
Then::Back => {
|
||||
let handled = self.top(|s, cx| s.back(cx)).unwrap_or(false);
|
||||
if handled {
|
||||
self.effects.borrow_mut().push(Effect::Refresh);
|
||||
self.run_effects();
|
||||
return;
|
||||
}
|
||||
let depth = self.state.borrow().stack.len();
|
||||
if depth > 1 {
|
||||
self.pop_now();
|
||||
} else {
|
||||
let mut st = self.state.borrow_mut();
|
||||
if let Some(e) = st.stack.last_mut() {
|
||||
if e.view.frame.nav.is_some() {
|
||||
e.view.focus = Focus::Nav;
|
||||
e.view.scroll = 0.0;
|
||||
} else if e.view.frame.side.is_some() {
|
||||
e.view.focus = Focus::Side;
|
||||
}
|
||||
}
|
||||
drop(st);
|
||||
self.sync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- search keyboard ----
|
||||
|
||||
fn search(&self, text: String, submit: bool) {
|
||||
if submit {
|
||||
self.search_timer.stop();
|
||||
self.top(|s, cx| s.query(cx, &text, true));
|
||||
self.run_effects();
|
||||
return;
|
||||
}
|
||||
let c = self.clone();
|
||||
self.search_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(600), move || {
|
||||
c.top(|s, cx| s.query(cx, &text, false));
|
||||
c.run_effects();
|
||||
});
|
||||
}
|
||||
|
||||
fn leave_keyboard(&self, down: bool) {
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
let Some(e) = st.stack.last_mut() else { return };
|
||||
let v = &mut e.view;
|
||||
if !v.vertical(down) && !down && v.frame.nav.is_some() {
|
||||
v.focus = Focus::Nav;
|
||||
}
|
||||
}
|
||||
self.sync();
|
||||
self.after_focus();
|
||||
}
|
||||
|
||||
/// Opens a screen from outside the screens (the player's channel button).
|
||||
pub fn push_screen(&self, s: Box<dyn Screen>) {
|
||||
self.effects.borrow_mut().push(Effect::Push(s));
|
||||
self.run_effects();
|
||||
}
|
||||
|
||||
/// Back from the player.
|
||||
pub fn player_closed(&self) {
|
||||
self.clear_backdrop();
|
||||
self.attach();
|
||||
self.top(|s, cx| s.shown(cx));
|
||||
self.rebuild();
|
||||
self.after_focus();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user