Files
lintunes/lintunes/nowplaying_mac.py
T
trav f21c31940f
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
2026-11-17 22:41:48 -08:00

234 lines
8.5 KiB
Python

"""macOS Now Playing and media keys: the Mac's answer to ``mpris.py``.
``MPNowPlayingInfoCenter`` is what Control Centre's Now Playing tile and
the menu-bar widget read (title, artist, album, length, where the song is
up to, artwork), and ``MPRemoteCommandCenter`` is where the keyboard's
play/pause/next/previous keys, AirPods and the tile's own buttons land.
A Mac sends those keys to whichever app last claimed Now Playing, so this
is the whole of media-key support there; ``MainWindow.eventFilter``'s
in-window keys stay as they are.
pyobjc (``pyobjc-framework-MediaPlayer`` + ``-Cocoa``) is a Mac-only
dependency, imported inside ``setup``: if it is missing the app logs once
and runs without, exactly as Linux does without a session bus.
The command handlers may run on a thread of the system's choosing, so they
only emit ``_command``; the Player is driven from the GUI thread by the
queued slot. The adaptor routes to the same Player methods MPRIS does.
"""
import logging
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import tagging
from lintunes.eventlog import log_control
log = logging.getLogger(__name__)
# The one live instance, so mpris.invalidate_artwork can reach it.
_live = None
# MPRemoteCommandHandlerStatus / MPNowPlayingPlaybackState
STATUS_SUCCESS = 0
STATUS_NO_SUCH_CONTENT = 100
STATE_PLAYING = 1
STATE_PAUSED = 2
STATE_STOPPED = 3
# (MPRemoteCommandCenter accessor, the name the handler emits)
COMMANDS = (
("playCommand", "play"),
("pauseCommand", "pause"),
("togglePlayPauseCommand", "toggle"),
("stopCommand", "stop"),
("nextTrackCommand", "next"),
("previousTrackCommand", "previous"),
("changePlaybackPositionCommand", "seek"),
)
def setup(player, main_window):
"""A live ``MacNowPlaying``, or None when pyobjc isn't installed or the
framework refuses (the app carries on either way)."""
try:
import MediaPlayer # noqa: F401 — pyobjc-framework-MediaPlayer
except Exception as e: # noqa: BLE001 — ImportError, or a broken install
log.info("Now Playing: pyobjc's MediaPlayer isn't available (%s); "
"media keys are off", e)
return None
try:
import AppKit
except Exception: # noqa: BLE001 — artwork is optional
AppKit = None
global _live
try:
_live = MacNowPlaying(player, main_window, MediaPlayer, AppKit)
return _live
except Exception as e: # noqa: BLE001
log.info("Now Playing: couldn't register with the system: %s", e)
return None
class MacNowPlaying(QObject):
"""Mirrors the Player into the system's Now Playing and routes the
remote commands back. ``mp``/``appkit`` are the pyobjc modules, passed
in so tests can hand it fakes."""
_command = pyqtSignal(str, float)
def __init__(self, player, main_window, mp, appkit=None):
super().__init__()
self._player = player
self._window = main_window
self._mp = mp
self._appkit = appkit
self._handlers = [] # keep the Python callables alive
self._art_track = None # whose artwork object we built
self._artwork = None
self._command.connect(self._run)
center = mp.MPRemoteCommandCenter.sharedCommandCenter()
for accessor, name in COMMANDS:
command = getattr(center, accessor, None)
if command is None:
continue
command = command()
handler = self._handler_for(name)
self._handlers.append(handler)
try:
command.setEnabled_(True)
command.addTargetWithHandler_(handler)
except Exception as e: # noqa: BLE001
log.info("Now Playing: %s unavailable: %s", accessor, e)
player.track_changed.connect(lambda _t: self.update())
player.playing_changed.connect(lambda _p: self.update())
# A seek moves the elapsed time; Now Playing extrapolates the rest
# from the rate, so a jump is the only position change it needs.
self._last_pos = 0
player.position_changed.connect(self._on_position)
self.update()
# -- commands (any thread) -> GUI thread --
def _handler_for(self, name):
def handler(event):
seconds = 0.0
if name == "seek":
try:
seconds = float(event.positionTime())
except Exception: # noqa: BLE001
return STATUS_NO_SUCH_CONTENT
self._command.emit(name, seconds)
return STATUS_SUCCESS
return handler
def _run(self, name: str, seconds: float):
log_control("nowplaying", name)
player = self._player
if name == "play":
player.play()
elif name == "pause":
player.pause()
elif name == "toggle":
player.toggle_play()
elif name == "stop":
player.stop()
elif name == "next":
player.next()
elif name == "previous":
player.previous()
elif name == "seek":
player.seek(int(seconds * 1000))
self.update()
# -- Player -> Now Playing --
def _on_position(self, ms):
ms = int(ms)
# Normal playback steps a few hundred ms at a time; only a jump
# (a seek, a restart) needs telling.
if abs(ms - self._last_pos) > 2000:
self._last_pos = ms
self.update()
else:
self._last_pos = ms
def info(self) -> dict | None:
"""The nowPlayingInfo dictionary for the current state (None when
nothing is loaded)."""
mp = self._mp
track = self._player.current_track
if track is None:
return None
playing = self._player.is_playing()
info = {
mp.MPMediaItemPropertyTitle: track.name or "",
mp.MPMediaItemPropertyArtist: track.artist or "",
mp.MPMediaItemPropertyAlbumTitle: track.album or "",
mp.MPNowPlayingInfoPropertyElapsedPlaybackTime:
self._player.position_ms() / 1000.0,
mp.MPNowPlayingInfoPropertyPlaybackRate: 1.0 if playing else 0.0,
}
length = track.total_time or self._player.duration_ms()
if length:
info[mp.MPMediaItemPropertyPlaybackDuration] = length / 1000.0
artwork = self._artwork_for(track)
if artwork is not None:
info[mp.MPMediaItemPropertyArtwork] = artwork
return info
def update(self):
try:
center = self._mp.MPNowPlayingInfoCenter.defaultCenter()
info = self.info()
center.setNowPlayingInfo_(info)
if info is None:
state = STATE_STOPPED
elif self._player.is_playing():
state = STATE_PLAYING
else:
state = STATE_PAUSED
# macOS only routes the media keys to an app that says it's
# playing (or paused), so this matters as much as the info.
if hasattr(center, "setPlaybackState_"):
center.setPlaybackState_(state)
except Exception as e: # noqa: BLE001 — never break playback for this
log.info("Now Playing: update failed: %s", e)
def _artwork_for(self, track):
if self._appkit is None or not track.location:
return None
if self._art_track == track.track_id:
return self._artwork
self._art_track = track.track_id
self._artwork = None
try:
data = tagging.read_embedded_artwork(track.location)
if not data:
return None
appkit = self._appkit
image = appkit.NSImage.alloc().initWithData_(
appkit.NSData.dataWithBytes_length_(data, len(data)))
if image is None:
return None
self._artwork = self._mp.MPMediaItemArtwork.alloc() \
.initWithBoundsSize_requestHandler_(
image.size(), lambda _size: image)
except Exception as e: # noqa: BLE001
log.info("Now Playing: no artwork for %s: %s", track.location, e)
self._artwork = None
return self._artwork
def invalidate_artwork(self, track=None):
"""Forget the built artwork (after new art is embedded)."""
if track is None or self._art_track == getattr(track, "track_id", None):
self._art_track = None
self._artwork = None
self.update()
def invalidate_artwork(track):
if _live is not None:
_live.invalidate_artwork(track)