Real background mode: closing the window or Ctrl+Q keeps playing in the tray

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-10-24 15:38:16 -05:00
commit 97770c9eb4
10 changed files with 273 additions and 83 deletions

View file

@ -78,6 +78,10 @@ pub struct App {
pub menu: Option<crate::ui::menus::OpenMenu>,
pub tray: Option<crate::tray::Tray>,
pub hidden: bool,
/// window closed but the player keeps running (tray)
pub background: bool,
pub headless: bool,
pub want_window: bool,
pub block_tex: Option<egui::TextureHandle>,
}
@ -123,7 +127,7 @@ impl App {
pub fn with_ctx(ctx: &egui::Context, args: Vec<String>) -> App {
let ctx = ctx.clone();
let (tx, rx) = channel();
let bus = Bus { tx, ctx: ctx.clone() };
let bus = Bus::new(tx, ctx.clone());
fonts_setup(&ctx);
let lib = Arc::new(Library::new());
let mut mgr = Manager::new();
@ -175,6 +179,9 @@ impl App {
block_tex: None,
tray: None,
hidden: false,
background: false,
headless: false,
want_window: false,
};
app.mpris = if std::env::var_os("MULBERRY_TEST").is_some() { None } else { crate::mpris::Mpris::start(bus.clone()) };
if settings().get_bool("appearance/tray") && std::env::var_os("MULBERRY_TEST").is_none() {
@ -200,6 +207,12 @@ impl App {
// ================================================================ messages
fn handle_msgs(&mut self) {
while let Ok(m) = self.rx.try_recv() {
self.handle_msg(m);
}
}
fn handle_msg(&mut self, m: Msg) {
{
match m {
Msg::ScanProgress { done, total } => self.scan = if done >= total { None } else { Some((done, total)) },
Msg::ScanFinished { added, updated, removed } => {
@ -247,6 +260,11 @@ impl App {
}
Msg::Mpris(cmd) => self.on_mpris(cmd),
Msg::Picked { purpose, paths } => self.on_picked(&purpose, paths),
Msg::Raise if self.headless => self.want_window = true,
Msg::OpenArgs(args) if self.headless => {
self.handle_args(args);
self.want_window = true;
}
Msg::Raise => {
self.hidden = false;
self.ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
@ -385,7 +403,7 @@ impl App {
if !settings().get_bool("appearance/notifications") {
return;
}
let focused = self.ctx.input(|i| i.viewport().focused.unwrap_or(true));
let focused = !self.headless && self.ctx.input(|i| i.viewport().focused.unwrap_or(true));
let Some(s) = self.player.song.clone() else { return };
if focused || !self.player.is_playing() {
return;
@ -691,18 +709,13 @@ impl App {
self.player.set_volume((v * 100.0).round() as i64);
self.drain_notes();
}
MprisCmd::Raise | MprisCmd::ToggleVisible if self.headless => self.want_window = true,
MprisCmd::ToggleVisible => self.go_background(),
MprisCmd::Raise => {
self.hidden = false;
self.ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
self.ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
MprisCmd::ToggleVisible => {
self.hidden = !self.hidden;
self.ctx.send_viewport_cmd(egui::ViewportCommand::Visible(!self.hidden));
if !self.hidden {
self.ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
}
MprisCmd::Quit => self.quit(),
MprisCmd::SetShuffle(b) => {
self.mgr.set_shuffle(b);
@ -774,6 +787,62 @@ impl App {
m.publish(snap);
}
/// Close the window; with the tray enabled the app keeps playing in the background.
pub fn go_background(&mut self) {
if self.tray.is_some() && settings().get_bool("appearance/tray") {
self.background = true;
self.lib.set_kv("resume_pos", &if self.player.song.is_some() { format!("{:.1}", self.player.pos()) } else { "0".into() });
self.mgr.save_all(&self.lib);
self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else {
self.quit();
}
}
/// Everything the frame loop does besides painting; also runs while no window is open.
pub fn pump_headless(&mut self, wait: Duration) {
if let Ok(m) = self.rx.recv_timeout(wait) {
self.handle_msg(m);
}
self.handle_msgs();
let _ = self.player.tick(&mut self.mgr, &self.lib);
self.drain_notes();
self.mgr.save_if_due(&self.lib);
self.maybe_notify();
self.publish_mpris();
if self.player.is_playing() && self.last_pos_save.elapsed() > Duration::from_secs(5) {
self.last_pos_save = Instant::now();
self.lib.set_kv("resume_pos", &format!("{:.1}", self.player.pos()));
}
}
/// A new window (new egui context) is taking over this app: rebuild everything bound to the old context.
pub fn attach(&mut self, ctx: &egui::Context) {
self.ctx = ctx.clone();
self.bus.set_ctx(ctx.clone());
self.g.ctx = ctx.clone();
self.g.icons = Icons::default();
self.thumbs = crate::ui::thumbs::Thumbs::default();
self.block_tex = None;
self.np.drop_textures();
self.menu = None;
self.dialog = None;
self.background = false;
self.headless = false;
self.want_window = false;
self.title_cache.clear();
self.hero.bg_dirty = true;
fonts_setup(ctx);
let t = Theme::build(self.album_seed);
apply_visuals(ctx, &t);
self.g.theme = t;
self.apply_icon();
if let Some(s) = self.player.song.clone() {
self.np.load_art(&s, true);
self.on_song_changed();
}
}
pub fn quit(&mut self) {
if self.quitting {
return;
@ -885,7 +954,7 @@ impl App {
"redo" => { let c = self.mgr.current_mut(); c.redo(); self.mgr.touch(); }
"export" => { let u = self.mgr.current; crate::ui::menus::export_playlist(self, u); }
"import" => crate::ui::menus::import_playlist(self),
"quit" => self.quit(),
"quit" => self.go_background(),
"settings" => self.dialog = Some(Dialog::settings()),
"sidebar" => { self.show_sidebar = !self.show_sidebar; settings().set("ui/sidebar", self.show_sidebar); }
"scan" => self.lib.scan(false, self.bus.clone()),
@ -1023,19 +1092,9 @@ impl eframe::App for App {
self.scan_note = None;
}
}
if self.hidden && (self.player.is_playing() || self.player.state == "loading") {
// no UI passes while hidden: keep the player ticking (crossfade, played counts)
ctx.request_repaint_after(Duration::from_millis(250));
}
if ctx.input(|i| i.viewport().close_requested()) && !self.quitting {
if self.tray.is_some() && settings().get_bool("appearance/tray") && !is_wayland() {
// close to tray
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
self.hidden = true;
} else {
self.quit_now();
}
if ctx.input(|i| i.viewport().close_requested()) && !self.quitting && !self.background {
// the title-bar X behaves like Ctrl+Q: tray on -> keep playing in the background, tray off -> exit
self.go_background();
}
}
@ -1055,12 +1114,14 @@ impl eframe::App for App {
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
self.quit_now();
if !self.background {
self.quit_now();
}
}
}
impl App {
fn quit_now(&mut self) {
pub fn quit_now(&mut self) {
self.quitting = true;
if let Some(r) = self.ctx.input(|i| i.viewport().inner_rect) {
if r.width() > 200.0 && r.height() > 200.0 {

View file

@ -76,16 +76,30 @@ pub enum MprisCmd {
SetLoop(String),
}
/// Channel to the UI thread. The egui context can be swapped, so the bus survives the window
/// being closed (background mode) and reopened.
#[derive(Clone)]
pub struct Bus {
pub tx: Sender<Msg>,
pub ctx: egui::Context,
ctx: std::sync::Arc<std::sync::Mutex<egui::Context>>,
}
impl Bus {
pub fn new(tx: Sender<Msg>, ctx: egui::Context) -> Bus {
Bus { tx, ctx: std::sync::Arc::new(std::sync::Mutex::new(ctx)) }
}
pub fn set_ctx(&self, ctx: egui::Context) {
*self.ctx.lock().unwrap() = ctx;
}
pub fn repaint(&self) {
self.ctx.lock().unwrap().request_repaint();
}
pub fn send(&self, m: Msg) {
let _ = self.tx.send(m);
self.ctx.request_repaint();
self.repaint();
}
pub fn toast(&self, s: impl Into<String>) {

View file

@ -1,4 +1,7 @@
use eframe::egui;
use eframe::App as _;
use std::cell::RefCell;
use std::rc::Rc;
use mulberry::{app, config, instance};
fn app_icon() -> egui::IconData {
@ -41,6 +44,63 @@ fn main() -> eframe::Result {
.with_inner_size([win_w, win_h])
.with_min_inner_size([860.0, 560.0])
.with_icon(std::sync::Arc::new(app_icon()));
let options = eframe::NativeOptions { viewport, multisampling: 4, ..Default::default() };
eframe::run_native(config::APP_NAME, options, Box::new(move |cc| Ok(Box::new(app::App::new(cc, abs.clone())))))
let options = || eframe::NativeOptions { viewport: viewport.clone(), multisampling: 4, run_and_return: true, ..Default::default() };
let cell: Rc<RefCell<Option<app::App>>> = Rc::new(RefCell::new(None));
loop {
let c = cell.clone();
let args = abs.clone();
eframe::run_native(
config::APP_NAME,
options(),
Box::new(move |cc| {
{
let mut slot = c.borrow_mut();
match slot.as_mut() {
Some(a) => a.attach(&cc.egui_ctx),
None => *slot = Some(app::App::new(cc, args)),
}
}
Ok(Box::new(Shell(c)))
}),
)?;
// the window is gone: keep playing in the background (tray) until it is asked for again or quit
let mut guard = cell.borrow_mut();
let app = guard.as_mut().expect("app");
if !app.background {
break;
}
app.headless = true;
app.spectrum.set_consumers(0);
while !app.want_window && !app.quitting {
app.pump_headless(std::time::Duration::from_millis(100));
}
if app.quitting {
break;
}
}
if let Some(a) = cell.borrow_mut().as_mut() {
a.quit_now();
}
Ok(())
}
/// Hands the persistent app to each window that is opened.
struct Shell(Rc<RefCell<Option<app::App>>>);
impl eframe::App for Shell {
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
if let Some(a) = self.0.borrow_mut().as_mut() {
a.logic(ctx, frame);
}
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
if let Some(a) = self.0.borrow_mut().as_mut() {
a.ui(ui, frame);
}
}
fn on_exit(&mut self, gl: Option<&eframe::glow::Context>) {
if let Some(a) = self.0.borrow_mut().as_mut() {
a.on_exit(gl);
}
}
}

View file

@ -63,6 +63,12 @@ impl NowPlaying {
}
}
pub fn drop_textures(&mut self) {
self.cover_tex = None;
self.blur_tex = None;
self.art_ident.clear();
}
pub fn on_song(&mut self, s: &Song) {
let prev = self.song.take();
let same = prev.as_ref().map(|p| p.url == s.url && p.begin == s.begin).unwrap_or(false);

View file

@ -59,7 +59,7 @@ impl CdState {
(toc, rels, cover)
});
*pending.lock().unwrap() = Some(res);
bus.ctx.request_repaint();
bus.repaint();
});
}

24
tests/background.rs Normal file
View file

@ -0,0 +1,24 @@
use eframe::egui::{self, vec2};
use egui_kittest::Harness;
use mulberry::app::App;
#[test]
fn background_mode_reattaches_to_a_new_window() {
let sc = std::env::temp_dir().join(format!("mulberry-bg-{}", std::process::id()));
std::fs::create_dir_all(sc.join("config/mulberry")).unwrap();
std::env::set_var("MULBERRY_TEST", "1");
std::env::set_var("XDG_DATA_HOME", sc.join("data"));
std::env::set_var("XDG_CONFIG_HOME", sc.join("config"));
std::env::set_var("XDG_CACHE_HOME", sc.join("cache"));
let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).wgpu().build_eframe(|cc| App::new(cc, vec![]));
for _ in 0..5 { h.step(); std::thread::sleep(std::time::Duration::from_millis(40)); }
let ctx2 = egui::Context::default();
let app = h.state_mut();
app.headless = true;
for _ in 0..5 {
app.pump_headless(std::time::Duration::from_millis(10));
}
app.attach(&ctx2);
assert!(!app.headless && !app.background);
for _ in 0..5 { h.step(); std::thread::sleep(std::time::Duration::from_millis(40)); }
}

View file

@ -9,7 +9,7 @@ use std::time::Duration;
fn mpris_and_tray_register_and_control() {
let ctx = egui::Context::default();
let (tx, rx) = channel();
let bus = Bus { tx, ctx };
let bus = Bus::new(tx, ctx);
let m = mulberry::mpris::Mpris::start(bus.clone()).expect("mpris");
let _t = mulberry::tray::Tray::start(bus.clone());
m.publish(mulberry::mpris::Snapshot { status: "Playing".into(), has_song: true, track_id: "/org/mulberry/track/1".into(), title: "Gasoline".into(), artists: vec!["Seether".into()], album: "Disclaimer II".into(), length_us: 168_000_000, ..Default::default() });

74
tests/dnd_e2e.rs Normal file
View file

@ -0,0 +1,74 @@
//! End to end: select several tracks, right-click the Album cell of one, choose
//! “Set album to …” and check the files on disk were rewritten (generated files only).
use eframe::egui::{self, pos2, vec2, Event, Modifiers, PointerButton};
use egui_kittest::Harness;
use mulberry::app::{AddMode, App};
fn click(h: &mut Harness<'_, App>, pos: egui::Pos2, button: PointerButton, mods: Modifiers) {
h.input_mut().events.push(Event::ModifiersChanged(mods));
h.input_mut().events.push(Event::PointerMoved(pos));
h.step();
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: true, modifiers: mods });
h.step();
h.input_mut().events.push(Event::PointerButton { pos, button, pressed: false, modifiers: mods });
h.step();
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
h.step();
}
fn settle(h: &mut Harness<'_, App>, n: usize) {
for _ in 0..n {
h.step();
std::thread::sleep(std::time::Duration::from_millis(40));
}
}
#[test]
fn drag_library_track_into_playlist() {
let sc = std::env::temp_dir().join(format!("mulberry-dnd-{}", std::process::id()));
let music = sc.join("music/Seether/Disclaimer II");
std::fs::create_dir_all(&music).unwrap();
std::fs::create_dir_all(sc.join("config/mulberry")).unwrap();
std::fs::write(sc.join("config/mulberry/settings.json"), format!("{{\"library/folders\": [\"{}\"], \"library/scan_on_start\": true, \"playback/resume\": false}}", sc.join("music").display())).unwrap();
std::env::set_var("MULBERRY_TEST", "1");
std::env::set_var("XDG_DATA_HOME", sc.join("data"));
std::env::set_var("XDG_CONFIG_HOME", sc.join("config"));
std::env::set_var("XDG_CACHE_HOME", sc.join("cache"));
for i in 1..=3 {
let p = music.join(format!("{i:02}.flac"));
assert!(std::process::Command::new("ffmpeg")
.args(["-v", "quiet", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=5", "-metadata", "album=Disclaimer II", "-metadata", &format!("title=Song {i}"), "-metadata", "artist=Seether", "-metadata", &format!("track={i}")])
.arg(&p)
.status()
.unwrap()
.success());
}
let mut h = Harness::builder().with_size(vec2(1380.0, 860.0)).wgpu().build_eframe(|cc| App::new(cc, vec![]));
settle(&mut h, 40); // scan
click(&mut h, pos2(34.0, 60.0), PointerButton::Primary, Modifiers::NONE);
settle(&mut h, 5);
click(&mut h, pos2(26.0, 195.0), PointerButton::Primary, Modifiers::NONE); // expand artist
settle(&mut h, 3);
click(&mut h, pos2(40.0, 237.0), PointerButton::Primary, Modifiers::NONE); // expand album
settle(&mut h, 3);
h.render().unwrap().save(std::env::temp_dir().join("mulberry-dnd-1.png")).unwrap();
let before = h.state().mgr.current_pl().entries.len();
// drag the first track onto the playlist
let from = pos2(120.0, 297.0);
h.input_mut().events.push(Event::PointerMoved(from));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for (x, y) in [(200.0, 300.0), (500.0, 500.0), (800.0, 600.0)] {
h.input_mut().events.push(Event::PointerMoved(pos2(x, y)));
h.step();
}
h.render().unwrap().save(std::env::temp_dir().join("mulberry-dnd-2.png")).unwrap();
h.input_mut().events.push(Event::PointerButton { pos: pos2(800.0, 600.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
settle(&mut h, 4);
let after = h.state().mgr.current_pl().entries.len();
eprintln!("playlist entries: {before} -> {after}");
assert_eq!(after, before + 1);
}

View file

@ -22,7 +22,7 @@ fn position_is_monotonic_and_smooth() {
let ctx = egui::Context::default();
let (tx, rx) = channel();
let bus = Bus { tx, ctx: ctx.clone() };
let bus = Bus::new(tx, ctx.clone());
let lib = Library::new();
let mut mgr = Manager::new();
let mut s = Song::new(file.to_string_lossy());

View file

@ -58,10 +58,10 @@ fn set_album_from_context_menu() {
let (mx, my) = (1000.0, r0);
click(&mut h, pos2(mx, my), PointerButton::Secondary, Modifiers::NONE);
settle(&mut h, 3);
h.input_mut().events.push(Event::PointerMoved(pos2(mx + 100.0, my + 26.0 + 327.0)));
h.input_mut().events.push(Event::PointerMoved(pos2(mx + 100.0, my + 287.0)));
settle(&mut h, 3);
h.render().unwrap().save(std::env::temp_dir().join("mulberry-e2e-menu.png")).unwrap();
click(&mut h, pos2(mx + 100.0, my + 26.0 + 327.0), PointerButton::Primary, Modifiers::NONE);
click(&mut h, pos2(mx + 100.0, my + 287.0), PointerButton::Primary, Modifiers::NONE);
settle(&mut h, 30);
let got: Vec<String> = files.iter().map(|f| mulberry::tags::read_song(f).unwrap().album).collect();
eprintln!("albums after: {got:?}");
@ -72,54 +72,5 @@ fn set_album_from_context_menu() {
let back: Vec<String> = files.iter().map(|f| mulberry::tags::read_song(f).unwrap().album).collect();
eprintln!("albums after undo: {back:?}");
assert_eq!(back[1], "Isolate And Medicate");
let _ = std::fs::remove_dir_all(&sc);
}
#[test]
fn drag_library_track_into_playlist() {
let sc = std::env::temp_dir().join(format!("mulberry-dnd-{}", std::process::id()));
let music = sc.join("music/Seether/Disclaimer II");
std::fs::create_dir_all(&music).unwrap();
std::fs::create_dir_all(sc.join("config/mulberry")).unwrap();
std::fs::write(sc.join("config/mulberry/settings.json"), format!("{{\"library/folders\": [\"{}\"], \"library/scan_on_start\": true, \"playback/resume\": false}}", sc.join("music").display())).unwrap();
std::env::set_var("MULBERRY_TEST", "1");
std::env::set_var("XDG_DATA_HOME", sc.join("data"));
std::env::set_var("XDG_CONFIG_HOME", sc.join("config"));
std::env::set_var("XDG_CACHE_HOME", sc.join("cache"));
for i in 1..=3 {
let p = music.join(format!("{i:02}.flac"));
assert!(std::process::Command::new("ffmpeg")
.args(["-v", "quiet", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=5", "-metadata", "album=Disclaimer II", "-metadata", &format!("title=Song {i}"), "-metadata", "artist=Seether", "-metadata", &format!("track={i}")])
.arg(&p)
.status()
.unwrap()
.success());
}
let mut h = Harness::builder().with_size(vec2(1380.0, 860.0)).wgpu().build_eframe(|cc| App::new(cc, vec![]));
settle(&mut h, 40); // scan
click(&mut h, pos2(34.0, 60.0), PointerButton::Primary, Modifiers::NONE);
settle(&mut h, 5);
click(&mut h, pos2(26.0, 195.0), PointerButton::Primary, Modifiers::NONE); // expand artist
settle(&mut h, 3);
click(&mut h, pos2(40.0, 237.0), PointerButton::Primary, Modifiers::NONE); // expand album
settle(&mut h, 3);
h.render().unwrap().save(std::env::temp_dir().join("mulberry-dnd-1.png")).unwrap();
let before = h.state().mgr.current_pl().entries.len();
// drag the first track onto the playlist
let from = pos2(120.0, 297.0);
h.input_mut().events.push(Event::PointerMoved(from));
h.step();
h.input_mut().events.push(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for (x, y) in [(200.0, 300.0), (500.0, 500.0), (800.0, 600.0)] {
h.input_mut().events.push(Event::PointerMoved(pos2(x, y)));
h.step();
}
h.render().unwrap().save(std::env::temp_dir().join("mulberry-dnd-2.png")).unwrap();
h.input_mut().events.push(Event::PointerButton { pos: pos2(800.0, 600.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
settle(&mut h, 4);
let after = h.state().mgr.current_pl().entries.len();
eprintln!("playlist entries: {before} -> {after}");
assert_eq!(after, before + 1);
let _ = std::fs::remove_dir_all(&sc);
}