//! A monochrome mini player in the macOS menu bar, shown while the window is //! minimised: previous, play/pause and next, then the track. Clicking the track //! brings the window back. The glyphs are template SF Symbols and the text uses //! the label colour, so the menu bar tints both to match itself. use ym_api::Track; use crate::player::Status; /// What the menu bar shows, so unchanged state isn't redrawn on every tick. #[derive(Debug, Clone, PartialEq, Eq)] struct NowPlaying { title: String, artist: String, playing: bool, } impl NowPlaying { fn new(track: Option<&Track>, status: Status) -> Option { track.map(|t| Self { title: t.full_title(), artist: t.artist_line(), playing: matches!(status, Status::Playing | Status::Loading), }) } #[cfg(any(target_os = "macos", test))] fn line(&self) -> String { if self.artist.is_empty() { self.title.clone() } else { format!("{} — {}", self.title, self.artist) } } } /// The app's handle on the mini player. Created on the main thread at startup. pub struct MiniPlayer { shown: Option, } impl MiniPlayer { pub fn new() -> Self { #[cfg(target_os = "macos")] mac::install(); Self { shown: None } } /// Hands the mini player the current track and play state. pub fn update(&mut self, track: Option<&Track>, status: Status) { let now = NowPlaying::new(track, status); if now == self.shown { return; } #[cfg(target_os = "macos")] mac::set_now_playing(now.clone()); self.shown = now; } } #[cfg(target_os = "macos")] mod mac { use std::cell::RefCell; use std::ptr::NonNull; use block2::RcBlock; use objc2::rc::Retained; use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel}; use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; use objc2_app_kit::{ NSApplication, NSButton, NSCellImagePosition, NSFont, NSFontWeightRegular, NSImage, NSImageSymbolConfiguration, NSLineBreakMode, NSStatusBar, NSStatusItem, NSTextField, NSVariableStatusItemLength, NSWindowDidDeminiaturizeNotification, NSWindowDidMiniaturizeNotification, }; use objc2_foundation::{NSNotification, NSNotificationCenter, NSObject, NSPoint, NSRect, NSSize, NSString}; use super::NowPlaying; use crate::i18n::tr; use crate::media::{self, Command}; /// Width of each transport button, in points. const KEY: f64 = 22.0; /// Space at the ends and between the buttons and the text. const PAD: f64 = 4.0; /// Longer titles are cut with an ellipsis. const MAX_TEXT: f64 = 220.0; #[derive(Default)] struct State { now: Option, minimised: bool, bar: Option, /// Kept so the window notifications keep arriving. observers: Vec>>, } thread_local! { static STATE: RefCell = RefCell::default(); } /// Watches the window being minimised and restored. Off the main thread /// (in tests) there's no menu bar, so this does nothing. pub fn install() { if MainThreadMarker::new().is_none() { return; } let center = NSNotificationCenter::defaultCenter(); // SAFETY: the notification names are AppKit constants, read on the main thread. let names = unsafe { [(NSWindowDidMiniaturizeNotification, true), (NSWindowDidDeminiaturizeNotification, false)] }; let observers = names.map(|(name, minimised)| { let block = RcBlock::new(move |_: NonNull| { STATE.with_borrow_mut(|s| { s.minimised = minimised; sync(s); }); }); // SAFETY: with no queue, AppKit runs the block on the thread that posts, // which for window notifications is the main thread. unsafe { center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block) } }); STATE.with_borrow_mut(|s| s.observers.extend(observers)); } pub fn set_now_playing(now: Option) { STATE.with_borrow_mut(|s| { s.now = now; sync(s); }); } /// Adds, refreshes or removes the status item to match the state. fn sync(state: &mut State) { let Some(mtm) = MainThreadMarker::new() else { return }; let now = state.now.as_ref().filter(|_| state.minimised); match (now, &state.bar) { (None, Some(_)) => { if let Some(bar) = state.bar.take() { NSStatusBar::systemStatusBar().removeStatusItem(&bar.item); } } (Some(now), None) => state.bar = Bar::new(mtm).inspect(|bar| bar.show(now)), (Some(now), Some(bar)) => bar.show(now), (None, None) => {} } } struct Bar { item: Retained, keys: [Retained; 3], label: Retained, /// Receives the clicks; the buttons hold it only weakly. _target: Retained, } impl Bar { fn new(mtm: MainThreadMarker) -> Option { let item = NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength); let button = item.button(mtm)?; let target = Target::new(mtm); let receiver: &AnyObject = ⌖ // SAFETY: `Target` implements every action named here and outlives the buttons. unsafe { button.setTarget(Some(receiver)); button.setAction(Some(sel!(restore:))); } let keys = [ key("backward.fill", tr("Previous track"), sel!(previous:), receiver, mtm), key("play.fill", tr("Play"), sel!(toggle:), receiver, mtm), key("forward.fill", tr("Next track"), sel!(next:), receiver, mtm), ]; let label = NSTextField::labelWithString(&NSString::new(), mtm); label.setFont(Some(&NSFont::menuBarFontOfSize(0.0))); label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail); for key in &keys { button.addSubview(key); } button.addSubview(&label); Some(Self { item, keys, label, _target: target }) } fn show(&self, now: &NowPlaying) { let (symbol, description) = if now.playing { ("pause.fill", tr("Pause")) } else { ("play.fill", tr("Play")) }; if let Some(image) = symbol_image(symbol, description) { self.keys[1].setImage(Some(&image)); } let line = NSString::from_str(&now.line()); self.label.setStringValue(&line); self.label.sizeToFit(); let height = NSStatusBar::systemStatusBar().thickness(); let mut x = PAD; for key in &self.keys { key.setFrame(NSRect::new(NSPoint::new(x, 0.0), NSSize::new(KEY, height))); x += KEY; } x += PAD; let text = self.label.frame().size; let width = text.width.min(MAX_TEXT).ceil(); self.label.setFrame(NSRect::new( NSPoint::new(x, ((height - text.height) / 2.0).round()), NSSize::new(width, text.height), )); self.item.setLength(x + width + PAD + 2.0); if let Some(button) = self.item.button(MainThreadMarker::from(&*self.label)) { button.setToolTip(Some(&line)); } } } /// A borderless transport button showing one template SF Symbol. fn key(symbol: &str, description: &str, action: Sel, target: &AnyObject, mtm: MainThreadMarker) -> Retained { let button = NSButton::new(mtm); if let Some(image) = symbol_image(symbol, description) { button.setImage(Some(&image)); } button.setBordered(false); button.setImagePosition(NSCellImagePosition::ImageOnly); button.setToolTip(Some(&NSString::from_str(description))); // SAFETY: `target` is the `Target` that implements `action`, kept alive by `Bar`. unsafe { button.setTarget(Some(target)); button.setAction(Some(action)); } button } fn symbol_image(symbol: &str, description: &str) -> Option> { let image = NSImage::imageWithSystemSymbolName_accessibilityDescription( &NSString::from_str(symbol), Some(&NSString::from_str(description)), )?; // SAFETY: an AppKit constant. let weight = unsafe { NSFontWeightRegular }; let config = NSImageSymbolConfiguration::configurationWithPointSize_weight(12.0, weight); let image = image.imageWithSymbolConfiguration(&config).unwrap_or(image); image.setTemplate(true); Some(image) } /// Deminiaturises the app's windows and brings it to the front. fn restore(mtm: MainThreadMarker) { let app = NSApplication::sharedApplication(mtm); for window in app.windows() { if window.isMiniaturized() { window.deminiaturize(None); } } #[allow(deprecated)] // `activate` needs macOS 14. app.activateIgnoringOtherApps(true); } define_class!( // SAFETY: NSObject has no subclassing requirements, and `Target` has no `Drop`. #[unsafe(super(NSObject))] #[thread_kind = MainThreadOnly] #[name = "MusyxMiniPlayerTarget"] struct Target; impl Target { #[unsafe(method(previous:))] fn previous(&self, _sender: Option<&AnyObject>) { media::send(Command::Previous); } #[unsafe(method(toggle:))] fn toggle(&self, _sender: Option<&AnyObject>) { media::send(Command::Toggle); } #[unsafe(method(next:))] fn next(&self, _sender: Option<&AnyObject>) { media::send(Command::Next); } #[unsafe(method(restore:))] fn restore(&self, _sender: Option<&AnyObject>) { restore(self.mtm()); } } ); impl Target { fn new(mtm: MainThreadMarker) -> Retained { let this = Self::alloc(mtm).set_ivars(()); // SAFETY: plain NSObject initialisation. unsafe { msg_send![super(this), init] } } } } #[cfg(test)] mod tests { use super::*; #[test] fn line_joins_title_and_artist() { let now = NowPlaying { title: "Song".into(), artist: "Band".into(), playing: true }; assert_eq!(now.line(), "Song — Band"); let now = NowPlaying { artist: String::new(), ..now }; assert_eq!(now.line(), "Song"); } }