//! The controller: the screen stack, keys, overlays (text input, picker, //! toast), the backdrop, start-up and sign-in. //! //! 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, pop, play, input...), which run when the method returns. use std::any::Any; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::time::Duration; use slint::platform::Key; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; use crate::api::{self, Api, User, UserSettings}; use crate::config::{self, Config}; use crate::page::{Focus, Kind, Spec, View}; use crate::{App, MenuItem, 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 { 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; 7] = ["Kezdőlap", "Filmek", "Sorozatok", "Anime", "Listám", "Keresés", "Beállítások"]; /// 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 (hero texts, 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 chip). fn query(&mut self, _cx: &Cx, _text: &str, _submit: bool) {} /// Every second while on top. fn tick(&mut self, _cx: &Cx) {} fn as_any(&mut self) -> &mut dyn Any; } /// A text field request (the input overlay). pub struct Input { pub title: String, pub subtitle: String, pub placeholder: String, pub value: String, pub secret: bool, pub submit: String, pub min: i32, /// Stays open (busy) until the callback calls `input_done`/`input_failed`. pub keep_open: bool, } impl Input { pub fn new(title: &str, placeholder: &str, value: &str) -> Input { Input { title: title.into(), subtitle: String::new(), placeholder: placeholder.into(), value: value.into(), secret: false, submit: "Kész".into(), min: 0, keep_open: false, } } } /// Called with the submitted text; `keep_open` inputs may be submitted again after a failure. type InputDone = Rc; type SelectDone = Box; enum Effect { Push(Box), Refresh, Play(player::Request), } struct Entry { id: u64, screen: Option>, view: View, } pub struct State { pub cfg: Config, pub api: Api, pub user: User, pub settings: UserSettings, stack: Vec, next_id: u64, /// "message", "page", "player" pub screen: &'static str, message_retry: bool, message_action: i32, input_done: Option, input_cancel: Option>, select: Option<(usize, usize, SelectDone)>, pub player: Option, pub vpn_ok: Option, } pub struct Inner { pub ui: slint::Weak, pub glass: sf_ui::Glass, pub images: sf_ui::images::Images, pub state: RefCell, effects: RefCell>, toast_timer: slint::Timer, backdrop_timer: slint::Timer, backdrop_key: RefCell, pub colours: Rc>>, tick: slint::Timer, health: slint::Timer, search_timer: slint::Timer, } /// Cheap to clone; every callback holds one. #[derive(Clone)] pub struct Controller(pub Rc); 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 { /// Details pages: sharp, dark towards the left and bottom. Sharp, /// Browsing: blurred and dim behind the rows. Soft, } impl<'a> Cx<'a> { pub fn api(&self) -> Api { self.c.api() } pub fn user(&self) -> User { self.c.state.borrow().user.clone() } pub fn settings(&self) -> UserSettings { self.c.state.borrow().settings.clone() } pub fn set_settings(&self, s: UserSettings) { self.c.state.borrow_mut().settings = s; } /// 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(&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::(id, move |s, cx| done(s, cx, r))); } /// Fire and forget, then rebuild this screen's page (and run `then`). pub fn call(&self, what: &'static str, work: impl FnOnce() -> anyhow::Result<()> + Send + 'static, then: impl FnOnce(&mut T, &Cx) + 'static) { self.spawn::(work, move |s, cx, r| { if let Err(e) = r { cx.error(what, &e); } then(s, cx); }); } /// Shows an API error (or signs out). pub fn error(&self, what: &str, e: &anyhow::Error) { if api::is_unauthenticated(e) { let c = self.c.clone(); slint::Timer::single_shot(Duration::from_millis(1), move || c.signed_out()); return; } log::warn!("{what}: {e:#}"); self.c.toast(&api::describe(e), true); } pub fn push(&self, s: Box) { 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 toast_bad(&self, text: &str) { self.c.toast(text, true); } pub fn backdrop(&self, url: &str, look: Look, key: &str) { self.c.backdrop(url, look, key); } /// A text field; `done` gets the text (this screen back first). pub fn input(&self, req: Input, done: impl FnOnce(&mut T, &Cx, String) + 'static) { let id = self.id; let once = RefCell::new(Some(done)); self.c.open_input( req, Rc::new(move |c: &Controller, text: String| { if let Some(done) = once.borrow_mut().take() { c.with::(id, move |s, cx| done(s, cx, text)); } }), None, ); } /// A picker over `items` (label, detail, checked). pub fn select(&self, title: &str, items: Vec<(String, String, bool)>, done: impl FnOnce(&mut T, &Cx, usize) + 'static) { let id = self.id; self.c.open_select(title, items, Box::new(move |c: &Controller, i: usize| c.with::(id, move |s, cx| done(s, cx, i)))); } /// The focus target (line id, item id) of this screen's page. pub fn focus_on(&self, line: &str, col: usize) { let mut st = self.c.state.borrow_mut(); if let Some(e) = st.stack.iter_mut().find(|e| e.id == self.id) { e.view.focus_on(line, col); } } } impl Controller { pub fn new(ui: &App, glass: sf_ui::Glass, images: sf_ui::images::Images) -> Controller { let cfg = Config::load(); let api = Api::new(&cfg.server, &cfg.token); let state = State { api, user: User::default(), settings: UserSettings::default(), stack: Vec::new(), next_id: 1, screen: "message", message_retry: false, message_action: 0, input_done: None, input_cancel: None, select: None, player: None, vpn_ok: None, cfg, }; 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(), tick: slint::Timer::default(), health: slint::Timer::default(), search_timer: slint::Timer::default(), })); crate::config::apply_look(&c.glass, &crate::config::Local::load().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_input_submitted(move |t| k.input_submitted(t.to_string())); let k = c.clone(); ui.on_input_cancelled(move || k.input_cancelled()); 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::>()))); let k = c.clone(); c.tick.start(slint::TimerMode::Repeated, Duration::from_secs(1), move || k.tick()); c } pub fn ui(&self) -> Option { 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 api(&self) -> Api { self.state.borrow().api.clone() } pub fn show(&self, screen: &'static str) { self.state.borrow_mut().screen = screen; if let Some(ui) = self.ui() { ui.set_screen(screen.into()); } } // ---- start-up and sign-in ---- pub fn start(&self) { if self.state.borrow().cfg.server.is_empty() { return self.sign_in_server(""); } self.message(false, "Kapcsolódás…", ""); let api = self.api(); let c = self.clone(); task::spawn( move || api.auth_status().map(|s| (s.user, api.settings().unwrap_or_default())), move |r| match r { Ok((Some(user), settings)) => { { let mut st = c.state.borrow_mut(); st.user = user; st.settings = settings; } c.watch_health(); c.section_now(0); } Ok((None, _)) => c.sign_in_user(""), Err(e) => { log::warn!("start: {e:#}"); c.message(true, "A szerver nem érhető el", &api::describe(&e)); } }, ); } pub fn shutdown(&self) { player::stop(self, false); } fn message(&self, retry: bool, title: &str, text: &str) { { let mut st = self.state.borrow_mut(); st.message_retry = retry; st.message_action = 0; } if let Some(ui) = self.ui() { ui.set_message_busy(!retry); ui.set_message_title(title.into()); ui.set_message_text(text.into()); ui.set_message_action_a(if retry { "Újra".into() } else { "".into() }); ui.set_message_action_b(if retry { "Szerver módosítása".into() } else { "".into() }); ui.set_message_action(0); } self.glass.set_backdrop(None); self.show("message"); } fn message_key(&self, a: Action) { let (retry, mut sel) = { let st = self.state.borrow(); (st.message_retry, st.message_action) }; match a { Action::Back => { let _ = slint::quit_event_loop(); } _ if !retry => {} Action::Left => sel = 0, Action::Right => sel = 1, Action::Ok if sel == 0 => return self.start(), Action::Ok => { let server = self.state.borrow().cfg.server.clone(); return self.sign_in_server(&server); } _ => {} } self.state.borrow_mut().message_action = sel; if let Some(ui) = self.ui() { ui.set_message_action(sel); } } /// Asks for the server's address (prefilled). pub fn sign_in_server(&self, current: &str) { self.message(false, "", ""); if let Some(ui) = self.ui() { ui.set_message_busy(false); } let host = if current.is_empty() { config::DEFAULT_SERVER.to_string() } else { current.to_string() }; let req = Input { title: "Netflex szerver".into(), subtitle: "A szerver címe, ahová a Netflex telepítve van".into(), placeholder: "netflex.pelda.hu".into(), value: host.trim_start_matches("https://").into(), secret: false, submit: "Tovább".into(), min: 3, keep_open: true, }; let had = !self.state.borrow().cfg.token.is_empty(); self.open_input( req, Rc::new(|c: &Controller, text: String| { let base = api::normalize_base(&text); let probe = Api::new(&base, ""); let c2 = c.clone(); task::spawn( move || probe.auth_status().map(|_| ()), move |r| match r { Ok(()) => { { let mut st = c2.state.borrow_mut(); st.cfg.server = base.clone(); st.cfg.token.clear(); st.cfg.save(); st.api = Api::new(&base, ""); } c2.input_done(); c2.sign_in_user(""); } Err(e) => c2.input_failed(&format!("Nem érhető el: {}", api::describe(&e))), }, ); }), Some(Box::new(move |c: &Controller| { if had { c.start() } else { let _ = slint::quit_event_loop(); } })), ); self.set_input_footer(""); } pub fn sign_in_user(&self, note: &str) { self.message(false, "", ""); if let Some(ui) = self.ui() { ui.set_message_busy(false); } let (server, username) = { let st = self.state.borrow(); (st.cfg.server.clone(), st.cfg.username.clone()) }; let req = Input { title: "Bejelentkezés".into(), subtitle: if note.is_empty() { "A Netflex felhasználóneved".into() } else { note.into() }, placeholder: "Felhasználónév".into(), value: username, secret: false, submit: "Tovább".into(), min: 2, keep_open: false, }; self.open_input( req, Rc::new(|c: &Controller, user: String| c.sign_in_password(user.trim().to_lowercase())), Some(Box::new(move |c: &Controller| { let server = c.state.borrow().cfg.server.clone(); c.sign_in_server(&server) })), ); self.set_input_footer(&format!("Szerver: {server} · Vissza: másik szerver")); } fn sign_in_password(&self, username: String) { let server = self.state.borrow().cfg.server.clone(); let req = Input { title: "Jelszó".into(), subtitle: format!("{username} jelszava"), placeholder: "Jelszó".into(), value: String::new(), secret: true, submit: "Belépés".into(), min: 1, keep_open: true, }; let user2 = username.clone(); self.open_input( req, Rc::new(move |c: &Controller, password: String| { let username = username.clone(); let api = c.api(); let c2 = c.clone(); task::spawn( move || { let signed = api.login(&username, &password)?; let settings = api.with_token(&signed.token).settings().unwrap_or_default(); Ok::<_, anyhow::Error>((signed, settings)) }, move |r| match r { Ok((signed, settings)) => { { let mut st = c2.state.borrow_mut(); st.cfg.token = signed.token.clone(); st.cfg.username = signed.user.username.clone(); st.cfg.save(); st.api = st.api.with_token(&signed.token); st.user = signed.user; st.settings = settings; } c2.input_done(); c2.watch_health(); c2.section_now(0); } Err(e) => c2.input_failed(&api::describe(&e)), }, ); }), Some(Box::new(move |c: &Controller| { c.state.borrow_mut().cfg.username = user2.clone(); c.sign_in_user("") })), ); self.set_input_footer(&format!("Szerver: {server}")); } /// The session ended on the server: sign in again. pub fn signed_out(&self) { { let mut st = self.state.borrow_mut(); st.cfg.token.clear(); st.cfg.save(); st.api = st.api.with_token(""); st.stack.clear(); } player::stop(self, false); self.sign_in_user("A munkamenet lejárt, jelentkezz be újra."); } /// Signs out of this device (Settings → Fiók). pub fn sign_out(&self) { let api = self.api(); let c = self.clone(); task::spawn(move || api.logout(), move |_| c.signed_out()); } // ---- input overlay ---- pub fn open_input(&self, req: Input, done: InputDone, cancel: Option>) { { let mut st = self.state.borrow_mut(); st.input_done = Some(done); st.input_cancel = cancel; } let Some(ui) = self.ui() else { return }; ui.invoke_input_reset(); ui.set_input_title(req.title.into()); ui.set_input_subtitle(req.subtitle.into()); ui.set_input_placeholder(req.placeholder.into()); ui.set_input_secret(req.secret); ui.set_input_submit_label(req.submit.into()); ui.set_input_min_length(req.min); ui.set_input_text(req.value.into()); ui.set_input_error("".into()); ui.set_input_busy(false); ui.set_input_footer("".into()); ui.set_input_open(true); INPUT_KEEP.with(|k| k.set(req.keep_open)); } fn set_input_footer(&self, text: &str) { if let Some(ui) = self.ui() { ui.set_input_footer(text.into()); } } fn input_submitted(&self, text: String) { let keep = INPUT_KEEP.with(|k| k.get()); let done = if keep { self.state.borrow().input_done.clone() } else { self.state.borrow_mut().input_done.take() }; let Some(done) = done else { return }; if keep { if let Some(ui) = self.ui() { ui.set_input_busy(true); } } else { self.close_input(); } done(self, text); } fn input_cancelled(&self) { let cancel = { let mut st = self.state.borrow_mut(); st.input_done = None; st.input_cancel.take() }; self.close_input(); if let Some(cb) = cancel { cb(self); } } fn close_input(&self) { if let Some(ui) = self.ui() { ui.set_input_open(false); ui.set_input_busy(false); } } /// A `keep_open` input succeeded. pub fn input_done(&self) { { let mut st = self.state.borrow_mut(); st.input_cancel = None; st.input_done = None; } self.close_input(); } /// A `keep_open` input failed: stays open with the error. pub fn input_failed(&self, msg: &str) { let Some(ui) = self.ui() else { return }; ui.set_input_busy(false); ui.set_input_error(msg.into()); } // ---- picker ---- pub fn open_select(&self, title: &str, items: Vec<(String, String, bool)>, done: SelectDone) { let focus = items.iter().position(|i| i.2).unwrap_or(0); let n = items.len(); self.state.borrow_mut().select = Some((focus, n, done)); let Some(ui) = self.ui() else { return }; let model: Vec = items .into_iter() .map(|(l, d, c)| MenuItem { text: l.into(), detail: d.into(), checked: c }) .collect(); ui.set_select_title(title.into()); ui.set_select_items(ModelRc::new(VecModel::from(model))); ui.set_select_focus(focus as i32); ui.set_select_open(true); } fn select_key(&self, a: Action) { let mut st = self.state.borrow_mut(); let Some((focus, n, _)) = st.select.as_mut() else { return }; match a { Action::Up => *focus = focus.saturating_sub(1), Action::Down => *focus = (*focus + 1).min(n.saturating_sub(1)), Action::Ok => { let (i, _, done) = st.select.take().unwrap(); drop(st); if let Some(ui) = self.ui() { ui.set_select_open(false); } done(self, i); self.run_effects(); return; } Action::Back | Action::Left | Action::Right => { st.select = None; drop(st); if let Some(ui) = self.ui() { ui.set_select_open(false); } return; } _ => {} } let f = *focus as i32; drop(st); if let Some(ui) = self.ui() { ui.set_select_focus(f); } } // ---- 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(300), 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; } let b = sf_ui::Backdrop::new(pixels.clone()); let b = match look { Look::Sharp => b.dim(0.25).fade_left(1.0).fade_bottom(0.9).align(0.6, 0.2), Look::Soft => b.dim(0.55).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); } // ---- health (VPN state in the nav) ---- fn watch_health(&self) { let c = self.clone(); let check = move || { let api = c.api(); let c2 = c.clone(); task::spawn( move || api.health(), move |r| { let ok = r.ok().map(|h| h.vpn == "vpn"); c2.state.borrow_mut().vpn_ok = ok; if let Some(ui) = c2.ui() { ui.set_page_vpn_label(match ok { Some(true) => "VPN aktív".into(), Some(false) => "VPN leállt".into(), None => "Szerver nem érhető el".into(), }); ui.set_page_vpn_ok(ok == Some(true)); } }, ); }; check(); self.health.start(slint::TimerMode::Repeated, Duration::from_secs(15), check); } // ---- 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(&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::() { 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(&self, f: impl FnOnce(&mut dyn Screen, &Cx) -> R) -> Option { 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 = 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.rebuild(); } } } fn push_now(&self, s: Box) { { 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 left = { let mut st = self.state.borrow_mut(); if st.stack.len() > 1 { st.stack.pop(); } st.stack.len() }; let _ = left; 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(["#ff4a3d", "#8c0b14", "#120305"])); self.attach(); self.rebuild(); self.after_focus(); } /// Settings on tab `tab` ("vpn", "ncore"...). pub fn open_settings(&self, tab: &str) { let tab = tab.to_string(); let c = self.clone(); slint::Timer::single_shot(Duration::from_millis(1), move || { c.section_now(6); let id = c.state.borrow().stack.last().map(|e| e.id).unwrap_or(0); c.with::(id, |s, cx| s.open_tab(cx, &tab)); }); } /// 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::>()))); 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)) => { let y = v_line_y(v, i); ui.set_page_kb_y(y); 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().select.is_some() { return self.select_key(a); } let screen = self.state.borrow().screen; match screen { "message" => return self.message_key(a), "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(450), 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(); } fn tick(&self) { if self.state.borrow().screen != "page" { return; } self.top(|s, cx| s.tick(cx)); 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(); } } fn v_line_y(v: &View, i: usize) -> f32 { v.line_y(i) } /// Cx helper for screens that need a keep-open input (async validation). impl Cx<'_> { /// A text field that stays open while `check` runs; `check` returns an /// error message to show, or None to close. pub fn input_checked( &self, req: Input, work: impl Fn(String) -> R + Send + Sync + 'static, done: impl Fn(&mut T, &Cx, R) -> Option + 'static, ) { let id = self.id; let work = std::sync::Arc::new(work); let done = Rc::new(done); let mut req = req; req.keep_open = true; self.c.open_input( req, Rc::new(move |c: &Controller, text: String| { let work = work.clone(); let done = done.clone(); let c2 = c.clone(); task::spawn( move || work(text), move |r| { let mut err: Option = None; c2.with::(id, |s, cx| err = done(s, cx, r)); match err { Some(e) => c2.input_failed(&e), None => c2.input_done(), } }, ); }), None, ); } } thread_local! { static INPUT_KEEP: std::cell::Cell = const { std::cell::Cell::new(false) }; }