feat: menu bar mini player while the window is minimised

A monochrome status item with previous, play/pause, next and the track
appears when the window is miniaturised and goes away when it comes back.
The buttons feed the media-key command channel; clicking the track
restores the window. Bumps the version to 0.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yuriy.pandClaude Opus 5.5 committed 2026-10-15 22:38:04 +06:00
1 parent 33c48de638
commit e48219b569
8 files changed
+335 -13

No files matched your search

Generated
+6 -2
View File
@@ -2992,12 +2992,16 @@ dependencies = [
[[package]] [[package]]
name = "musyx" name = "musyx"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"block2 0.6.2",
"directories", "directories",
"iced", "iced",
"iced_test", "iced_test",
"keyring", "keyring",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"open", "open",
"png 0.18.1", "png 0.18.1",
"rand 0.9.5", "rand 0.9.5",
@@ -6625,7 +6629,7 @@ checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5"
[[package]] [[package]]
name = "ym-api" name = "ym-api"
version = "0.1.0" version = "0.2.0"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/ym-api", "crates/musyx"] members = ["crates/ym-api", "crates/musyx"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.2.0"
edition = "2024" edition = "2024"
license = "MIT" license = "MIT"
publish = false publish = false
+6
View File
@@ -21,6 +21,12 @@ directories = "6.0.0"
sys-locale = "0.3.2" sys-locale = "0.3.2"
png = { version = "0.18.1", optional = true } png = { version = "0.18.1", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6.3"
objc2-foundation = "0.3.2"
objc2-app-kit = "0.3.2"
block2 = "0.6.2"
[dev-dependencies] [dev-dependencies]
iced_test = "0.14" iced_test = "0.14"
tokio = { version = "1", features = ["macros", "rt"] } tokio = { version = "1", features = ["macros", "rt"] }
+5
View File
@@ -77,6 +77,8 @@ pub struct App {
settings_dirty: Option<std::time::Instant>, settings_dirty: Option<std::time::Instant>,
/// Media keys and the system's Now Playing widget. /// Media keys and the system's Now Playing widget.
media: crate::media::Media, media: crate::media::Media,
/// The menu bar mini player shown while the window is minimised.
mini_player: crate::menubar::MiniPlayer,
/// A live snapshot run opens this route once signed in. /// A live snapshot run opens this route once signed in.
#[cfg(feature = "snapshot")] #[cfg(feature = "snapshot")]
snapshot_route: Option<Route>, snapshot_route: Option<Route>,
@@ -195,6 +197,7 @@ impl App {
system_mode: Mode::Dark, system_mode: Mode::Dark,
settings_dirty: None, settings_dirty: None,
media: crate::media::Media::new(), media: crate::media::Media::new(),
mini_player: crate::menubar::MiniPlayer::new(),
#[cfg(feature = "snapshot")] #[cfg(feature = "snapshot")]
snapshot_route: None, snapshot_route: None,
}; };
@@ -446,6 +449,7 @@ impl App {
self.nav = Navigator::new(Route::Home); self.nav = Navigator::new(Route::Home);
self.drawer = None; self.drawer = None;
self.player.reset(); self.player.reset();
self.mini_player.update(None, self.player.status());
self.library = Library::default(); self.library = Library::default();
self.pages.clear(); self.pages.clear();
self.discover = Discover::default(); self.discover = Discover::default();
@@ -496,6 +500,7 @@ impl App {
let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit); let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit);
let effects = self.player.update(msg); let effects = self.player.update(msg);
self.media.update(self.player.track(), self.player.status(), self.player.position(), seeked); self.media.update(self.player.track(), self.player.status(), self.player.position(), seeked);
self.mini_player.update(self.player.track(), self.player.status());
if self.player.volume != self.settings.volume { if self.player.volume != self.settings.volume {
self.settings.volume = self.player.volume; self.settings.volume = self.player.volume;
self.settings_dirty = Some(std::time::Instant::now()); self.settings_dirty = Some(std::time::Instant::now());
+1
View File
@@ -284,6 +284,7 @@ pub fn get(english: &str) -> Option<&'static str> {
// Track menu // Track menu
"Next track" => "Следующий трек", "Next track" => "Следующий трек",
"Previous track" => "Предыдущий трек",
"Play next" => "Играть следующим", "Play next" => "Играть следующим",
"Add to queue" => "Добавить в очередь", "Add to queue" => "Добавить в очередь",
"Add to Liked tracks" => "Добавить в «Мне нравится»", "Add to Liked tracks" => "Добавить в «Мне нравится»",
+1
View File
@@ -2,6 +2,7 @@ mod app;
mod covers; mod covers;
mod i18n; mod i18n;
mod media; mod media;
mod menubar;
mod player; mod player;
mod route; mod route;
mod screens; mod screens;
+18 -10
View File
@@ -1,7 +1,7 @@
//! Media keys and the system's Now Playing widget (macOS Control Center, //! Media keys and the system's Now Playing widget (macOS Control Center,
//! Windows media overlay, Linux MPRIS), through `souvlaki`. //! Windows media overlay, Linux MPRIS), through `souvlaki`.
use std::sync::Mutex; use std::sync::{Mutex, OnceLock};
use std::time::Duration; use std::time::Duration;
use iced::Subscription; use iced::Subscription;
@@ -47,6 +47,14 @@ impl Command {
/// The OS calls back on its own thread; this hands commands to the subscription. /// The OS calls back on its own thread; this hands commands to the subscription.
static INBOX: Mutex<Option<UnboundedReceiver<Command>>> = Mutex::new(None); static INBOX: Mutex<Option<UnboundedReceiver<Command>>> = Mutex::new(None);
static OUTBOX: OnceLock<UnboundedSender<Command>> = OnceLock::new();
/// Queues a command as if a media key sent it (the menu bar mini player uses this).
pub fn send(command: Command) {
if let Some(tx) = OUTBOX.get() {
let _ = tx.send(command);
}
}
/// Owns the OS integration. Created on the main thread at startup. /// Owns the OS integration. Created on the main thread at startup.
pub struct Media { pub struct Media {
@@ -58,22 +66,22 @@ pub struct Media {
impl Media { impl Media {
pub fn new() -> Self { pub fn new() -> Self {
let (tx, rx): (UnboundedSender<Command>, _) = unbounded_channel(); let (tx, rx): (UnboundedSender<Command>, _) = unbounded_channel();
if OUTBOX.set(tx).is_ok()
&& let Ok(mut inbox) = INBOX.lock()
{
*inbox = Some(rx);
}
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None }) let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None })
.and_then(|mut c| { .and_then(|mut c| {
c.attach(move |event| { c.attach(|event| {
if let Some(command) = Command::from_event(event) { if let Some(command) = Command::from_event(event) {
let _ = tx.send(command); send(command);
} }
})?; })?;
Ok(c) Ok(c)
}); });
match controls { match controls {
Ok(c) => { Ok(c) => Self { controls: Some(c), shown: None },
if let Ok(mut inbox) = INBOX.lock() {
*inbox = Some(rx);
}
Self { controls: Some(c), shown: None }
}
Err(e) => { Err(e) => {
eprintln!("media controls unavailable: {e:?}"); eprintln!("media controls unavailable: {e:?}");
Self { controls: None, shown: None } Self { controls: None, shown: None }
@@ -125,7 +133,7 @@ fn commands() -> impl Stream<Item = Command> {
iced::stream::channel(16, async |mut output| { iced::stream::channel(16, async |mut output| {
let inbox = INBOX.lock().ok().and_then(|mut i| i.take()); let inbox = INBOX.lock().ok().and_then(|mut i| i.take());
let Some(mut inbox) = inbox else { let Some(mut inbox) = inbox else {
// No OS integration: stay pending rather than ending the subscription. // Already taken by an earlier run: stay pending rather than ending the subscription.
std::future::pending::<()>().await; std::future::pending::<()>().await;
return; return;
}; };
+297
View File
@@ -0,0 +1,297 @@
//! 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<Self> {
track.map(|t| Self {
title: t.full_title(),
artist: t.artist_line(),
playing: matches!(status, Status::Playing | Status::Loading),
})
}
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<NowPlaying>,
}
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<NowPlaying>,
minimised: bool,
bar: Option<Bar>,
/// Kept so the window notifications keep arriving.
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
thread_local! {
static STATE: RefCell<State> = 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<NSNotification>| {
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<NowPlaying>) {
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<NSStatusItem>,
keys: [Retained<NSButton>; 3],
label: Retained<NSTextField>,
/// Receives the clicks; the buttons hold it only weakly.
_target: Retained<Target>,
}
impl Bar {
fn new(mtm: MainThreadMarker) -> Option<Self> {
let item = NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength);
let button = item.button(mtm)?;
let target = Target::new(mtm);
let receiver: &AnyObject = &target;
// 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<NSButton> {
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<Retained<NSImage>> {
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<Self> {
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");
}
}