|
| 1 | +use block2::RcBlock; |
| 2 | +use objc2::rc::Retained; |
| 3 | +use objc2::runtime::{AnyClass, AnyObject}; |
| 4 | +use objc2::{class, msg_send}; |
| 5 | +use objc2_foundation::{NSMutableDictionary, NSNumber, NSString}; |
| 6 | +use serde::Deserialize; |
| 7 | +use std::sync::Mutex; |
| 8 | +use tauri::{AppHandle, Emitter}; |
| 9 | + |
| 10 | +const MEDIA_CONTROL_EVENT: &str = "macos-media-control"; |
| 11 | +const COMMAND_SUCCESS: isize = 0; |
| 12 | + |
| 13 | +#[derive(Deserialize)] |
| 14 | +#[serde(rename_all = "camelCase")] |
| 15 | +pub struct MediaSessionUpdate { |
| 16 | + title: Option<String>, |
| 17 | + artist: Option<String>, |
| 18 | + artwork_url: Option<String>, |
| 19 | + status: String, |
| 20 | + duration_sec: Option<f64>, |
| 21 | + position_sec: Option<f64>, |
| 22 | +} |
| 23 | + |
| 24 | +pub struct MacosMediaSession(Mutex<bool>); |
| 25 | + |
| 26 | +unsafe impl Send for MacosMediaSession {} |
| 27 | +unsafe impl Sync for MacosMediaSession {} |
| 28 | + |
| 29 | +#[link(name = "MediaPlayer", kind = "framework")] |
| 30 | +extern "C" { |
| 31 | + static MPMediaItemPropertyTitle: *const NSString; |
| 32 | + static MPMediaItemPropertyArtist: *const NSString; |
| 33 | + static MPMediaItemPropertyPlaybackDuration: *const NSString; |
| 34 | + static MPNowPlayingInfoPropertyElapsedPlaybackTime: *const NSString; |
| 35 | + static MPNowPlayingInfoPropertyPlaybackRate: *const NSString; |
| 36 | +} |
| 37 | + |
| 38 | +impl MacosMediaSession { |
| 39 | + pub fn new() -> Self { |
| 40 | + Self(Mutex::new(false)) |
| 41 | + } |
| 42 | + |
| 43 | + fn ensure_handlers(&self, app: &AppHandle) -> Result<(), String> { |
| 44 | + let mut initialized = self.0.lock().map_err(|error| error.to_string())?; |
| 45 | + if *initialized { |
| 46 | + return Ok(()); |
| 47 | + } |
| 48 | + |
| 49 | + install_remote_command_handler(app, "playCommand", "play")?; |
| 50 | + install_remote_command_handler(app, "pauseCommand", "pause")?; |
| 51 | + install_remote_command_handler(app, "nextTrackCommand", "next")?; |
| 52 | + install_remote_command_handler(app, "previousTrackCommand", "previous")?; |
| 53 | + *initialized = true; |
| 54 | + Ok(()) |
| 55 | + } |
| 56 | + |
| 57 | + fn update(&self, app: &AppHandle, update: MediaSessionUpdate) -> Result<(), String> { |
| 58 | + self.ensure_handlers(app)?; |
| 59 | + set_now_playing_info(update); |
| 60 | + Ok(()) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +fn command_center() -> *mut AnyObject { |
| 65 | + let class: &AnyClass = class!(MPRemoteCommandCenter); |
| 66 | + unsafe { msg_send![class, sharedCommandCenter] } |
| 67 | +} |
| 68 | + |
| 69 | +fn now_playing_info_center() -> *mut AnyObject { |
| 70 | + let class: &AnyClass = class!(MPNowPlayingInfoCenter); |
| 71 | + unsafe { msg_send![class, defaultCenter] } |
| 72 | +} |
| 73 | + |
| 74 | +fn install_remote_command_handler( |
| 75 | + app: &AppHandle, |
| 76 | + command_selector: &str, |
| 77 | + action: &'static str, |
| 78 | +) -> Result<(), String> { |
| 79 | + let center = command_center(); |
| 80 | + if center.is_null() { |
| 81 | + return Err("macOS remote command center unavailable".to_string()); |
| 82 | + } |
| 83 | + |
| 84 | + let command: *mut AnyObject = unsafe { |
| 85 | + match command_selector { |
| 86 | + "playCommand" => msg_send![center, playCommand], |
| 87 | + "pauseCommand" => msg_send![center, pauseCommand], |
| 88 | + "nextTrackCommand" => msg_send![center, nextTrackCommand], |
| 89 | + "previousTrackCommand" => msg_send![center, previousTrackCommand], |
| 90 | + _ => return Err(format!("unsupported macOS media command: {command_selector}")), |
| 91 | + } |
| 92 | + }; |
| 93 | + |
| 94 | + if command.is_null() { |
| 95 | + return Err(format!("macOS media command unavailable: {command_selector}")); |
| 96 | + } |
| 97 | + |
| 98 | + let app = app.clone(); |
| 99 | + let block = RcBlock::new(move |_event: *mut AnyObject| { |
| 100 | + let _ = app.emit(MEDIA_CONTROL_EVENT, action); |
| 101 | + COMMAND_SUCCESS |
| 102 | + }); |
| 103 | + |
| 104 | + unsafe { |
| 105 | + let _: () = msg_send![command, setEnabled: true]; |
| 106 | + let _: *mut AnyObject = msg_send![command, addTargetWithHandler: &*block]; |
| 107 | + } |
| 108 | + |
| 109 | + std::mem::forget(block); |
| 110 | + Ok(()) |
| 111 | +} |
| 112 | + |
| 113 | +fn set_now_playing_info(update: MediaSessionUpdate) { |
| 114 | + let center = now_playing_info_center(); |
| 115 | + if center.is_null() { |
| 116 | + return; |
| 117 | + } |
| 118 | + |
| 119 | + let Some(title) = update.title else { |
| 120 | + let nil_info: *mut AnyObject = std::ptr::null_mut(); |
| 121 | + unsafe { |
| 122 | + let _: () = msg_send![center, setNowPlayingInfo: nil_info]; |
| 123 | + } |
| 124 | + return; |
| 125 | + }; |
| 126 | + |
| 127 | + let info = NSMutableDictionary::<NSString, AnyObject>::dictionaryWithCapacity(6); |
| 128 | + insert_string(&info, unsafe { &*MPMediaItemPropertyTitle }, &title); |
| 129 | + |
| 130 | + if let Some(artist) = update.artist { |
| 131 | + insert_string(&info, unsafe { &*MPMediaItemPropertyArtist }, &artist); |
| 132 | + } |
| 133 | + |
| 134 | + if let Some(duration) = update.duration_sec.filter(|duration| duration.is_finite()) { |
| 135 | + insert_number( |
| 136 | + &info, |
| 137 | + unsafe { &*MPMediaItemPropertyPlaybackDuration }, |
| 138 | + duration.max(0.0), |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + if let Some(position) = update.position_sec.filter(|position| position.is_finite()) { |
| 143 | + insert_number( |
| 144 | + &info, |
| 145 | + unsafe { &*MPNowPlayingInfoPropertyElapsedPlaybackTime }, |
| 146 | + position.max(0.0), |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + let playback_rate = if update.status == "playing" { 1.0 } else { 0.0 }; |
| 151 | + insert_number( |
| 152 | + &info, |
| 153 | + unsafe { &*MPNowPlayingInfoPropertyPlaybackRate }, |
| 154 | + playback_rate, |
| 155 | + ); |
| 156 | + |
| 157 | + let _ = update.artwork_url; |
| 158 | + |
| 159 | + unsafe { |
| 160 | + let _: () = msg_send![center, setNowPlayingInfo: &*info]; |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +fn insert_string( |
| 165 | + info: &NSMutableDictionary<NSString, AnyObject>, |
| 166 | + key: &NSString, |
| 167 | + value: &str, |
| 168 | +) { |
| 169 | + let value = NSString::from_str(value); |
| 170 | + let value: Retained<AnyObject> = value.into(); |
| 171 | + info.insert(key, &value); |
| 172 | +} |
| 173 | + |
| 174 | +fn insert_number( |
| 175 | + info: &NSMutableDictionary<NSString, AnyObject>, |
| 176 | + key: &NSString, |
| 177 | + value: f64, |
| 178 | +) { |
| 179 | + let value = NSNumber::new_f64(value); |
| 180 | + let value: Retained<AnyObject> = value.into(); |
| 181 | + info.insert(key, &value); |
| 182 | +} |
| 183 | + |
| 184 | +#[tauri::command] |
| 185 | +pub fn update_macos_media_session( |
| 186 | + app: AppHandle, |
| 187 | + state: tauri::State<'_, MacosMediaSession>, |
| 188 | + update: MediaSessionUpdate, |
| 189 | +) -> Result<(), String> { |
| 190 | + state.update(&app, update) |
| 191 | +} |
0 commit comments