- Enable eframe's clipboard feature so Ctrl+C/X/V work in text fields - Playlist/player shortcuts no longer fire while typing in a text box - Remove "Paste files from file manager" menu item; Ctrl+V still adds copied file:// paths when no text field has focus - Submenu rows use the same font/icon metrics as other rows, and all menu rows span the full menu width - "Change shape" in the floating shape menu now morphs the shape - Edit lyrics opens with the currently active lyrics from any source Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1174 lines
50 KiB
Rust
1174 lines
50 KiB
Rust
//! Main application: owns the model (library, playlists, player) and drives the egui frame.
|
|
|
|
use crate::bus::{AddJob, Bus, Msg, MprisCmd, TagsDone};
|
|
use crate::config::{fmt_time, settings, APP_NAME};
|
|
use crate::library::Library;
|
|
use crate::nowplaying::NowPlaying;
|
|
use crate::player::{Note, Player};
|
|
use crate::playlist::{Manager, Ref};
|
|
use crate::song::Song;
|
|
use crate::spectrum::Spectrum;
|
|
use crate::tags::Field;
|
|
use crate::theme::Theme;
|
|
use crate::ui::dialogs::Dialog;
|
|
use crate::ui::gfx::Gfx;
|
|
use crate::ui::hero::HeroState;
|
|
use crate::ui::icons::Icons;
|
|
use crate::ui::playlist_view::AreaState;
|
|
use crate::ui::shape::ShapeState;
|
|
use crate::ui::sidebar::SidebarState;
|
|
use crate::{fonts_setup, playlistio, util};
|
|
use eframe::egui::{self, Color32};
|
|
use std::collections::HashMap;
|
|
use std::sync::mpsc::{channel, Receiver};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum AddMode {
|
|
Append,
|
|
Replace,
|
|
New,
|
|
Play,
|
|
Queue,
|
|
Next,
|
|
}
|
|
|
|
pub struct TagUndo {
|
|
pub items: Vec<(Song, Vec<(Field, String)>)>,
|
|
pub label: String,
|
|
pub at: Instant,
|
|
}
|
|
|
|
pub struct App {
|
|
pub ctx: egui::Context,
|
|
pub bus: Bus,
|
|
rx: Receiver<Msg>,
|
|
pub lib: Arc<Library>,
|
|
pub mgr: Manager,
|
|
pub player: Player,
|
|
pub spectrum: Spectrum,
|
|
pub g: Gfx,
|
|
pub np: NowPlaying,
|
|
pub hero: HeroState,
|
|
pub area: AreaState,
|
|
pub side: SidebarState,
|
|
pub shape: ShapeState,
|
|
pub dialog: Option<Dialog>,
|
|
pub toast: Option<(String, Instant)>,
|
|
pub tag_undo: Option<TagUndo>,
|
|
pub focus_mode: bool,
|
|
pub scan: Option<(usize, usize)>,
|
|
pub scan_note: Option<(String, Instant)>,
|
|
pub quitting: bool,
|
|
pub album_seed: Option<Color32>,
|
|
sys_mtime: Option<std::time::SystemTime>,
|
|
last_theme_check: Instant,
|
|
last_frame: Instant,
|
|
pub thumbs: crate::ui::thumbs::Thumbs,
|
|
pub mpris: Option<crate::mpris::Mpris>,
|
|
pub pending_resume: bool,
|
|
title_cache: String,
|
|
notify_due: Option<Instant>,
|
|
pub last_pos_save: Instant,
|
|
pub fps_cap: u32,
|
|
pub show_sidebar: bool,
|
|
pub scrobbler: crate::scrobble::Scrobbler,
|
|
pub seek_to: Option<f64>,
|
|
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>,
|
|
}
|
|
|
|
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, crate::theme::with_alpha(t.outline_variant, 0.6));
|
|
v.window_corner_radius = crate::ui::gfx::cr(24.0);
|
|
v.menu_corner_radius = crate::ui::gfx::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 = crate::ui::gfx::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<'_>, args: Vec<String>) -> App {
|
|
App::with_ctx(&cc.egui_ctx, args)
|
|
}
|
|
|
|
pub fn with_ctx(ctx: &egui::Context, args: Vec<String>) -> App {
|
|
let ctx = ctx.clone();
|
|
let (tx, rx) = channel();
|
|
let bus = Bus::new(tx, ctx.clone());
|
|
fonts_setup(&ctx);
|
|
let lib = Arc::new(Library::new());
|
|
let mut mgr = Manager::new();
|
|
mgr.restore(&lib);
|
|
let theme = Theme::build(None);
|
|
apply_visuals(&ctx, &theme);
|
|
let mut player = Player::new(bus.clone());
|
|
let spectrum = Spectrum::new(bus.clone());
|
|
let np = NowPlaying::new(lib.clone(), bus.clone());
|
|
let g = Gfx { theme, icons: Icons::default(), ctx: ctx.clone() };
|
|
player.apply_audio_settings();
|
|
let scrobbler = crate::scrobble::Scrobbler::new(bus.clone());
|
|
let mut app = App {
|
|
ctx: ctx.clone(),
|
|
bus: bus.clone(),
|
|
rx,
|
|
lib: lib.clone(),
|
|
mgr,
|
|
player,
|
|
spectrum,
|
|
g,
|
|
np,
|
|
hero: HeroState::new(),
|
|
area: AreaState::new(),
|
|
side: SidebarState::new(&lib),
|
|
shape: ShapeState::new(),
|
|
dialog: None,
|
|
toast: None,
|
|
tag_undo: None,
|
|
focus_mode: false,
|
|
scan: None,
|
|
scan_note: None,
|
|
quitting: false,
|
|
album_seed: None,
|
|
sys_mtime: crate::theme::system_mtime(),
|
|
last_theme_check: Instant::now(),
|
|
last_frame: Instant::now(),
|
|
thumbs: crate::ui::thumbs::Thumbs::default(),
|
|
mpris: None,
|
|
pending_resume: true,
|
|
title_cache: String::new(),
|
|
notify_due: None,
|
|
last_pos_save: Instant::now(),
|
|
fps_cap: 30,
|
|
show_sidebar: settings().get_bool("ui/sidebar"),
|
|
scrobbler,
|
|
seek_to: None,
|
|
menu: None,
|
|
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() {
|
|
app.tray = crate::tray::Tray::start(bus.clone());
|
|
}
|
|
if !app.player.backend_error.is_empty() {
|
|
app.dialog = Some(Dialog::Message { title: "Audio".into(), text: app.player.backend_error.clone() });
|
|
}
|
|
if settings().get_bool("library/scan_on_start") && !settings().get_list("library/folders").is_empty() {
|
|
app.lib.scan(false, bus.clone());
|
|
}
|
|
app.apply_icon();
|
|
app.resume_playback();
|
|
if !args.is_empty() {
|
|
app.handle_args(args);
|
|
}
|
|
if std::env::var_os("MULBERRY_TEST").is_none() {
|
|
crate::instance::serve(bus);
|
|
}
|
|
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 } => {
|
|
self.scan = None;
|
|
self.scan_note = Some((format!("Library updated: {added} added, {updated} updated, {removed} removed"), Instant::now()));
|
|
self.side.library_dirty = true;
|
|
}
|
|
Msg::Art { ident, art, path } => {
|
|
let ctx = self.ctx.clone();
|
|
let accent = self.np.on_art(&ctx, &ident, art, path, &self.lib);
|
|
self.on_art_changed(accent);
|
|
}
|
|
Msg::Lyrics { token, text, source } => {
|
|
if token == self.np.lyr_token || source == "loading" {
|
|
self.hero.on_lyrics(&text, &source, self.np.song.as_ref().map(|s| s.is_stream()).unwrap_or(false));
|
|
if source != "loading" {
|
|
// the editor opens on whatever lyrics are active, whichever source they came from
|
|
self.np.lyrics = text.clone();
|
|
self.np.lyrics_source = source.clone();
|
|
let pos = self.player.pos();
|
|
self.hero.lyrics.set_position(pos);
|
|
}
|
|
}
|
|
}
|
|
Msg::ArtistInfo { artist, text } => self.hero.on_info(&artist, &text),
|
|
Msg::Toast(s) => self.toast(s),
|
|
Msg::Done { toast } => self.toast(toast),
|
|
Msg::Decoded { token, samples, done } => self.spectrum.on_decoded(token, samples, done),
|
|
Msg::Added { job, songs } => self.finish_add(job, songs),
|
|
Msg::Resolved { token, result } => match result {
|
|
Ok(r) => {
|
|
let paused = false;
|
|
self.player.resolved(&mut self.mgr, &r, token, 0.0, paused);
|
|
self.drain_notes();
|
|
}
|
|
Err(e) => {
|
|
if token == self.player.resolve_token() {
|
|
self.toast(format!("Couldn't open that link: {e}"));
|
|
self.player.song_ended_stop(&mut self.mgr);
|
|
self.drain_notes();
|
|
}
|
|
}
|
|
},
|
|
Msg::TagsWritten(done) => self.on_tags_written(*done),
|
|
Msg::Engine(id, ev) => {
|
|
self.player.on_engine(&mut self.mgr, &self.lib, id, ev);
|
|
self.drain_notes();
|
|
}
|
|
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));
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
|
}
|
|
Msg::OpenArgs(args) => {
|
|
self.handle_args(args);
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
|
}
|
|
Msg::CoverCandidates { token, items } => crate::ui::dialogs::on_cover_candidates(self, token, items),
|
|
Msg::CoverThumb { token, idx, image } => crate::ui::dialogs::on_cover_thumb(self, token, idx, image),
|
|
Msg::CoverFull { token, bytes } => crate::ui::dialogs::on_cover_full(self, token, bytes),
|
|
Msg::MbResults { token, items } => crate::ui::dialogs::on_mb_results(self, token, items),
|
|
Msg::ConnectLastFm(r) => crate::ui::dialogs::on_lastfm_connected(self, r),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_art_changed(&mut self, accent: Option<Color32>) {
|
|
self.hero.bg_dirty = true;
|
|
match settings().get_str("appearance/color_source").as_str() {
|
|
"album" => {
|
|
if accent != self.album_seed {
|
|
self.album_seed = accent;
|
|
self.rebuild_theme();
|
|
}
|
|
}
|
|
_ => self.album_seed = accent,
|
|
}
|
|
if let Some(m) = &self.mpris {
|
|
m.notify_changed();
|
|
}
|
|
}
|
|
|
|
/// Window and tray icon follow the accent colour.
|
|
pub fn apply_icon(&mut self) {
|
|
let t = &self.g.theme;
|
|
let rgba = util::themed_icon(t.primary, t.on_primary, 256);
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Icon(Some(Arc::new(egui::IconData { rgba, width: 256, height: 256 }))));
|
|
if let Some(tray) = &self.tray {
|
|
tray.set_icon(util::themed_icon(t.primary, t.on_primary, 64));
|
|
}
|
|
}
|
|
|
|
pub fn rebuild_theme(&mut self) {
|
|
let t = Theme::build(self.album_seed);
|
|
if !t.same_colors(&self.g.theme) || t.surface_container != self.g.theme.surface_container {
|
|
apply_visuals(&self.ctx, &t);
|
|
self.g.theme = t;
|
|
self.apply_icon();
|
|
self.hero.bg_dirty = true;
|
|
}
|
|
}
|
|
|
|
fn drain_notes(&mut self) {
|
|
let notes: Vec<Note> = std::mem::take(&mut self.player.notes);
|
|
for n in notes {
|
|
match n {
|
|
Note::SongChanged => self.on_song_changed(),
|
|
Note::StateChanged(st) => {
|
|
self.spectrum.set_playing(st == "playing");
|
|
self.hero.on_state(&st);
|
|
if let Some(t) = &self.tray {
|
|
t.set_playing(st == "playing");
|
|
}
|
|
if let Some(m) = &self.mpris {
|
|
m.notify_changed();
|
|
}
|
|
if st == "stopped" && self.player.song.is_none() {
|
|
self.set_title(APP_NAME.to_string());
|
|
}
|
|
}
|
|
Note::TrackStarted(s) => self.scrobbler.track_started(&s),
|
|
Note::TrackFinished { song, listened, start_ts } => self.scrobbler.track_finished(&song, listened, start_ts),
|
|
Note::Message(m) => self.toast(m),
|
|
Note::VolumeChanged(_) => {
|
|
if let Some(m) = &self.mpris {
|
|
m.notify_changed();
|
|
}
|
|
}
|
|
Note::Seeked(sec) => {
|
|
self.hero.lyrics.set_position(sec);
|
|
self.spectrum.set_position(sec);
|
|
if let Some(m) = &self.mpris {
|
|
m.seeked(sec);
|
|
}
|
|
}
|
|
Note::NeedResolve(song) => {
|
|
let (bus, token) = (self.bus.clone(), self.player.resolve_token());
|
|
std::thread::spawn(move || {
|
|
let result = crate::online::resolve_stream(&song.url);
|
|
bus.send(Msg::Resolved { token, result });
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_song_changed(&mut self) {
|
|
let Some(s) = self.player.song.clone() else { return };
|
|
self.np.on_song(&s);
|
|
let path = if s.is_local() && !s.is_cd() { Some(s.path()) } else { None };
|
|
self.spectrum.set_track(path.as_deref(), s.begin, s.duration());
|
|
self.hero.on_song(&s);
|
|
let title = if s.is_stream() && !s.stream_title.is_empty() { s.stream_title.clone() } else { s.display_title() };
|
|
let artist = s.display_artist();
|
|
self.set_title(if artist.is_empty() { format!("{title} — {APP_NAME}") } else { format!("{artist} - {title} — {APP_NAME}") });
|
|
if let Some(r) = self.player.song_ref {
|
|
if self.mgr.active == Some(r.0) {
|
|
self.area.scroll_request = Some(r);
|
|
}
|
|
}
|
|
self.notify_due = Some(Instant::now() + Duration::from_millis(700));
|
|
if let Some(m) = &self.mpris {
|
|
m.notify_changed();
|
|
}
|
|
if self.mgr.stop_after.map(|sa| Some(sa.1) != self.player.song_ref.map(|r| r.1)).unwrap_or(false) {
|
|
// stop-after targeted another song: keep it
|
|
}
|
|
}
|
|
|
|
fn set_title(&mut self, t: String) {
|
|
if t != self.title_cache {
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Title(t.clone()));
|
|
self.title_cache = t;
|
|
}
|
|
}
|
|
|
|
fn maybe_notify(&mut self) {
|
|
let Some(due) = self.notify_due else { return };
|
|
if Instant::now() < due {
|
|
return;
|
|
}
|
|
self.notify_due = None;
|
|
if !settings().get_bool("appearance/notifications") {
|
|
return;
|
|
}
|
|
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;
|
|
}
|
|
let title = if s.stream_title.is_empty() { s.display_title() } else { s.stream_title.clone() };
|
|
let body = [s.display_artist(), s.album.clone()].into_iter().filter(|x| !x.is_empty()).collect::<Vec<_>>().join(" — ");
|
|
let art = self.np.art_path.clone();
|
|
std::thread::spawn(move || {
|
|
let mut cmd = std::process::Command::new("notify-send");
|
|
cmd.args(["-a", "Mulberry", "-t", "4000", "-h", "string:x-canonical-private-synchronous:mulberry"]);
|
|
if !art.is_empty() {
|
|
cmd.args(["-i", &art]);
|
|
}
|
|
let _ = cmd.arg(title).arg(body).status();
|
|
});
|
|
}
|
|
|
|
pub fn toast(&mut self, s: impl Into<String>) {
|
|
let s = s.into();
|
|
if !s.is_empty() {
|
|
self.toast = Some((s, Instant::now()));
|
|
}
|
|
}
|
|
|
|
// ================================================================ actions
|
|
pub fn play_ref(&mut self, r: Ref) {
|
|
self.player.play_song(&mut self.mgr, &self.lib, r, 0.0, false);
|
|
self.drain_notes();
|
|
}
|
|
|
|
pub fn play_pause(&mut self) {
|
|
self.player.play_pause(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
}
|
|
pub fn next(&mut self) {
|
|
self.player.next(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
}
|
|
pub fn prev(&mut self) {
|
|
self.player.prev(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
}
|
|
pub fn stop(&mut self) {
|
|
self.player.stop(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
}
|
|
pub fn seek(&mut self, sec: f64) {
|
|
self.player.seek(sec);
|
|
self.drain_notes();
|
|
}
|
|
pub fn refresh_next(&mut self) {
|
|
self.player.refresh_next(&mut self.mgr);
|
|
}
|
|
|
|
pub fn resume_playback(&mut self) {
|
|
if !settings().get_bool("playback/resume") {
|
|
return;
|
|
}
|
|
let Some(pl) = self.mgr.active.and_then(|a| self.mgr.pl(a)) else { return };
|
|
let Some(cur) = pl.current else { return };
|
|
let Some(song) = pl.entry(cur).map(|e| e.song.clone()) else { return };
|
|
if song.is_stream() {
|
|
return;
|
|
}
|
|
let pos: f64 = self.lib.kv("resume_pos").and_then(|v| v.parse().ok()).unwrap_or(0.0);
|
|
let r = (pl.uid, cur);
|
|
self.player.play_song(&mut self.mgr, &self.lib, r, pos, true);
|
|
self.drain_notes();
|
|
self.pending_resume = false;
|
|
}
|
|
|
|
pub fn add_songs(&mut self, songs: Vec<Song>, mode: AddMode) {
|
|
if songs.is_empty() {
|
|
return;
|
|
}
|
|
let cur = self.mgr.current;
|
|
match mode {
|
|
AddMode::New => {
|
|
let name = if !songs[0].album.is_empty() { songs[0].album.clone() } else if !songs[0].display_artist().is_empty() { songs[0].display_artist() } else { "Playlist".into() };
|
|
let pl = self.mgr.new_playlist(&self.lib, Some(&name), vec![], true);
|
|
let uids = self.mgr.pl_mut(pl).unwrap().insert_songs(songs, None);
|
|
if let Some(u) = uids.first() {
|
|
self.play_ref((pl, *u));
|
|
}
|
|
}
|
|
AddMode::Replace => {
|
|
let pl = self.mgr.current_mut();
|
|
pl.replace(songs);
|
|
if let Some(e) = pl.entries.first() {
|
|
let r = (cur, e.uid);
|
|
self.play_ref(r);
|
|
}
|
|
}
|
|
AddMode::Play => {
|
|
let uids = self.mgr.current_mut().insert_songs(songs, None);
|
|
if let Some(u) = uids.first() {
|
|
self.play_ref((cur, *u));
|
|
}
|
|
}
|
|
AddMode::Queue => {
|
|
let uids = self.mgr.current_mut().insert_songs(songs, None);
|
|
self.mgr.enqueue(cur, &uids, false);
|
|
self.refresh_next();
|
|
}
|
|
AddMode::Next => {
|
|
let pl = self.mgr.current_mut();
|
|
let row = pl.current_row().map(|r| r + 1);
|
|
let uids = pl.insert_songs(songs, row);
|
|
self.mgr.enqueue(cur, &uids, true);
|
|
self.refresh_next();
|
|
}
|
|
AddMode::Append => {
|
|
self.mgr.current_mut().insert_songs(songs, None);
|
|
}
|
|
}
|
|
self.mgr.touch();
|
|
}
|
|
|
|
pub fn add_paths(&mut self, paths: Vec<String>, mode: AddMode) {
|
|
let mut pl = self.mgr.current;
|
|
let mut job = AddJob { pl, row: None, play: false, replace: false };
|
|
match mode {
|
|
AddMode::New => {
|
|
let name = std::path::Path::new(paths[0].trim_end_matches('/')).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "Playlist".into());
|
|
pl = self.mgr.new_playlist(&self.lib, Some(&name), vec![], true);
|
|
job = AddJob { pl, row: None, play: true, replace: false };
|
|
}
|
|
AddMode::Replace => job = AddJob { pl, row: None, play: true, replace: true },
|
|
AddMode::Play => job.play = true,
|
|
_ => {}
|
|
}
|
|
self.start_add(paths, job);
|
|
}
|
|
|
|
pub fn start_add(&mut self, paths: Vec<String>, job: AddJob) {
|
|
let (lib, bus) = (self.lib.clone(), self.bus.clone());
|
|
self.toast("Adding files…");
|
|
std::thread::spawn(move || {
|
|
let mut out: Vec<Song> = vec![];
|
|
let mut plain: Vec<String> = vec![];
|
|
for p in paths {
|
|
let ext = crate::config::ext_of(&p);
|
|
if crate::config::PLAYLIST_EXTS.contains(&ext.as_str()) && std::path::Path::new(&p).is_file() {
|
|
if !plain.is_empty() {
|
|
out.extend(crate::library::scan_paths(&lib, &std::mem::take(&mut plain)));
|
|
}
|
|
out.extend(playlistio::enrich(&lib, playlistio::import_playlist(&p)));
|
|
} else if p.contains("://") && !p.starts_with("file://") {
|
|
let mut s = Song::new(p.clone());
|
|
s.title = p.clone();
|
|
s.filetype = "Stream".into();
|
|
out.push(s);
|
|
} else {
|
|
plain.push(p.strip_prefix("file://").map(crate::song::percent_decode).unwrap_or(p));
|
|
}
|
|
}
|
|
if !plain.is_empty() {
|
|
out.extend(crate::library::scan_paths(&lib, &plain));
|
|
}
|
|
bus.send(Msg::Added { job, songs: out });
|
|
});
|
|
}
|
|
|
|
fn finish_add(&mut self, job: AddJob, songs: Vec<Song>) {
|
|
let Some(pl) = self.mgr.pl_mut(job.pl) else { return };
|
|
let first = if job.replace {
|
|
pl.replace(songs);
|
|
pl.entries.first().map(|e| e.uid)
|
|
} else {
|
|
pl.insert_songs(songs, job.row).first().copied()
|
|
};
|
|
if job.play {
|
|
if let Some(u) = first {
|
|
self.mgr.set_current(job.pl);
|
|
self.play_ref((job.pl, u));
|
|
}
|
|
}
|
|
self.mgr.touch();
|
|
}
|
|
|
|
pub fn handle_args(&mut self, args: Vec<String>) {
|
|
let paths: Vec<String> = args.into_iter().filter(|a| std::path::Path::new(a).exists() || a.contains("://")).collect();
|
|
if !paths.is_empty() {
|
|
self.add_paths(paths, AddMode::Play);
|
|
}
|
|
}
|
|
|
|
pub fn toggle_queue(&mut self, pl: u64, uids: &[u64]) {
|
|
if uids.iter().all(|u| self.mgr.is_queued(*u)) {
|
|
for u in uids {
|
|
self.mgr.dequeue(*u);
|
|
}
|
|
} else {
|
|
let fresh: Vec<u64> = uids.iter().copied().filter(|u| !self.mgr.is_queued(*u)).collect();
|
|
self.mgr.enqueue(pl, &fresh, false);
|
|
}
|
|
self.refresh_next();
|
|
}
|
|
|
|
// ================================================================ tag editing
|
|
/// Write `values` to the files of `songs` on a worker thread; the UI updates when it finishes.
|
|
pub fn write_tags(&mut self, songs: Vec<Song>, per_song: Vec<Vec<(Field, String)>>, label: String, is_undo: bool) {
|
|
let (lib, bus) = (self.lib.clone(), self.bus.clone());
|
|
// never write to the file that is currently playing mid-stream without stopping the user: fine for mpv
|
|
std::thread::spawn(move || {
|
|
let mut done = TagsDone { ok: vec![], errors: vec![], label, is_undo };
|
|
for (song, values) in songs.into_iter().zip(per_song) {
|
|
let old: Vec<(Field, String)> = values.iter().map(|(f, _)| (*f, f.get(&song))).collect();
|
|
match crate::tags::write_tags(&song.path(), &values) {
|
|
Ok(()) => {
|
|
let new = lib.reread(&song.path(), &song).or_else(|| crate::tags::read_song(&song.path()).map(|mut s| {
|
|
s.art = song.art.clone();
|
|
s
|
|
}));
|
|
match new {
|
|
Some(mut n) => {
|
|
n.art = if n.art.is_empty() { song.art.clone() } else { n.art };
|
|
done.ok.push((song, n, old));
|
|
}
|
|
None => done.errors.push(format!("{}: couldn't re-read tags", song.display_title())),
|
|
}
|
|
}
|
|
Err(e) => done.errors.push(format!("{}: {e}", song.display_title())),
|
|
}
|
|
}
|
|
bus.send(Msg::TagsWritten(Box::new(done)));
|
|
});
|
|
}
|
|
|
|
/// "Set <field> to <value>" on every selected song, written to the files instantly.
|
|
pub fn set_field_for(&mut self, songs: &[Song], field: Field, value: &str) {
|
|
let local: Vec<Song> = songs.iter().filter(|s| s.is_local() && std::path::Path::new(&s.path()).exists()).cloned().collect();
|
|
if local.is_empty() {
|
|
return;
|
|
}
|
|
let per: Vec<Vec<(Field, String)>> = local.iter().map(|_| vec![(field, value.to_string())]).collect();
|
|
let shown: String = value.chars().take(40).collect();
|
|
let n = local.len();
|
|
let label = format!("Set {} to “{shown}” on {n} track{}", field.label(), if n == 1 { "" } else { "s" });
|
|
self.write_tags(local, per, label, false);
|
|
}
|
|
|
|
fn on_tags_written(&mut self, d: TagsDone) {
|
|
let mut undo_items = vec![];
|
|
for (old, new, old_vals) in &d.ok {
|
|
for pl in &mut self.mgr.playlists {
|
|
pl.refresh_song(new);
|
|
}
|
|
if let Some(cur) = &mut self.player.song {
|
|
if cur.same_as(old) {
|
|
let keep = (cur.stream_title.clone(), cur.resolved.clone(), cur.resolved_at);
|
|
*cur = new.clone();
|
|
cur.stream_title = keep.0;
|
|
cur.resolved = keep.1;
|
|
cur.resolved_at = keep.2;
|
|
let s = cur.clone();
|
|
self.np.song = Some(s.clone());
|
|
self.hero.on_song(&s);
|
|
self.np.load_art(&s, false);
|
|
}
|
|
}
|
|
undo_items.push((new.clone(), old_vals.clone()));
|
|
}
|
|
self.mgr.touch();
|
|
self.side.library_dirty = true;
|
|
if let Some(e) = d.errors.first() {
|
|
self.toast(format!("Tag write failed — {e}"));
|
|
} else if d.is_undo {
|
|
self.toast("Undid tag change");
|
|
self.tag_undo = None;
|
|
} else {
|
|
self.toast(d.label.clone());
|
|
if !undo_items.is_empty() {
|
|
self.tag_undo = Some(TagUndo { items: undo_items, label: d.label, at: Instant::now() });
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn undo_tags(&mut self) {
|
|
let Some(u) = self.tag_undo.take() else { return };
|
|
let (songs, per): (Vec<Song>, Vec<Vec<(Field, String)>>) = u.items.into_iter().unzip();
|
|
self.write_tags(songs, per, "Undo".into(), true);
|
|
}
|
|
|
|
// ================================================================ MPRIS
|
|
fn on_mpris(&mut self, cmd: MprisCmd) {
|
|
match cmd {
|
|
MprisCmd::Play => {
|
|
self.player.play(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
}
|
|
MprisCmd::Pause => self.player.pause(),
|
|
MprisCmd::PlayPause => self.play_pause(),
|
|
MprisCmd::Stop => self.stop(),
|
|
MprisCmd::Next => self.next(),
|
|
MprisCmd::Prev => self.prev(),
|
|
MprisCmd::Seek(d) => {
|
|
self.player.seek_relative(d);
|
|
self.drain_notes();
|
|
}
|
|
MprisCmd::SetPos(p) => self.seek(p),
|
|
MprisCmd::SetVolume(v) => {
|
|
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::Quit => self.quit(),
|
|
MprisCmd::SetShuffle(b) => {
|
|
self.mgr.set_shuffle(b);
|
|
self.refresh_next();
|
|
}
|
|
MprisCmd::SetLoop(m) => {
|
|
self.mgr.set_repeat(match m.as_str() {
|
|
"Track" => "track",
|
|
"Playlist" => "playlist",
|
|
_ => "off",
|
|
});
|
|
self.refresh_next();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn publish_mpris(&mut self) {
|
|
let Some(m) = &self.mpris else { return };
|
|
if let Some(s) = &self.player.song {
|
|
let _ = s;
|
|
m.set_position(self.player.clock_peek());
|
|
}
|
|
if !m.take_dirty() {
|
|
return;
|
|
}
|
|
let s = self.player.song.clone();
|
|
let mut snap = crate::mpris::Snapshot {
|
|
status: match self.player.state.as_str() { "playing" => "Playing", "paused" => "Paused", _ => "Stopped" }.into(),
|
|
loop_status: match self.mgr.repeat.as_str() { "track" => "Track", "playlist" => "Playlist", _ => "None" }.into(),
|
|
shuffle: self.mgr.shuffle,
|
|
volume: self.player.volume as f64 / 100.0,
|
|
can_seek: s.as_ref().map(|s| !s.is_stream()).unwrap_or(false),
|
|
..Default::default()
|
|
};
|
|
if let Some(s) = s {
|
|
let (mut title, mut artist) = (s.display_title(), s.display_artist());
|
|
if s.is_stream() {
|
|
if let Some((a, t)) = s.stream_title.split_once(" - ") {
|
|
artist = a.trim().into();
|
|
title = t.trim().into();
|
|
} else {
|
|
title = if s.stream_title.is_empty() { if s.title.is_empty() { s.url.clone() } else { s.title.clone() } } else { s.stream_title.clone() };
|
|
if artist.is_empty() {
|
|
artist = s.title.clone();
|
|
}
|
|
}
|
|
}
|
|
let key = s.key();
|
|
let hash = key.bytes().fold(5381u64, |h, b| h.wrapping_mul(33) ^ b as u64) % 1_000_000_000_000;
|
|
snap.has_song = true;
|
|
snap.track_id = format!("/org/mulberry/track/{hash}");
|
|
snap.title = title;
|
|
snap.artists = if artist.is_empty() { vec![] } else { vec![artist] };
|
|
snap.album = s.album.clone();
|
|
snap.album_artist = s.effective_albumartist();
|
|
snap.genre = s.genre.clone();
|
|
snap.track = s.track;
|
|
snap.disc = s.disc;
|
|
snap.length_us = (self.player.dur.max(s.duration()) * 1e6) as i64;
|
|
snap.url = if s.is_local() && std::path::Path::new(&s.path()).is_absolute() { format!("file://{}", urlencoding::encode(&s.path()).replace("%2F", "/")) } else { s.url.clone() };
|
|
let art = if !self.np.art_path.is_empty() { self.np.art_path.clone() } else { s.art.clone() };
|
|
if !art.is_empty() && std::path::Path::new(&art).exists() {
|
|
snap.art_url = format!("file://{}", urlencoding::encode(&art).replace("%2F", "/"));
|
|
}
|
|
snap.year = s.year;
|
|
snap.use_count = s.playcount;
|
|
snap.rating = s.rating as f64 / 5.0;
|
|
}
|
|
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;
|
|
}
|
|
self.quitting = 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.lib.stop_scan();
|
|
self.player.shutdown();
|
|
self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
|
// never hang on exit (mpv/D-Bus threads): leave for sure shortly after the window closes
|
|
std::thread::spawn(|| {
|
|
std::thread::sleep(Duration::from_millis(1200));
|
|
std::process::exit(0);
|
|
});
|
|
}
|
|
|
|
// ================================================================ frame
|
|
fn check_theme(&mut self) {
|
|
if self.last_theme_check.elapsed() < Duration::from_secs(2) {
|
|
return;
|
|
}
|
|
self.last_theme_check = Instant::now();
|
|
let m = crate::theme::system_mtime();
|
|
if m != self.sys_mtime {
|
|
self.sys_mtime = m;
|
|
self.rebuild_theme();
|
|
}
|
|
}
|
|
|
|
fn shortcuts(&mut self, ctx: &egui::Context) {
|
|
use egui::{Key, Modifiers};
|
|
let typing = ctx.egui_wants_keyboard_input();
|
|
let mut act: Option<&str> = None;
|
|
ctx.input_mut(|i| {
|
|
let c = Modifiers::COMMAND;
|
|
let cs = Modifiers::COMMAND | Modifiers::SHIFT;
|
|
if i.consume_key(Modifiers::NONE, Key::F11) { act = Some("focus"); }
|
|
if !typing && i.consume_key(c, Key::ArrowRight) { act = Some("next"); }
|
|
if !typing && i.consume_key(c, Key::ArrowLeft) { act = Some("prev"); }
|
|
if !typing && i.consume_key(Modifiers::ALT, Key::ArrowRight) { act = Some("seek+"); }
|
|
if !typing && i.consume_key(Modifiers::ALT, Key::ArrowLeft) { act = Some("seek-"); }
|
|
if !typing && i.consume_key(c, Key::ArrowUp) { act = Some("vol+"); }
|
|
if !typing && i.consume_key(c, Key::ArrowDown) { act = Some("vol-"); }
|
|
if !typing && i.consume_key(c, Key::M) { act = Some("mute"); }
|
|
if !typing && i.consume_key(c, Key::T) { act = Some("newpl"); }
|
|
if !typing && i.consume_key(c, Key::W) { act = Some("closepl"); }
|
|
if !typing && i.consume_key(c, Key::J) { act = Some("jump"); }
|
|
if !typing && i.consume_key(c, Key::D) { act = Some("queue"); }
|
|
if !typing && i.consume_key(c, Key::E) { act = Some("tags"); }
|
|
if i.consume_key(c, Key::F) { act = Some("filter"); }
|
|
if !typing && i.consume_key(c, Key::L) { act = Some("love"); }
|
|
if !typing && i.consume_key(c, Key::U) { act = Some("url"); }
|
|
if !typing && i.consume_key(cs, Key::Z) { act = Some("redo"); }
|
|
else if !typing && i.consume_key(c, Key::Z) { act = Some("undo"); }
|
|
if i.consume_key(cs, Key::S) { act = Some("export_all"); }
|
|
else if i.consume_key(c, Key::S) { act = Some("export"); }
|
|
if !typing && i.consume_key(c, Key::H) { act = Some("toggle_shuffle"); }
|
|
// egui-winit turns Ctrl+V into Event::Paste(text); files copied in a file manager arrive as file:// lines
|
|
if !typing && i.events.iter().any(|e| matches!(e, egui::Event::Paste(t) if t.lines().next().is_some_and(|l| l.starts_with("file://")))) { act = Some("paste_files"); }
|
|
if i.consume_key(cs, Key::O) { act = Some("open_folder"); }
|
|
else if i.consume_key(c, Key::O) { act = Some("open"); }
|
|
if i.consume_key(Modifiers::COMMAND | Modifiers::ALT, Key::V) { act = Some("stop_after"); }
|
|
if i.consume_key(c, Key::I) { act = Some("import"); }
|
|
if i.consume_key(c, Key::Q) { act = Some("quit"); }
|
|
if i.consume_key(c, Key::Comma) { act = Some("settings"); }
|
|
if i.consume_key(c, Key::B) { act = Some("sidebar"); }
|
|
if i.consume_key(Modifiers::NONE, Key::F5) { act = Some("scan"); }
|
|
if i.consume_key(Modifiers::CTRL, Key::F5) { act = Some("fullscan"); }
|
|
if !typing && i.consume_key(Modifiers::NONE, Key::Space) { act = Some("pp"); }
|
|
if !typing && i.consume_key(c, Key::A) { act = Some("selall"); }
|
|
});
|
|
if let Some(a) = act {
|
|
self.do_action(a);
|
|
}
|
|
// media keys
|
|
let media: Vec<egui::Event> = ctx.input(|i| i.events.clone());
|
|
let _ = media;
|
|
}
|
|
|
|
pub fn do_action(&mut self, a: &str) {
|
|
match a {
|
|
"pp" => self.play_pause(),
|
|
"next" => self.next(),
|
|
"prev" => self.prev(),
|
|
"stop" => self.stop(),
|
|
"seek+" => { self.player.seek_relative(10.0); self.drain_notes(); }
|
|
"seek-" => { self.player.seek_relative(-10.0); self.drain_notes(); }
|
|
"vol+" => { let v = self.player.volume + 5; self.player.set_volume(v); self.drain_notes(); }
|
|
"vol-" => { let v = self.player.volume - 5; self.player.set_volume(v); self.drain_notes(); }
|
|
"mute" => { self.player.toggle_mute(); self.drain_notes(); }
|
|
"focus" => self.focus_mode = !self.focus_mode,
|
|
"newpl" => { self.mgr.new_playlist(&self.lib, None, vec![], true); }
|
|
"closepl" => { let u = self.mgr.current; self.mgr.close_playlist(&self.lib, u, None); }
|
|
"jump" => self.area.jump_to_current(&mut self.mgr),
|
|
"queue" => {
|
|
let cur = self.mgr.current;
|
|
let sel: Vec<u64> = self.mgr.current_pl().entries.iter().filter(|e| self.mgr.current_pl().view.selected.contains(&e.uid)).map(|e| e.uid).collect();
|
|
if !sel.is_empty() { self.toggle_queue(cur, &sel); }
|
|
}
|
|
"tags" => {
|
|
let songs = self.selected_or_current();
|
|
let local: Vec<Song> = songs.into_iter().filter(|s| s.is_local()).collect();
|
|
if !local.is_empty() { self.dialog = Some(Dialog::tags(local)); }
|
|
}
|
|
"filter" => self.area.focus_filter = true,
|
|
"love" => self.hero.toggle_love_request = true,
|
|
"url" => self.dialog = Some(Dialog::prompt("Open URL", "Internet radio stream, or a YouTube / SoundCloud / Bandcamp link:", "", "open_url")),
|
|
"open" => crate::ui::menus::open_files(self),
|
|
"undo" => { let c = self.mgr.current_mut(); c.undo(); self.mgr.touch(); }
|
|
"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.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()),
|
|
"fullscan" => self.lib.scan(true, self.bus.clone()),
|
|
"open_folder" => crate::ui::menus::pick(self, "open_folder", crate::ui::menus::Pick::Folder),
|
|
"add_library_folder" => crate::ui::menus::pick(self, "add_library_folder", crate::ui::menus::Pick::Folder),
|
|
"open_cd" => {
|
|
self.side.tab = 4;
|
|
settings().set("ui/sidebar_tab", 4i64);
|
|
self.show_sidebar = true;
|
|
let bus = self.bus.clone();
|
|
self.side.cd.maybe_read(&bus);
|
|
}
|
|
"stop_after" => {
|
|
self.mgr.stop_after = match (self.mgr.stop_after, self.player.song_ref) {
|
|
(Some(s), Some(r)) if s.1 == r.1 => None,
|
|
(_, r) => r,
|
|
};
|
|
self.refresh_next();
|
|
}
|
|
"export_all" => self.dialog = Some(Dialog::export_all()),
|
|
"clear_queue" => {
|
|
self.mgr.clear_queue();
|
|
self.refresh_next();
|
|
}
|
|
"shuffle_order" => { self.mgr.current_mut().shuffle_items(); self.mgr.touch(); }
|
|
"remove_dups" => { self.mgr.current_mut().remove_duplicates(); self.mgr.touch(); }
|
|
"remove_unavail" => { self.mgr.current_mut().remove_unavailable(); self.mgr.touch(); }
|
|
"clear_playlist" => { self.mgr.current_mut().clear(); self.mgr.touch(); }
|
|
"toggle_shuffle" => {
|
|
let on = !self.mgr.shuffle;
|
|
self.mgr.set_shuffle(on);
|
|
self.refresh_next();
|
|
}
|
|
"fetch_mb" => {
|
|
let local: Vec<Song> = self.selected_or_current().into_iter().filter(|s| s.is_local()).collect();
|
|
if local.len() > 1 {
|
|
self.dialog = Some(Dialog::tags(local));
|
|
} else if let Some(s) = local.into_iter().next() {
|
|
self.dialog = Some(Dialog::musicbrainz(&self.bus.clone(), s));
|
|
}
|
|
}
|
|
"cover" => {
|
|
if let Some(s) = self.selected_or_current().into_iter().next() {
|
|
self.dialog = Some(Dialog::cover(&self.bus.clone(), s));
|
|
}
|
|
}
|
|
"equalizer" => self.dialog = Some(Dialog::Equalizer),
|
|
"analyzer" => { let v = !settings().get_bool("appearance/analyzer"); settings().set("appearance/analyzer", v); }
|
|
"shape" => { let v = !settings().get_bool("appearance/floating_shape"); settings().set("appearance/floating_shape", v); }
|
|
"shape_morph" => { let App { shape, g, .. } = self; shape.morph_to(g); }
|
|
"about" => self.dialog = Some(Dialog::About),
|
|
"paste_files" => {
|
|
let bus = self.bus.clone();
|
|
std::thread::spawn(move || {
|
|
let paths = util::clipboard_files();
|
|
if paths.is_empty() {
|
|
bus.toast("No files on the clipboard (copy them in your file manager first)");
|
|
} else {
|
|
bus.send(Msg::Picked { purpose: "paste_files".into(), paths });
|
|
}
|
|
});
|
|
}
|
|
"noop" => {}
|
|
"selall" => {
|
|
let pl = self.mgr.current_mut();
|
|
let all: std::collections::HashSet<u64> = pl.entries.iter().map(|e| e.uid).collect();
|
|
pl.view.selected = all;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
pub fn selected_or_current(&self) -> Vec<Song> {
|
|
let pl = self.mgr.current_pl();
|
|
let sel: Vec<Song> = pl.entries.iter().filter(|e| pl.view.selected.contains(&e.uid)).map(|e| e.song.clone()).collect();
|
|
if !sel.is_empty() {
|
|
return sel;
|
|
}
|
|
self.player.song.clone().into_iter().collect()
|
|
}
|
|
|
|
fn handle_drops(&mut self, ctx: &egui::Context) {
|
|
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
|
|
if dropped.is_empty() {
|
|
return;
|
|
}
|
|
let paths: Vec<String> = dropped.iter().map(|f| f.path().to_string_lossy().into_owned()).filter(|p| !p.is_empty()).collect();
|
|
// files land where they were hovered, like a row being reordered
|
|
let row = self.area.hover_dest.take();
|
|
if !paths.is_empty() {
|
|
let job = AddJob { pl: self.mgr.current, row, play: false, replace: false };
|
|
self.start_add(paths, job);
|
|
}
|
|
}
|
|
|
|
pub fn animating(&self) -> bool {
|
|
self.player.is_playing()
|
|
|| self.player.state == "loading"
|
|
|| self.spectrum.active()
|
|
|| self.hero.lyrics.animating
|
|
|| self.shape.active(&self.spectrum, self.player.is_playing())
|
|
|| self.scan.is_some()
|
|
|| self.toast.is_some()
|
|
}
|
|
}
|
|
|
|
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_f64().clamp(1.0 / 240.0, 1.0 / 20.0);
|
|
self.last_frame = now;
|
|
self.handle_msgs();
|
|
self.handle_drops(ctx);
|
|
self.shortcuts(ctx);
|
|
self.check_theme();
|
|
let _ = self.player.tick(&mut self.mgr, &self.lib);
|
|
self.drain_notes();
|
|
self.mgr.save_if_due(&self.lib);
|
|
if self.player.song.is_some() {
|
|
let p = self.player.pos();
|
|
self.spectrum.set_position(p);
|
|
self.hero.lyrics.set_position(p);
|
|
}
|
|
if self.spectrum.active() {
|
|
if let Some(strength) = self.spectrum.tick(dt) {
|
|
self.shape.on_beat(strength);
|
|
}
|
|
}
|
|
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()));
|
|
}
|
|
if let Some((_, t)) = &self.toast {
|
|
let keep = if self.tag_undo.is_some() { 9 } else { 6 };
|
|
if t.elapsed() > Duration::from_secs(keep) {
|
|
self.toast = None;
|
|
}
|
|
}
|
|
if let Some(u) = &self.tag_undo {
|
|
if u.at.elapsed() > Duration::from_secs(30) {
|
|
self.tag_undo = None;
|
|
}
|
|
}
|
|
if let Some((_, t)) = &self.scan_note {
|
|
if t.elapsed() > Duration::from_secs(6) {
|
|
self.scan_note = None;
|
|
}
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
|
|
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
|
let ctx = ui.ctx().clone();
|
|
crate::ui::layout::draw(self, ui);
|
|
crate::ui::dialogs::show(self, &ctx);
|
|
// frame pacing: only keep repainting while something moves, capped to the animation rate
|
|
let cap = settings().get_i64("appearance/max_fps");
|
|
let hz = if cap > 0 { cap as f64 } else { 60.0 };
|
|
self.fps_cap = hz as u32;
|
|
if self.animating() {
|
|
ctx.request_repaint_after(Duration::from_secs_f64(1.0 / hz));
|
|
} else if self.notify_due.is_some() {
|
|
ctx.request_repaint_after(Duration::from_millis(200));
|
|
}
|
|
}
|
|
|
|
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
|
|
if !self.background {
|
|
self.quit_now();
|
|
}
|
|
}
|
|
}
|
|
|
|
impl App {
|
|
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 {
|
|
settings().set("ui/win_w", r.width() as f64);
|
|
settings().set("ui/win_h", r.height() as f64);
|
|
}
|
|
}
|
|
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.lib.stop_scan();
|
|
self.player.shutdown();
|
|
}
|
|
}
|
|
|
|
pub fn summary_text(app: &App) -> String {
|
|
app.mgr.summary()
|
|
}
|
|
|
|
pub fn pos_text(pos: f64, dur: f64) -> String {
|
|
format!("{} / {}", fmt_time(pos), fmt_time(dur))
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
fn _unused(_: HashMap<u8, u8>) {
|
|
let _ = util::open_url;
|
|
}
|
|
|
|
/// winit cannot hide a window on Wayland, so "close to tray" only works under X11.
|
|
fn is_wayland() -> bool {
|
|
std::env::var_os("WAYLAND_DISPLAY").is_some() && std::env::var("XDG_SESSION_TYPE").map(|v| v != "x11").unwrap_or(true)
|
|
}
|