Files
musyx/crates/musyx/src/media.rs
T
yuriy.pandClaude Opus 5.5 c496275101 fix: attach Windows media controls to the main window
souvlaki panics on Windows without an HWND, which crashed the app at
startup. Wait for the window to open and connect with its raw handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:06:41 +06:00

176 lines
6.4 KiB
Rust

//! Media keys and the system's Now Playing widget (macOS Control Center,
//! Windows media overlay, Linux MPRIS), through `souvlaki`.
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use iced::Subscription;
use iced::futures::{SinkExt, Stream};
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use ym_api::Track;
use crate::covers;
use crate::player::Status;
/// What the media keys asked for, in player terms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
Play,
Pause,
Toggle,
Next,
Previous,
SeekTo(Duration),
SeekBy { forward: bool, by: Duration },
}
/// Without an amount, a seek key jumps this far.
const SEEK_STEP: Duration = Duration::from_secs(10);
impl Command {
fn from_event(event: MediaControlEvent) -> Option<Self> {
use souvlaki::SeekDirection::Forward;
Some(match event {
MediaControlEvent::Play => Command::Play,
MediaControlEvent::Pause | MediaControlEvent::Stop => Command::Pause,
MediaControlEvent::Toggle => Command::Toggle,
MediaControlEvent::Next => Command::Next,
MediaControlEvent::Previous => Command::Previous,
MediaControlEvent::SetPosition(MediaPosition(at)) => Command::SeekTo(at),
MediaControlEvent::Seek(dir) => Command::SeekBy { forward: dir == Forward, by: SEEK_STEP },
MediaControlEvent::SeekBy(dir, by) => Command::SeekBy { forward: dir == Forward, by },
_ => return None,
})
}
}
/// The OS calls back on its own thread; this hands commands to the subscription.
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.
pub struct Media {
controls: Option<MediaControls>,
/// What was last published, so unchanged state isn't sent again.
shown: Option<(String, Status)>,
}
impl Media {
pub fn new() -> Self {
let (tx, rx): (UnboundedSender<Command>, _) = unbounded_channel();
if OUTBOX.set(tx).is_ok()
&& let Ok(mut inbox) = INBOX.lock()
{
*inbox = Some(rx);
}
// Windows ties the controls to a window, so they wait for `attach_window`.
let controls = if cfg!(windows) { None } else { connect(None) };
Self { controls, shown: None }
}
/// Connects the controls to the main window (Windows needs its HWND, from `window::raw_id`).
pub fn attach_window(&mut self, raw_id: u64) {
if cfg!(windows) && self.controls.is_none() {
self.controls = connect(Some(raw_id as *mut std::ffi::c_void));
self.shown = None;
}
}
/// Publishes the track and play state; `force` resends the position after a seek.
pub fn update(&mut self, track: Option<&Track>, status: Status, position: Duration, force: bool) {
let Some(controls) = &mut self.controls else { return };
let Some(track) = track else {
if self.shown.take().is_some() {
let _ = controls.set_playback(MediaPlayback::Stopped);
}
return;
};
let new_track = self.shown.as_ref().is_none_or(|(id, _)| *id != track.id);
let new_status = self.shown.as_ref().is_none_or(|(_, s)| *s != status);
if !new_track && !new_status && !force {
return;
}
if new_track {
let title = track.full_title();
let artist = track.artist_line();
let album = track.album.as_ref().map(|a| a.title.clone());
let cover = track.cover_url(covers::LARGE);
let _ = controls.set_metadata(MediaMetadata {
title: Some(&title),
artist: Some(&artist),
album: album.as_deref(),
cover_url: cover.as_deref(),
duration: Some(track.duration),
});
}
let progress = Some(MediaPosition(position));
let _ = controls.set_playback(match status {
Status::Playing | Status::Loading => MediaPlayback::Playing { progress },
Status::Paused | Status::Ended => MediaPlayback::Paused { progress },
});
self.shown = Some((track.id.clone(), status));
}
}
fn connect(hwnd: Option<*mut std::ffi::c_void>) -> Option<MediaControls> {
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd })
.and_then(|mut c| {
c.attach(|event| {
if let Some(command) = Command::from_event(event) {
send(command);
}
})?;
Ok(c)
});
controls.map_err(|e| eprintln!("media controls unavailable: {e:?}")).ok()
}
pub fn subscription() -> Subscription<Command> {
Subscription::run(commands)
}
fn commands() -> impl Stream<Item = Command> {
iced::stream::channel(16, async |mut output| {
let inbox = INBOX.lock().ok().and_then(|mut i| i.take());
let Some(mut inbox) = inbox else {
// Already taken by an earlier run: stay pending rather than ending the subscription.
std::future::pending::<()>().await;
return;
};
while let Some(command) = inbox.recv().await {
if output.send(command).await.is_err() {
break;
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use souvlaki::SeekDirection;
#[test]
fn os_events_map_to_player_commands() {
assert_eq!(Command::from_event(MediaControlEvent::Toggle), Some(Command::Toggle));
assert_eq!(Command::from_event(MediaControlEvent::Stop), Some(Command::Pause));
assert_eq!(
Command::from_event(MediaControlEvent::SetPosition(MediaPosition(Duration::from_secs(42)))),
Some(Command::SeekTo(Duration::from_secs(42)))
);
assert_eq!(
Command::from_event(MediaControlEvent::Seek(SeekDirection::Backward)),
Some(Command::SeekBy { forward: false, by: SEEK_STEP })
);
assert_eq!(Command::from_event(MediaControlEvent::Raise), None);
}
}