Files
spotify/src/app.rs
Tamas Csikel 7fd7e242a7
All checks were successful
release / release (push) Successful in 10m37s
0.2.0: play through Spotify Soloist
Spotify refuses librespot the audio keys ("error audio key 0 1",
librespot #1649), so nothing played. Playback now goes through Spotify
Soloist, Spotify's own headless Linux player:

- The TV downloads it from Spotify (redistribution is not allowed), keeps
  it fresh (builds expire after 90 days), runs and restarts it, and drives
  it over its local WebSocket API; its events feed Most szól.
- It needs the user's own Soloist API key: the key screen shows a QR code
  to a small page on the TV where the phone pastes it (or type it on the
  TV); asked once after sign-in, also in Settings. Then the TV is picked
  once in the phone's Spotify app (pairing); home shows that step.
- Soloist is the Connect device; librespot only signs in (pairing code)
  and browses. Its player, Connect and zeroconf are gone, and with them
  GStreamer.
- A track from a list plays and the next ones are queued (Soloist's play
  takes one URI). The queue panel is back (Soloist reports the queue).
- Settings: the player's state and key instead of quality/normalisation/
  autoplay (Soloist decides those).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:50:44 +01:00

1165 lines
39 KiB
Rust

//! The controller: the screen stack, keys, overlays (text input, picker,
//! toast), the backdrop, sign-in and the Spotify engine's events.
//!
//! 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::RefCell;
use std::rc::Rc;
use std::time::Duration;
use slint::platform::Key;
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use crate::api::{self, Api, User};
use crate::config::Config;
use crate::nowplaying::NowPlaying;
use crate::page::{Focus, Kind, Spec, View};
use crate::spotify::{Cmd, Engine, Event, Status};
use crate::{App, MenuItem, nowplaying, 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;
})
}
/// `text` as a QR code: black modules on white, with the quiet zone.
pub fn qr_image(text: &str) -> Option<slint::Image> {
let code = qrcode::QrCode::new(text.as_bytes()).ok()?;
let n = code.width();
let colors = code.to_colors();
let (quiet, scale) = (2usize, 12usize);
let size = (n + 2 * quiet) * scale;
let mut buf = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::new(size as u32, size as u32);
let px = buf.make_mut_slice();
for y in 0..size {
for x in 0..size {
let (mx, my) = ((x / scale) as isize - quiet as isize, (y / scale) as isize - quiet as isize);
let dark = mx >= 0 && my >= 0 && (mx as usize) < n && (my as usize) < n && colors[my as usize * n + mx as usize] == qrcode::Color::Dark;
let v = if dark { 0x12 } else { 0xff };
px[y * size + x] = slint::Rgba8Pixel { r: v, g: v, b: v, a: 0xff };
}
}
Some(slint::Image::from_rgba8(buf))
}
/// Top navigation sections. Right of the last one: the "now playing" capsule.
pub const SECTIONS: [&str; 4] = ["Kezdőlap", "Keresés", "Könyvtár", "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 (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) {}
/// The search keyboard's text changed (`submit`: the search chip).
fn query(&mut self, _cx: &Cx, _text: &str, _submit: bool) {}
/// The playing track changed (rows mark it).
fn track_changed(&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 submit: String,
pub min: i32,
}
type InputDone = Rc<dyn Fn(&Controller, String)>;
type SelectDone = Box<dyn FnOnce(&Controller, usize)>;
enum Effect {
Push(Box<dyn Screen>),
Refresh,
Play(Cmd),
}
struct Entry {
id: u64,
screen: Option<Box<dyn Screen>>,
view: View,
}
pub struct State {
pub cfg: Config,
pub api: Api,
pub user: User,
pub status: Status,
stack: Vec<Entry>,
next_id: u64,
/// "message", "signin", "page", "nowplaying"
pub screen: &'static str,
input_done: Option<InputDone>,
select: Option<(usize, usize, SelectDone)>,
pub np: NowPlaying,
/// The nav focus sits on the "now playing" capsule.
np_capsule: bool,
/// The player (Soloist).
pub solo: crate::soloist::Status,
/// The key page while the key screen is open.
keyserver: Option<crate::keyserver::KeyServer>,
}
pub struct Inner {
pub ui: slint::Weak<App>,
pub glass: sf_ui::Glass,
pub images: sf_ui::images::Images,
pub engine: Engine,
pub state: RefCell<State>,
effects: RefCell<Vec<Effect>>,
toast_timer: slint::Timer,
backdrop_timer: slint::Timer,
backdrop_key: RefCell<String>,
pub np_timer: slint::Timer,
search_timer: slint::Timer,
}
/// 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
}
}
thread_local! {
static CONTROLLER: RefCell<Option<Controller>> = const { RefCell::new(None) };
}
/// 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 and now playing: blurred and dim.
Soft,
}
/// The app's colours: Spotify green on near black.
pub const PALETTE: [&str; 3] = ["#1ed760", "#0d5c2b", "#060a07"];
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 solo(&self) -> crate::soloist::Status {
self.c.state.borrow().solo.clone()
}
pub fn cfg(&self) -> Config {
self.c.state.borrow().cfg.clone()
}
/// The uri of the track that plays ("" if none).
pub fn playing_uri(&self) -> String {
self.c.state.borrow().np.track.as_ref().map(|t| t.uri.clone()).unwrap_or_default()
}
/// 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);
});
}
pub fn error(&self, what: &str, e: &anyhow::Error) {
log::warn!("{what}: {e:#}");
self.c.toast(&api::describe(e), true);
}
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);
}
/// Starts playback and shows the now playing screen.
pub fn play(&self, cmd: Cmd) {
self.c.effects.borrow_mut().push(Effect::Play(cmd));
}
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);
}
/// A text field; `done` gets the text (this screen back first).
pub fn input<T: Screen>(&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::<T>(id, move |s, cx| done(s, cx, text));
}
}),
);
}
/// A picker over `items` (label, detail, checked).
pub fn select<T: Screen>(&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::<T>(id, move |s, cx| done(s, cx, i))));
}
pub fn set_cfg(&self, f: impl FnOnce(&mut Config)) {
let mut st = self.c.state.borrow_mut();
f(&mut st.cfg);
st.cfg.save();
}
}
impl Controller {
pub fn new(ui: &App, glass: sf_ui::Glass, images: sf_ui::images::Images) -> Controller {
let cfg = Config::load();
crate::config::apply_look(&glass, &cfg.glass);
// Engine events arrive on a runtime thread: hop to the UI thread.
let engine = Engine::start(&cfg, |ev| {
let _ = slint::invoke_from_event_loop(move || {
if let Some(c) = CONTROLLER.with(|c| c.borrow().clone()) {
c.on_event(ev);
}
});
});
let api = Api::new(engine.clone());
let state = State {
cfg,
api,
user: User::default(),
status: Status::Connecting,
stack: Vec::new(),
next_id: 1,
screen: "message",
input_done: None,
select: None,
np: NowPlaying::default(),
np_capsule: false,
solo: crate::soloist::Status::Starting,
keyserver: None,
};
let c = Controller(Rc::new(Inner {
ui: ui.as_weak(),
glass,
images,
engine,
state: RefCell::new(state),
effects: RefCell::default(),
toast_timer: slint::Timer::default(),
backdrop_timer: slint::Timer::default(),
backdrop_key: RefCell::default(),
np_timer: slint::Timer::default(),
search_timer: slint::Timer::default(),
}));
CONTROLLER.with(|k| *k.borrow_mut() = Some(c.clone()));
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.close_input());
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.message(true, "Kapcsolódás a Spotifyhoz…", "");
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 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());
}
}
pub fn shutdown(&self) {
CONTROLLER.with(|k| *k.borrow_mut() = None);
self.engine.shutdown(Duration::from_secs(2));
}
fn message(&self, busy: bool, title: &str, text: &str) {
if let Some(ui) = self.ui() {
ui.set_message_busy(busy);
ui.set_message_title(title.into());
ui.set_message_text(text.into());
}
self.clear_backdrop();
self.show("message");
}
// ---- the engine ----
fn on_event(&self, ev: Event) {
match ev {
Event::Status(s) => self.on_status(s),
Event::Pair(p) => self.on_pair(p),
Event::Solo(s) => self.on_solo(s),
other => nowplaying::on_event(self, other),
}
}
/// A pairing code: the code and its QR code on the sign-in screen.
fn on_pair(&self, p: Option<crate::spotify::Pair>) {
let Some(ui) = self.ui() else { return };
match p {
Some(p) => {
ui.set_signin_code(p.code.clone().into());
ui.set_signin_qr(qr_image(&p.url).unwrap_or_default());
}
None => {
ui.set_signin_code("".into());
ui.set_signin_qr(Default::default());
}
}
}
fn on_status(&self, s: Status) {
let in_app = !self.state.borrow().stack.is_empty();
self.state.borrow_mut().status = s.clone();
match s {
Status::SignIn(name) => {
self.state.borrow_mut().stack.clear();
if let Some(ui) = self.ui() {
ui.set_signin_device(name.into());
}
self.clear_backdrop();
self.glass.set_palette(sf_ui::Palette::from_hex(PALETTE));
self.show("signin");
}
Status::Connecting if !in_app => {
let screen = self.state.borrow().screen;
if screen == "signin" {
if let Some(ui) = self.ui() {
ui.set_signin_busy(true);
}
} else {
self.message(true, "Kapcsolódás a Spotifyhoz…", "");
}
}
Status::Connecting => {}
Status::Ready(_) if in_app => {}
Status::Ready(_) => {
if let Some(ui) = self.ui() {
ui.set_signin_busy(false);
}
self.message(true, "Kapcsolódás a Spotifyhoz…", "");
let api = self.api();
let c = self.clone();
task::spawn(
move || api.me(),
move |r| match r {
Ok(user) => {
if user.product != "premium" && !user.product.is_empty() {
c.toast("A lejátszáshoz Spotify Premium kell.", true);
}
c.show_user(&user);
c.state.borrow_mut().user = user;
c.after_sign_in();
}
Err(e) => {
// Browsing may still fail, but playback works: go on.
log::warn!("me: {e:#}");
c.after_sign_in();
}
},
);
}
Status::Failed(msg) if in_app => self.toast(&msg, true),
Status::Failed(msg) => {
if let Some(ui) = self.ui() {
ui.set_signin_busy(false);
}
if self.state.borrow().screen == "signin" {
if let Some(ui) = self.ui() {
ui.set_signin_error(msg.into());
}
} else {
self.message(false, "Nem sikerült csatlakozni", &msg);
}
}
}
}
/// Signed in: the home page, or first the Soloist key if there is none.
fn after_sign_in(&self) {
if self.state.borrow().cfg.soloist_key.trim().is_empty() {
self.open_key_screen();
} else {
self.section_now(0);
}
}
/// The player's state changed.
fn on_solo(&self, s: crate::soloist::Status) {
let changed = self.state.borrow().solo != s;
self.state.borrow_mut().solo = s.clone();
if !changed {
return;
}
if let crate::soloist::Status::Failed(msg) = &s {
self.toast(msg, true);
}
// Home and settings show it.
if self.state.borrow().screen == "page" {
self.rebuild();
}
crate::nowplaying::sync(self);
}
/// The Soloist key screen: a QR code to a page where the phone pastes
/// the key; OK types it on the TV instead; Back: later.
pub fn open_key_screen(&self) {
let server = crate::keyserver::start(move |key| {
let _ = slint::invoke_from_event_loop(move || {
if let Some(c) = CONTROLLER.with(|k| k.borrow().clone()) {
c.set_solo_key(&key);
}
});
});
let url = match server {
Ok(s) => {
let url = s.url.clone();
self.state.borrow_mut().keyserver = Some(s);
url
}
Err(e) => {
log::warn!("key page: {e:#}");
String::new()
}
};
if let Some(ui) = self.ui() {
ui.set_solokey_url(url.trim_start_matches("http://").trim_end_matches('/').into());
ui.set_solokey_qr(if url.is_empty() { Default::default() } else { qr_image(&url).unwrap_or_default() });
}
self.clear_backdrop();
self.show("solokey");
}
/// A new Soloist key (from the phone or the TV keyboard).
pub fn set_solo_key(&self, key: &str) {
let key = key.trim().to_string();
if key.len() < 16 {
self.toast("Ez nem tűnik kulcsnak.", true);
return;
}
{
let mut st = self.state.borrow_mut();
st.cfg.soloist_key = key.clone();
st.cfg.save();
}
self.engine.set_key(&key);
self.toast("Kulcs elmentve, indul a lejátszó", false);
if self.state.borrow().screen == "solokey" {
self.close_key_screen();
}
}
fn close_key_screen(&self) {
self.state.borrow_mut().keyserver = None;
if self.state.borrow().stack.is_empty() {
self.section_now(0);
} else {
self.back_to_pages();
}
}
fn key_screen_key(&self, a: Action) {
match a {
Action::Back => self.close_key_screen(),
Action::Ok => {
let req = Input {
title: "Spotify Soloist kulcs".into(),
subtitle: "developer.spotify.com/dashboard/soloist".into(),
placeholder: "API-kulcs".into(),
value: String::new(),
submit: "Mentés".into(),
min: 16,
};
self.open_input(req, Rc::new(|c: &Controller, text: String| c.set_solo_key(&text)));
}
_ => {}
}
}
/// The user's picture (or initial) in the top right corner.
fn show_user(&self, user: &User) {
let Some(ui) = self.ui() else { return };
ui.set_page_user_initial(user.name().chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default().into());
ui.set_page_user_image(Default::default());
let url = api::pick(&user.images, 160);
if !url.is_empty() {
let px = self.px();
let w = self.ui.clone();
self.images.load(&url, ((72.0 * px) as u32, (72.0 * px) as u32), move |img| {
if let Some(ui) = w.upgrade() {
ui.set_page_user_image(img);
}
});
}
}
/// Settings → Kijelentkezés.
pub fn sign_out(&self) {
self.engine.send(Cmd::SignOut);
}
// ---- input overlay ----
pub fn open_input(&self, req: Input, done: InputDone) {
self.state.borrow_mut().input_done = Some(done);
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_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_open(true);
}
fn input_submitted(&self, text: String) {
let done = self.state.borrow_mut().input_done.take();
self.close_input();
if let Some(done) = done {
done(self, text);
}
}
fn close_input(&self) {
self.state.borrow_mut().input_done = None;
if let Some(ui) = self.ui() {
ui.set_input_open(false);
}
}
// ---- 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<MenuItem> = 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.
/// Its average colour tints 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 url.is_empty() {
self.backdrop_timer.stop();
self.glass.set_backdrop(None);
self.glass.set_palette(sf_ui::Palette::from_hex(PALETTE));
return;
}
let (c, url, key) = (self.clone(), url.to_string(), key.to_string());
self.backdrop_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(250), 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 {
return;
}
let colour = sf_ui::images::average_color(pixels);
c2.glass.set_palette(sf_ui::Palette::from_color(colour));
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.5, 0.3),
Look::Soft => b.dim(0.55).fade_left(0.5).fade_bottom(0.7).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);
self.glass.set_palette(sf_ui::Palette::from_hex(PALETTE));
}
// ---- 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(cmd) => {
self.engine.send(cmd);
nowplaying::open(self);
}
}
}
if refresh && self.state.borrow().screen == "page" {
self.rebuild();
}
}
}
/// Opens a page from outside a screen (menus, the player).
pub fn push_screen(&self, s: Box<dyn Screen>) {
if self.state.borrow().stack.is_empty() {
return;
}
self.effects.borrow_mut().push(Effect::Push(s));
self.run_effects();
}
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();
self.state.borrow_mut().np_capsule = false;
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.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);
}
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();
}
/// The playing track changed: pages that mark it rebuild.
pub fn track_changed(&self) {
if self.state.borrow().stack.is_empty() {
return;
}
self.top(|s, cx| s.track_changed(cx));
if self.state.borrow().screen == "page" {
self.rebuild();
} else {
self.sync_nav();
}
}
/// Focus, scroll and frame to Slint; pictures around the focus.
fn sync(&self) {
let Some(ui) = self.ui() else { return };
let px = self.px();
self.sync_nav();
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);
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);
}
/// The nav focus and the "now playing" capsule.
pub fn sync_nav(&self) {
let Some(ui) = self.ui() else { return };
let st = self.state.borrow();
let nav_focus = st.stack.last().is_some_and(|e| e.view.focus == Focus::Nav);
ui.set_page_nav_focused(nav_focus && !st.np_capsule);
ui.set_page_np_focused(nav_focus && st.np_capsule);
match &st.np.track {
Some(t) => {
ui.set_page_np_title(t.name.clone().into());
ui.set_page_np_artist(t.artist_names().into());
ui.set_page_np_playing(st.np.playing);
}
None => {
ui.set_page_np_title("".into());
ui.set_page_np_artist("".into());
}
}
}
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();
}
/// Back from the now playing screen.
pub fn back_to_pages(&self) {
if self.state.borrow().stack.is_empty() {
return;
}
self.clear_backdrop();
self.attach();
self.top(|s, cx| s.shown(cx));
self.rebuild();
self.after_focus();
}
// ---- 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 {
"solokey" => self.key_screen_key(a),
"message" | "signin" => {
if a == Action::Back {
let _ = slint::quit_event_loop();
}
}
"nowplaying" => nowplaying::key(self, a, repeat),
_ => self.page_key(a),
}
}
fn page_key(&self, a: Action) {
enum Then {
Moved,
Activate(String, String),
Back,
Section(usize),
NowPlaying,
Nothing,
Quit,
}
if a == Action::PlayPause {
if self.state.borrow().np.track.is_some() {
self.engine.send(Cmd::PlayPause);
}
return;
}
let has_track = self.state.borrow().np.track.is_some();
let then = {
let mut st = self.state.borrow_mut();
let capsule = st.np_capsule;
let Some(e) = st.stack.last_mut() else { return };
let v = &mut e.view;
let has_nav = v.frame.nav.is_some();
let nav = v.frame.nav.unwrap_or(0);
let mut capsule_to: Option<bool> = None;
let then = match v.focus {
Focus::Nav if capsule => match a {
Action::Left => {
capsule_to = Some(false);
Then::Moved
}
Action::Ok | Action::Down => Then::NowPlaying,
Action::Back => {
capsule_to = Some(false);
Then::Section(0)
}
_ => Then::Nothing,
},
Focus::Nav => match a {
Action::Left if nav > 0 => Then::Section(nav - 1),
Action::Right if nav + 1 < SECTIONS.len() => Then::Section(nav + 1),
Action::Right if has_track => {
capsule_to = Some(true);
Then::Moved
}
Action::Down | Action::Ok => {
if v.lines.iter().any(|l| matches!(l.kind, Kind::Chips | Kind::Cards | Kind::Item | Kind::Hero | Kind::Keyboard | Kind::Track)) {
v.focus = Focus::Line;
v.clamp_scroll();
Then::Moved
} else {
Then::Nothing
}
}
Action::Back if nav != 0 => Then::Section(0),
Action::Back => Then::Quit,
_ => Then::Nothing,
},
Focus::Side => Then::Nothing,
Focus::Line => match a {
Action::Up => {
if !v.vertical(false) && has_nav {
v.focus = Focus::Nav;
v.scroll = 0.0;
}
Then::Moved
}
Action::Down => {
v.vertical(true);
Then::Moved
}
Action::Left => {
v.horizontal(false);
Then::Moved
}
Action::Right => {
v.horizontal(true);
Then::Moved
}
Action::Ok => {
let (l, i) = v.target();
Then::Activate(l, i)
}
Action::Back => Then::Back,
Action::PlayPause => Then::Nothing,
},
};
if let Some(cap) = capsule_to {
st.np_capsule = cap;
}
then
};
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::NowPlaying => nowplaying::open(self),
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;
}
}
}
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();
}
}