Audiphi/src/app.rs
2026-10-24 17:58:16 -05:00

692 lines
29 KiB
Rust

//! The application: state, background events, and the window chrome (tabs, banners, snackbar).
use crate::core::downloader::{LogLine, Manager};
use crate::core::library::{self, LibraryItem};
use crate::core::lyrics::Lyrics;
use crate::core::metadata::Candidate;
use crate::core::models::ResolveResult;
use crate::core::settings::Settings;
use crate::core::{paths, ytdlp};
use crate::player::Player;
use crate::ui::controls::*;
use crate::ui::gfx::*;
use crate::ui::icons::Icons;
use crate::ui::images::Images;
use crate::ui::pages::{download, editor, player_page, queue, settings_page};
use crate::ui::theme::{with_alpha, Theme};
use crate::ui::widgets::*;
use eframe::egui::{self, Align2, Color32, Pos2, Rect, RichText, Sense, Vec2};
use std::collections::BTreeMap;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::{Duration, Instant};
pub const TAB_DOWNLOAD: usize = 0;
pub const TAB_QUEUE: usize = 1;
pub const TAB_PLAYER: usize = 2;
pub const TAB_SETTINGS: usize = 3;
pub enum Ev {
Resolved(u64, Result<ResolveResult, String>),
FetchInfo(u64, String),
Library(Vec<LibraryItem>),
LyricsFound(String, Result<Option<String>, String>),
Candidates(Result<BTreeMap<String, Vec<Candidate>>, String>),
EditorLyrics(Result<Lyrics, String>),
EditorCover(Option<Vec<u8>>),
SpotifyTest(String),
YtdlpUpdate(String),
Toast(String),
Log(u64, String, String),
}
pub struct LogEntry {
pub job: u64,
pub kind: String,
pub text: String,
}
pub struct Toast {
pub text: String,
pub action: Option<(String, usize)>,
pub at: Instant,
}
pub struct Confirm {
pub title: String,
pub text: String,
pub ok: String,
}
pub struct App {
pub ctx: egui::Context,
pub g: Gfx,
pub settings: Settings,
pub images: Images,
pub tab: usize,
pub tx: Sender<Ev>,
rx: Receiver<Ev>,
pub manager: Manager,
log_rx: Receiver<LogLine>,
pub logs: Vec<LogEntry>,
pub dl: download::State,
pub q: queue::State,
pub pl: player_page::State,
pub st: settings_page::State,
pub player: Player,
pub editor: Option<editor::Editor>,
pub confirm: Option<Confirm>,
pub toast: Option<Toast>,
cover_seed: Option<Color32>,
seed_key: String,
theme_rev: u64,
sys_mtime: Option<std::time::SystemTime>,
last_check: Instant,
last_frame: Instant,
pub quit_asked: bool,
pub quitting: bool,
pub ffmpeg_ok: bool,
pub ytdlp_ok: bool,
shots: Option<Shots>,
}
pub fn apply_visuals(ctx: &egui::Context, t: &Theme) {
let mut v = if t.dark { egui::Visuals::dark() } else { egui::Visuals::light() };
v.panel_fill = t.surface;
v.window_fill = t.surface_container;
v.extreme_bg_color = t.surface_container_highest;
v.faint_bg_color = t.surface_container_low;
v.code_bg_color = t.surface_container_high;
v.override_text_color = Some(t.on_surface);
v.hyperlink_color = t.primary;
v.selection.bg_fill = t.primary;
v.selection.stroke = egui::Stroke::new(1.0, t.on_primary);
v.window_stroke = egui::Stroke::new(1.0, with_alpha(t.outline_variant, 0.6));
v.window_corner_radius = cr(24.0);
v.menu_corner_radius = cr(14.0);
v.popup_shadow = egui::Shadow { offset: [0, 6], blur: 24, spread: 0, color: Color32::from_black_alpha(90) };
v.window_shadow = egui::Shadow { offset: [0, 10], blur: 40, spread: 0, color: Color32::from_black_alpha(110) };
let w = &mut v.widgets;
for (wd, bg) in [(&mut w.noninteractive, t.surface), (&mut w.inactive, t.surface_container_high), (&mut w.hovered, t.surface_container_highest), (&mut w.active, t.surface_container_highest), (&mut w.open, t.surface_container_highest)] {
wd.bg_fill = bg;
wd.weak_bg_fill = bg;
wd.fg_stroke.color = t.on_surface;
wd.corner_radius = cr(10.0);
wd.bg_stroke = egui::Stroke::NONE;
}
w.noninteractive.bg_stroke = egui::Stroke::new(1.0, t.outline_variant);
ctx.set_visuals(v);
ctx.global_style_mut(|s| {
s.spacing.item_spacing = egui::vec2(8.0, 6.0);
s.spacing.button_padding = egui::vec2(14.0, 7.0);
s.spacing.scroll = egui::style::ScrollStyle { floating: true, bar_width: 8.0, floating_width: 4.0, floating_allocated_width: 0.0, foreground_color: false, dormant_background_opacity: 0.0, active_background_opacity: 0.2, interact_background_opacity: 0.35, dormant_handle_opacity: 0.35, active_handle_opacity: 0.55, interact_handle_opacity: 0.8, ..egui::style::ScrollStyle::floating() };
s.interaction.tooltip_delay = 0.4;
});
}
impl App {
pub fn new(cc: &eframe::CreationContext<'_>, url: Option<String>) -> App {
let ctx = cc.egui_ctx.clone();
ctx.set_missing_glyph_policy(eframe::epaint::text::MissingGlyphPolicy::Tofu);
crate::ui::fonts::install(&ctx);
let settings = Settings::load();
let snap = settings.snapshot();
let theme = Theme::build(&snap, None);
apply_visuals(&ctx, &theme);
let g = Gfx { theme, icons: Icons::default(), ctx: ctx.clone() };
let (tx, rx) = channel();
let (log_tx, log_rx) = channel();
let repaint_ctx = ctx.clone();
let manager = Manager::new(settings.get_i64("download.concurrent").max(1) as usize, log_tx, Arc::new(move || repaint_ctx.request_repaint()));
let player = Player::new(&ctx, &settings);
let mut app = App {
images: Images::new(&ctx),
tab: (settings.get_i64("ui.last_tab").clamp(0, 3)) as usize,
dl: download::State::new(&settings),
q: queue::State::default(),
pl: player_page::State::default(),
st: settings_page::State::default(),
player,
editor: None,
confirm: None,
toast: None,
cover_seed: None,
seed_key: String::new(),
theme_rev: settings.revision,
sys_mtime: crate::ui::theme::system_mtime(),
last_check: Instant::now(),
last_frame: Instant::now(),
quit_asked: false,
quitting: false,
ffmpeg_ok: paths::find_ffmpeg(&settings.get_str("download.ffmpeg_path")).is_some(),
ytdlp_ok: paths::find_ytdlp().is_some(),
shots: std::env::var_os("AUDIPHI_SHOTS").map(|d| Shots { dir: d.into(), step: 0, started: Instant::now(), wait_until: 0.0, pending: None }),
logs: vec![],
manager,
log_rx,
tx,
rx,
settings,
g,
ctx,
};
app.rescan_library();
if let Some(u) = url {
app.open_url(&u);
}
app
}
// ---- helpers used by the pages --------------------------------------------------
pub fn toast(&mut self, text: impl Into<String>) {
self.toast = Some(Toast { text: text.into(), action: None, at: Instant::now() });
}
pub fn toast_action(&mut self, text: impl Into<String>, label: &str, tab: usize) {
self.toast = Some(Toast { text: text.into(), action: Some((label.into(), tab)), at: Instant::now() });
}
pub fn open_url(&mut self, url: &str) {
self.tab = TAB_DOWNLOAD;
self.dl.query = url.to_string();
download::fetch(self, "top");
}
pub fn rescan_library(&mut self) {
let dir = self.settings.library_dir();
let tx = self.tx.clone();
let ctx = self.ctx.clone();
self.pl.scanning = true;
std::thread::spawn(move || {
let _ = tx.send(Ev::Library(library::scan(&dir)));
ctx.request_repaint();
});
}
pub fn log(&mut self, job: u64, kind: &str, text: &str) {
self.logs.push(LogEntry { job, kind: kind.into(), text: text.into() });
if self.logs.len() > 6000 {
self.logs.drain(..1000);
}
}
pub fn play_file(&mut self, path: &str) {
self.tab = TAB_PLAYER;
let items = self.pl.visible_items();
self.player.set_queue(&items);
self.player.play_path(path);
}
pub fn edit_file(&mut self, path: &str) {
if !std::path::Path::new(path).is_file() {
self.toast("That file isn't there anymore");
return;
}
self.editor = Some(editor::Editor::for_file(path));
}
/// Run `work` on a thread and deliver its result as an event.
pub fn spawn<T: Send + 'static>(&self, work: impl FnOnce() -> T + Send + 'static, wrap: impl FnOnce(T) -> Ev + Send + 'static) {
let (tx, ctx) = (self.tx.clone(), self.ctx.clone());
std::thread::spawn(move || {
let v = work();
let _ = tx.send(wrap(v));
ctx.request_repaint();
});
}
// ---- events ----------------------------------------------------------------------
fn pump(&mut self) {
self.images.pump();
while let Ok(l) = self.log_rx.try_recv() {
self.log(l.job, &l.kind, &l.text);
}
while let Ok(ev) = self.rx.try_recv() {
match ev {
Ev::Resolved(token, r) => download::resolved(self, token, r),
Ev::FetchInfo(token, text) => {
if token == self.dl.token {
self.dl.detail = text;
}
}
Ev::Library(items) => {
self.pl.scanning = false;
self.pl.set_items(items);
let v = self.pl.visible_items();
self.player.set_queue(&v);
}
Ev::LyricsFound(path, r) => player_page::lyrics_found(self, &path, r),
Ev::Candidates(r) => {
if let Some(e) = &mut self.editor {
e.lookup_busy = false;
match r {
Ok(c) => e.candidates = Some(c),
Err(m) => e.error = m,
}
}
}
Ev::EditorLyrics(r) => {
if let Some(e) = &mut self.editor {
e.lyrics_busy = false;
match r {
Ok(l) if l.instrumental => e.lyrics_state = "LRCLIB lists this as instrumental".into(),
Ok(l) if l.found() => {
e.lyrics = if l.synced.is_empty() { l.plain } else { l.synced };
e.lyrics_touched = true;
}
Ok(_) => e.lyrics_state = "Nothing on LRCLIB for this song".into(),
Err(m) => e.lyrics_state = format!("Lookup failed: {m}"),
}
}
}
Ev::EditorCover(bytes) => {
if let Some(e) = &mut self.editor {
if let Some(b) = bytes {
e.set_cover(&mut self.images, b, true);
}
}
}
Ev::SpotifyTest(m) => {
self.st.spotify_status = m;
self.st.spotify_busy = false;
}
Ev::YtdlpUpdate(m) => {
self.st.ytdlp_note = m;
self.st.ytdlp_busy = false;
self.ytdlp_ok = paths::find_ytdlp().is_some();
}
Ev::Toast(t) => self.toast(t),
Ev::Log(job, kind, text) => self.log(job, &kind, &text),
}
}
}
fn check_theme(&mut self) {
let mut rebuild = false;
if self.theme_rev != self.settings.revision {
self.theme_rev = self.settings.revision;
rebuild = true;
}
if self.last_check.elapsed() > Duration::from_secs(2) {
self.last_check = Instant::now();
let m = crate::ui::theme::system_mtime();
if m != self.sys_mtime {
self.sys_mtime = m;
rebuild = true;
}
}
// follow the album art of what's playing
let key = self.player.cover_key.clone();
if key != self.seed_key {
if let Some(c) = self.images.accent(&key) {
self.seed_key = key;
self.cover_seed = Some(c);
rebuild = true;
} else if self.images.get(&key).is_some() {
self.seed_key = key;
}
}
if rebuild {
let t = Theme::build(&self.settings.snapshot(), self.cover_seed);
if !t.same_colors(&self.g.theme) || t.source != self.g.theme.source {
apply_visuals(&self.ctx, &t);
self.g.theme = t;
}
}
}
fn shortcuts(&mut self, ctx: &egui::Context) {
let typing = ctx.egui_wants_keyboard_input();
let (ctrl, keys, pasted): (bool, Vec<egui::Key>, Option<String>) = ctx.input(|i| {
let keys = i.events.iter().filter_map(|e| if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { if modifiers.command || !modifiers.any() { Some(*key) } else { None } } else { None }).collect();
let pasted = i.events.iter().find_map(|e| if let egui::Event::Paste(s) = e { Some(s.clone()) } else { None });
(i.modifiers.command, keys, pasted)
});
for k in keys {
if ctrl {
match k {
egui::Key::Num1 => self.tab = 0,
egui::Key::Num2 => self.tab = 1,
egui::Key::Num3 => self.tab = 2,
egui::Key::Num4 => self.tab = 3,
egui::Key::L | egui::Key::F => {
self.tab = TAB_DOWNLOAD;
self.dl.focus_query = true;
}
egui::Key::Backtick => {
let v = !self.settings.get_bool("ui.show_terminal");
self.settings.set_bool("ui.show_terminal", v);
}
_ => {}
}
} else if k == egui::Key::Space && !typing && !self.player.path.is_empty() {
self.player.toggle();
}
}
if let (Some(text), false) = (pasted, typing) {
let t = text.trim();
if !t.is_empty() {
self.tab = TAB_DOWNLOAD;
self.dl.query = t.to_string();
download::fetch(self, "top");
}
}
}
fn handle_drops(&mut self, ctx: &egui::Context) {
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
for f in dropped {
let p = f.path();
if paths::is_audio(p) {
self.play_file(&p.to_string_lossy());
return;
}
}
}
}
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let now = Instant::now();
let dt = now.duration_since(self.last_frame).as_secs_f32().clamp(1.0 / 240.0, 0.1);
self.last_frame = now;
self.pump();
self.drive_shots(ctx);
self.handle_drops(ctx);
self.shortcuts(ctx);
self.check_theme();
self.settings.save_if_due();
let moving = self.player.tick();
if self.settings.get_bool("player.visualizer") && self.tab == TAB_PLAYER {
let n = self.settings.get_i64("player.visualizer_bars").clamp(16, 128) as usize;
let (pos, active) = (self.player.pos, self.player.playing);
self.player.spectrum.update(pos, n, active, dt);
}
if self.player.track_changed {
self.player.track_changed = false;
let key = self.player.cover_key.clone();
self.images.forget(&key);
self.images.request(&key, || crate::ui::images::Source::File(self.player.path.clone()), 900);
player_page::on_track_changed(self);
}
if let Some((done, failed)) = self.manager.poll_all_done() {
let text = format!("Downloads finished: {done} saved{}", if failed > 0 { format!(", {failed} failed") } else { String::new() });
self.toast_action(text.clone(), "Show", TAB_QUEUE);
if !ctx.input(|i| i.focused) {
let _ = std::process::Command::new("notify-send").args(["-a", crate::APP_NAME, &format!("{}", crate::APP_NAME), &text]).spawn();
}
self.rescan_library();
}
if let Some(t) = &self.toast {
if t.at.elapsed() > Duration::from_secs(6) {
self.toast = None;
}
}
if ctx.input(|i| i.viewport().close_requested()) && !self.quitting {
let active = self.manager.counts().0;
if active > 0 && !self.quit_asked {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.confirm = Some(Confirm { title: "Quit while downloading?".into(), text: format!("{active} download{} still running and will stop.", if active == 1 { " is" } else { "s are" }), ok: "Quit".into() });
} else {
self.quitting = true;
self.manager.cancel_all();
self.settings.set("ui.last_tab", serde_json::json!(self.tab));
self.settings.save();
self.player.stop();
}
}
if moving {
ctx.request_repaint_after(Duration::from_millis(16));
}
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
let t = self.g.theme.clone();
egui::Panel::top("tabs").frame(egui::Frame::NONE.fill(t.surface).inner_margin(egui::Margin { left: 16, right: 16, top: 10, bottom: 4 })).show_separator_line(false).show(ui, |ui| {
self.draw_tabs(ui);
self.draw_banners(ui);
});
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.surface)).show(ui, |ui| {
match self.tab {
TAB_DOWNLOAD => download::draw(self, ui),
TAB_QUEUE => queue::draw(self, ui),
TAB_PLAYER => player_page::draw(self, ui),
_ => settings_page::draw(self, ui),
}
});
self.draw_toast(&ctx);
self.draw_confirm(&ctx);
editor::show(self, &ctx);
if self.images.loading() {
ctx.request_repaint_after(Duration::from_millis(100));
}
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
self.manager.cancel_all();
self.settings.set("ui.last_tab", serde_json::json!(self.tab));
self.settings.save();
self.player.stop();
}
}
impl App {
fn draw_tabs(&mut self, ui: &mut egui::Ui) {
let labels = [("download", "Download"), ("downloading", "Downloads"), ("play_circle", "Player"), ("settings", "Settings")];
let active = self.manager.counts().0;
ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::new(150.0, 40.0), Sense::hover());
let t = self.g.theme.clone();
self.g.icon_at(ui.painter(), Pos2::new(rect.left() + 16.0, rect.center().y), 26.0, "library_music_fill", t.primary);
ui.painter().text(Pos2::new(rect.left() + 38.0, rect.center().y), Align2::LEFT_CENTER, crate::APP_NAME, disp_semi(21.0), t.on_surface);
let total: f32 = 4.0 * 128.0;
let left = ((ui.available_width() - total) / 2.0).max(0.0);
ui.add_space(left);
for (i, (icon, label)) in labels.iter().enumerate() {
let sel = self.tab == i;
let (rect, resp) = ui.allocate_exact_size(Vec2::new(122.0, 40.0), Sense::click());
let t = &self.g.theme;
let hover = ui.ctx().animate_bool_with_time(resp.id.with("h"), resp.hovered(), 0.12);
let anim = ui.ctx().animate_bool_with_time(resp.id.with("s"), sel, 0.18);
let bg = mix_c(with_alpha(t.on_surface, hover * 0.06), t.secondary_container, anim);
ui.painter().rect_filled(rect, cr(20.0), bg);
let fg = mix_c(t.on_surface_variant, t.on_secondary_container, anim);
let fnt = if sel { font_semi(14.5) } else { font(14.5) };
let tw = ui.painter().layout_no_wrap(label.to_string(), fnt.clone(), Color32::WHITE).size().x;
let x0 = rect.center().x - (tw + 28.0) / 2.0;
self.g.icon(ui.painter(), Rect::from_center_size(Pos2::new(x0 + 10.0, rect.center().y), Vec2::splat(20.0)), if sel && i == 2 { "play_circle_fill" } else { icon }, fg);
ui.painter().text(Pos2::new(x0 + 28.0, rect.center().y), Align2::LEFT_CENTER, label, fnt, fg);
if i == TAB_QUEUE && active > 0 {
let c = Pos2::new(rect.right() - 12.0, rect.top() + 9.0);
ui.painter().circle_filled(c, 9.0, self.g.theme.primary);
ui.painter().text(c, Align2::CENTER_CENTER, active.min(99).to_string(), font_semi(11.0), self.g.theme.on_primary);
}
if resp.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if resp.clicked() {
self.tab = i;
}
}
});
}
fn draw_banners(&mut self, ui: &mut egui::Ui) {
let mut msgs = vec![];
if !self.ffmpeg_ok {
msgs.push("ffmpeg wasn't found. Downloads need it to convert audio — install it (e.g. “sudo pacman -S ffmpeg”) or set its location in Settings.");
}
if !self.ytdlp_ok {
msgs.push("yt-dlp wasn't found. Install it (e.g. “sudo pacman -S yt-dlp”) so Audiphi can download.");
}
for m in msgs {
let t = self.g.theme.clone();
ui.add_space(6.0);
let mut go = false;
egui::Frame::NONE.fill(t.error_container).corner_radius(cr(16.0)).inner_margin(egui::Margin::symmetric(16, 10)).show(ui, |ui| {
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(Vec2::splat(22.0), Sense::hover());
self.g.icon(ui.painter(), r, "warning", t.on_error_container);
ui.label(RichText::new(m).color(t.on_error_container));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
go = button_h(ui, &mut self.g, None, "Settings", Kind::Text, 32.0).clicked();
});
});
});
if go {
self.tab = TAB_SETTINGS;
}
}
}
fn draw_toast(&mut self, ctx: &egui::Context) {
let Some(t) = self.toast.as_ref().map(|t| (t.text.clone(), t.action.clone())) else { return };
let th = self.g.theme.clone();
let mut act = None;
let mut close = false;
egui::Area::new(egui::Id::new("toast")).order(egui::Order::Foreground).anchor(Align2::CENTER_BOTTOM, Vec2::new(0.0, -86.0)).show(ctx, |ui| {
egui::Frame::NONE.fill(th.inverse_surface).corner_radius(cr(12.0)).inner_margin(egui::Margin::symmetric(18, 8)).shadow(egui::Shadow { offset: [0, 4], blur: 14, spread: 0, color: Color32::from_black_alpha(80) }).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(&t.0).color(th.inverse_on_surface).size(14.0));
if let Some((label, tab)) = &t.1 {
if ui.add(egui::Button::new(RichText::new(label).color(th.primary_container).strong()).frame(false)).clicked() {
act = Some(*tab);
}
}
if ui.add(egui::Button::new(RichText::new("✕").color(th.inverse_on_surface)).frame(false)).clicked() {
close = true;
}
});
});
});
if let Some(tab) = act {
self.tab = tab;
self.toast = None;
}
if close {
self.toast = None;
}
ctx.request_repaint_after(Duration::from_millis(500));
}
fn draw_confirm(&mut self, ctx: &egui::Context) {
let Some(c) = self.confirm.as_ref().map(|c| (c.title.clone(), c.text.clone(), c.ok.clone())) else { return };
let (mut ok, mut cancel) = (false, ctx.input(|i| i.key_pressed(egui::Key::Escape)));
let fr = egui::Frame::NONE.fill(self.g.theme.surface_container_high).corner_radius(cr(28.0)).inner_margin(egui::Margin::same(24));
egui::Modal::new(egui::Id::new("confirm")).frame(fr).backdrop_color(Color32::from_black_alpha(130)).show(ctx, |ui| {
ui.set_width(380.0);
ui.label(RichText::new(&c.0).font(disp_semi(20.0)).color(self.g.theme.on_surface));
ui.add_space(6.0);
ui.label(RichText::new(&c.1).color(self.g.theme.on_surface_variant));
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ok = button(ui, &mut self.g, None, &c.2, Kind::Danger).clicked();
cancel |= button(ui, &mut self.g, None, "Cancel", Kind::Text).clicked();
});
});
if ok {
self.confirm = None;
self.quit_asked = true;
self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else if cancel {
self.confirm = None;
}
}
pub fn check_ytdlp_now(&mut self) -> Option<String> {
ytdlp::version()
}
}
/// Hidden test harness: `AUDIPHI_SHOTS=/dir AUDIPHI_SHOT_URL=<link>` walks the tabs, saving screenshots.
struct Shots {
dir: std::path::PathBuf,
step: usize,
started: Instant,
wait_until: f64,
pending: Option<Arc<std::sync::atomic::AtomicBool>>,
}
impl App {
fn drive_shots(&mut self, ctx: &egui::Context) {
let Some(mut sh) = self.shots.take() else { return };
let now = sh.started.elapsed().as_secs_f64();
if let Some(flag) = &sh.pending {
if flag.load(std::sync::atomic::Ordering::Relaxed) {
sh.pending = None;
}
}
if sh.pending.is_none() && now >= sh.wait_until {
let shoot = |sh: &mut Shots, name: &str| {
let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
sh.pending = Some(flag.clone());
let path = sh.dir.join(format!("{name}.png"));
let _ = std::fs::create_dir_all(&sh.dir);
let name = name.to_string();
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |img| {
let mut out = image::RgbaImage::new(img.width() as u32, img.height() as u32);
for (i, p) in img.pixels.iter().enumerate() {
out.put_pixel((i % img.width()) as u32, (i / img.width()) as u32, image::Rgba([p.r(), p.g(), p.b(), 255]));
}
let _ = out.save(&path);
eprintln!("shot {name}");
flag.store(true, std::sync::atomic::Ordering::Relaxed);
})));
};
match sh.step {
0 => { if now > 2.0 { shoot(&mut sh, "1-download-empty"); sh.step = 1; } }
1 => {
if let Ok(u) = std::env::var("AUDIPHI_SHOT_URL") {
self.dl.query = u;
download::fetch(self, "top");
}
sh.step = 2;
sh.wait_until = now + 1.0;
}
2 => {
if self.dl.result.is_some() || self.dl.error.is_some() || now > 60.0 {
sh.wait_until = now + 1.5;
sh.step = 3;
}
}
3 => { shoot(&mut sh, "2-download-result"); sh.step = 4; }
4 => {
if self.dl.result.is_some() {
self.editor = Some(editor::Editor::for_track(self.dl.result.as_ref().unwrap(), None));
sh.wait_until = now + 1.5;
}
sh.step = 5;
}
5 => { shoot(&mut sh, "3-editor"); sh.step = 6; }
6 => {
self.editor = None;
download::start_download_pub(self);
self.tab = TAB_QUEUE;
self.settings.set_bool("ui.show_terminal", true);
sh.wait_until = now + 25.0;
sh.step = 7;
}
7 => { shoot(&mut sh, "4-queue"); sh.step = 8; }
8 => {
self.tab = TAB_PLAYER;
if let Some(p) = self.pl.visible_items().first().map(|i| i.path.clone()) {
self.play_file(&p);
}
sh.wait_until = now + 4.0;
sh.step = 9;
}
9 => { shoot(&mut sh, "5-player"); sh.step = 10; }
10 => { self.tab = TAB_SETTINGS; sh.wait_until = now + 1.0; sh.step = 11; }
11 => { shoot(&mut sh, "6-settings"); sh.step = 12; }
_ => { if sh.pending.is_none() { ctx.send_viewport_cmd(egui::ViewportCommand::Close); self.quit_asked = true; } }
}
}
self.shots = Some(sh);
ctx.request_repaint_after(Duration::from_millis(100));
}
}