Mulberry/mulberry/widgets/hero.py
Mulberry 615b21d64a
Mulberry 1.1.0: Material You music player for Linux and Windows
- KDE/Windows accent-driven Material 3 theme, live updating
- Library, tabbed playlists, smart/saved lists, queue, ratings
- mpv and Qt Multimedia engines, EQ, ReplayGain, gapless
- Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags
- Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys
- Audio CD playback and ripping
- PyInstaller, Inno Setup and AppImage builds via GitHub Actions

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-09 23:00:48 -05:00

811 lines
33 KiB
Python

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""The 'now playing' hero: cookie-shaped cover with a radial visualizer,
wavy seek bar, expressive transport buttons and a synced lyrics card."""
from __future__ import annotations
import math
import time
import numpy as np
from PyQt6.QtCore import QLineF, QPointF, QRectF, QSize, Qt, pyqtSignal
from PyQt6.QtGui import (QBrush, QColor, QFont, QFontMetrics, QImage, QLinearGradient, QPainter,
QPainterPath, QPen, QPixmap, QTransform)
from PyQt6.QtWidgets import (QHBoxLayout, QLabel, QMenu, QSizePolicy, QVBoxLayout, QWidget)
from .. import online
from .. import theme as Th
from ..config import fmt_time, settings
from ..icons import icon, paint_icon
from .m3 import C, ElideLabel, FrameClock, IconButton, PillButton, WavySlider, with_alpha
def blur_image(img: QImage, w: int, h: int) -> QImage:
small = img.scaled(18, 18, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
mid = small.scaled(64, 64, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
return mid.scaled(max(1, w), max(1, h), Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation)
# ---------------------------------------------------------------------- cookie cover
class CookieCover(QWidget):
"""Album art clipped to a spinning M3 'cookie'. The visualizer bars are
anchored to the cookie's own outline, so they follow its scallops and spin
with it."""
clicked = pyqtSignal()
NBARS = 72
def __init__(self, spectrum, parent=None):
super().__init__(parent)
self.spectrum = spectrum
self.image: QImage | None = None
self._pm: QPixmap | None = None
self.playing = False
self.rot = 0.0 # degrees
self.show_bars = True
self.lobes = 9
self._ticking = False
self._acquired = False
self._spin = 7.0
self.setCursor(Qt.CursorShape.PointingHandCursor)
base = np.arange(self.NBARS) / self.NBARS * 2 * np.pi
self._base = base
self._shape = 1.0 + np.cos(self.lobes * base) # 0..2 scallop factor per bar
def set_image(self, img: QImage | None):
self.image = img
self._pm = None
self.update()
def set_playing(self, on):
self.playing = on
self._sync()
def _sync(self):
vis = self.isVisible() and self.show_bars
if vis and not self._acquired:
self.spectrum.acquire()
self._acquired = True
elif not vis and self._acquired:
self.spectrum.release()
self._acquired = False
need = self.isVisible() and (self.playing or self.spectrum.levels.max() > 0.002)
if need and not self._ticking:
FrameClock.subscribe(self._tick)
self._ticking = True
elif not need and self._ticking:
FrameClock.unsubscribe(self._tick)
self._ticking = False
self.update()
def showEvent(self, e):
self._sync()
def hideEvent(self, e):
self._sync()
def _tick(self, dt=1 / 60):
target = (7.0 + 55.0 * self.spectrum.pulse) if self.playing else 0.0
self._spin += (target - self._spin) * min(1.0, dt * 4)
self.rot = (self.rot + self._spin * dt) % 360
self.update()
if not self.playing and self._spin < 0.05 and self.spectrum.levels.max() <= 0.002:
self._sync()
def resizeEvent(self, e):
self._pm = None
def mouseReleaseEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
def _cover_pm(self, d: int) -> QPixmap:
"""Cached at a fixed size; per-frame size changes are done with the
brush transform (no rescaling every frame)."""
dpr = self.devicePixelRatioF()
if self._pm is None or self._pm.width() != int(d * dpr):
if self.image is not None and not self.image.isNull():
img = self.image.scaled(int(d * dpr), int(d * dpr), Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation)
self._pm = QPixmap.fromImage(img)
else:
self._pm = QPixmap()
return self._pm
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
size = min(self.width(), self.height())
cx, cy = self.width() / 2, self.height() / 2
Ro = size / 2 - 2
bars = self.show_bars and size > 120
sp = self.spectrum
pulse = sp.pulse if bars else 0.0
R0 = Ro * (0.70 if bars else 0.98)
amp = 0.06 if bars else 0.045
R = R0 * (1 + 0.045 * pulse + 0.015 * sp.bass)
rot = math.radians(self.rot)
# ---- bars glued to the cookie outline
if bars:
n = self.NBARS
half = sp.resample(n // 2)
lv = np.concatenate((half, half[::-1]))
ang = self._base + rot
edge = R * (1 - amp + amp * (self._shape - 1.0)) # cookie radius under each bar
gap = Ro * 0.035
maxlen = Ro - (R0 * 1.05) - gap - 3
r1 = edge + gap
r2 = r1 + 2.5 + lv * maxlen
ca, sa = np.cos(ang), np.sin(ang)
x1, y1 = cx + ca * r1, cy + sa * r1
x2, y2 = cx + ca * r2, cy + sa * r2
prim = C("primary")
width = max(2.6, size / 80)
buckets = np.minimum(3, (lv * 4.5).astype(int))
for b in range(4):
idx = np.nonzero(buckets == b)[0]
if not len(idx):
continue
p.setPen(QPen(with_alpha(prim, 0.42 + 0.19 * b), width, Qt.PenStyle.SolidLine,
Qt.PenCapStyle.RoundCap))
p.drawLines([QLineF(x1[i], y1[i], x2[i], y2[i]) for i in idx])
# ---- cookie
steps = 160
t = np.linspace(0, 2 * np.pi, steps, endpoint=False)
r = R * (1 - amp + amp * np.cos(self.lobes * (t - rot)))
xs, ys = cx + r * np.cos(t), cy + r * np.sin(t)
path = QPainterPath(QPointF(xs[0], ys[0]))
for i in range(1, steps):
path.lineTo(xs[i], ys[i])
path.closeSubpath()
dmax = int(R0 * 2.12)
pm = self._cover_pm(dmax)
if not pm.isNull():
br = QBrush(pm)
tr = QTransform()
tr.translate(cx - R, cy - R)
k = (2 * R) / (pm.width())
tr.scale(k, k)
br.setTransform(tr)
p.fillPath(path, br)
else:
p.fillPath(path, C("primaryContainer"))
s2 = R * 0.7
paint_icon(p, QRectF(cx - s2 / 2, cy - s2 / 2, s2, s2), "album", C("onPrimaryContainer"))
# ---------------------------------------------------------------------- lyrics view
class LyricsView(QWidget):
"""Synced lyrics: the active line glows and pops, the list glides to keep
it in view, and clicking any line seeks there (like Spotify)."""
seek_requested = pyqtSignal(float)
def __init__(self, parent=None):
super().__init__(parent)
self.lines: list[tuple[float, str]] = []
self.synced = False
self.state = "empty"
self.message = "No lyrics"
self.offset = 0.0
self.target = 0.0
self.current = -1
self._layout: list[tuple[float, float]] = [] # y, h per line
self._act: np.ndarray = np.zeros(0) # animated highlight per line
self._manual_until = 0.0
self._animating = False
self._hover = -1
self.time_offset = 0.0
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumHeight(80)
self.setMouseTracking(True)
def _font(self, active=False):
return Th.theme.display_font(15, QFont.Weight.DemiBold)
def set_message(self, msg, state="empty"):
self.lines, self.synced, self.state, self.message = [], False, state, msg
self._layout = []
self._act = np.zeros(0)
self.offset = self.target = 0
self.current = -1
self._hover = -1
self.setCursor(Qt.CursorShape.ArrowCursor)
self.update()
def set_text(self, text: str, plain_only=False):
if plain_only:
parsed, _ = online.parse_lrc(text)
lines, synced = [(-1.0, t) for _, t in parsed], False
else:
lines, synced = online.parse_lrc(text)
while lines and not lines[0][1].strip() and not synced:
lines.pop(0)
if not lines or all(not t.strip() for _, t in lines):
self.set_message("No lyrics found")
return
if len(lines) == 1 and lines[0][1].strip().lower() == "[instrumental]":
self.set_message("♪ Instrumental ♪")
return
self.lines, self.synced, self.state = lines, synced, "text"
self.offset = self.target = 0
self.current = -1
self._act = np.zeros(len(lines))
self._relayout()
self.update()
def _relayout(self):
self._layout = []
y = 0.0
w = max(50, self.width() - 16)
fm = QFontMetrics(self._font(True))
for _, txt in self.lines:
if not txt.strip():
h = fm.height() * (0.6 if self.synced else 0.5)
else:
h = fm.boundingRect(0, 0, w, 10000, Qt.TextFlag.TextWordWrap, txt).height()
self._layout.append((y, h))
y += h + 12
self._content_h = y
def resizeEvent(self, e):
if self.lines:
self._relayout()
self._retarget(jump=True)
def set_position(self, sec):
if not self.synced or not self.lines:
return
sec += self.time_offset
idx = -1
lo, hi = 0, len(self.lines) - 1
while lo <= hi:
mid = (lo + hi) // 2
if self.lines[mid][0] <= sec + 0.15:
idx = mid
lo = mid + 1
else:
hi = mid - 1
if idx != self.current:
self.current = idx
self._retarget()
self._start()
def _retarget(self, jump=False):
if time.monotonic() < self._manual_until:
return
if self.synced and 0 <= self.current < len(self._layout):
y, h = self._layout[self.current]
self.target = max(0.0, y + h / 2 - self.height() * 0.34)
elif self.synced:
self.target = 0.0
if jump:
self.offset = self.target
self.update()
else:
self._start()
def _start(self):
if not self._animating and self.isVisible():
self._animating = True
FrameClock.subscribe(self._tick)
def _tick(self, dt=1 / 60):
k = 1 - math.exp(-dt * 9.0) # frame-rate independent easing
self.offset += (self.target - self.offset) * k
settled = abs(self.target - self.offset) < 0.3
if len(self._act):
goal = np.zeros(len(self._act))
if 0 <= self.current < len(goal):
goal[self.current] = 1.0
self._act += (goal - self._act) * (1 - math.exp(-dt * 10.0))
settled = settled and float(np.abs(goal - self._act).max()) < 0.01
if settled:
self.offset = self.target
FrameClock.unsubscribe(self._tick)
self._animating = False
self.update()
def hideEvent(self, e):
if self._animating:
FrameClock.unsubscribe(self._tick)
self._animating = False
self.offset = self.target
def wheelEvent(self, e):
if not self.lines:
return
maxo = max(0.0, getattr(self, "_content_h", 0) - self.height() * 0.5)
self.target = max(0.0, min(maxo, self.target - e.angleDelta().y() / 1.5))
self._manual_until = time.monotonic() + 4
self._start()
def _line_at(self, y):
y += self.offset
for i, (ly, h) in enumerate(self._layout):
if ly - 6 <= y <= ly + h + 6 and self.lines[i][1].strip():
return i
return -1
def mouseMoveEvent(self, e):
i = self._line_at(e.position().y()) if self.synced else -1
if i != self._hover:
self._hover = i
self.setCursor(Qt.CursorShape.PointingHandCursor if i >= 0 else Qt.CursorShape.ArrowCursor)
self.setToolTip(f"Jump to {fmt_time(self.lines[i][0] - self.time_offset)}" if i >= 0 else "")
self.update()
def leaveEvent(self, e):
if self._hover != -1:
self._hover = -1
self.update()
def mouseReleaseEvent(self, e):
if not self.synced or e.button() != Qt.MouseButton.LeftButton:
return
i = self._line_at(e.position().y())
if i >= 0:
self._manual_until = 0
self.current = i
self._retarget()
self.seek_requested.emit(max(0.0, self.lines[i][0] - self.time_offset + 0.01))
def paintEvent(self, e):
W, H = self.width(), self.height()
dpr = self.devicePixelRatioF()
pm = QPixmap(int(W * dpr), int(H * dpr))
pm.setDevicePixelRatio(dpr)
pm.fill(Qt.GlobalColor.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
if self.state != "text":
p.setFont(Th.theme.display_font(15, QFont.Weight.Medium))
p.setPen(with_alpha(C("onSurfaceVariant"), 0.8))
p.drawText(QRectF(8, 0, W - 8, H * 0.6), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
| Qt.TextFlag.TextWordWrap, self.message)
p.end()
QPainter(self).drawPixmap(0, 0, pm)
return
prim = C("primary")
var = C("onSurfaceVariant")
onsurf = C("onSurface")
w = W - 16
p.setFont(self._font())
for i, ((t, txt), (y, h)) in enumerate(zip(self.lines, self._layout)):
yy = y - self.offset
if yy + h < -14 or yy > H + 14:
continue
if self.synced:
a = float(self._act[i]) if i < len(self._act) else 0.0
dist = abs(i - self.current) if self.current >= 0 else i + 1
base = with_alpha(var, max(0.36, 0.9 - dist * 0.09))
col = Th.mix(base, prim, a)
if i == self._hover:
hp = QPainterPath()
hp.addRoundedRect(QRectF(0, yy - 5, W, h + 10), 12, 12)
p.fillPath(hp, with_alpha(onsurf, 0.07))
if a < 0.5:
col = Th.mix(col, onsurf, 0.6)
scale = 1.0 + 0.045 * a
else:
col, scale = onsurf, 1.0
p.save()
p.translate(8, yy + h / 2)
p.scale(scale, scale)
p.setPen(col)
p.drawText(QRectF(0, -h / 2 - 1, w / scale, h + 2), Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft, txt)
p.restore()
# fade edges
p.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
g = QLinearGradient(0, 0, 0, H)
fade = min(0.18, 28 / max(H, 1))
g.setColorAt(0, QColor(0, 0, 0, 0 if self.offset > 2 else 255))
g.setColorAt(fade, QColor(0, 0, 0, 255))
g.setColorAt(1 - fade * 1.4, QColor(0, 0, 0, 255))
g.setColorAt(1, QColor(0, 0, 0, 0))
p.fillRect(QRectF(0, 0, W, H), g)
p.end()
QPainter(self).drawPixmap(0, 0, pm)
# ---------------------------------------------------------------------- hero
class Hero(QWidget):
open_menu = pyqtSignal(object) # QPoint for the song actions menu
cover_clicked = pyqtSignal()
def __init__(self, player, nowplaying, spectrum, scrobbler, parent=None):
super().__init__(parent)
self.player, self.np, self.scrobbler = player, nowplaying, scrobbler
self.mode = "full"
self._bg: QPixmap | None = None
self._bg_img: QImage | None = None
self._show_info = False
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.cover = CookieCover(spectrum)
self.cover.clicked.connect(self.cover_clicked)
self.title = ElideLabel("Nothing playing")
self.artist = ElideLabel("")
self.album = ElideLabel("")
self.meta = ElideLabel("")
self.meta.setObjectName("muted")
self.pos_lbl = QLabel("0:00")
self.dur_lbl = QLabel("0:00")
for lbl in (self.pos_lbl, self.dur_lbl):
lbl.setMinimumWidth(40)
self.dur_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
self.wave = WavySlider()
self.wave.seek_requested.connect(lambda v: player.seek(v * player.dur))
self.wave.dragging.connect(lambda v: self.pos_lbl.setText(fmt_time(v * player.dur)))
self.b_shuffle = IconButton("shuffle", "tonal", 44, 22, tooltip="Shuffle")
self.b_shuffle.setCheckable(True)
self.b_prev = IconButton("skip_previous_fill", "tonal", 44, 24, tooltip="Previous")
self.b_play = IconButton("play_arrow_fill", "filled", 56, 30, wide=104, tooltip="Play / Pause")
self.b_next = IconButton("skip_next_fill", "tonal", 44, 24, tooltip="Next")
self.b_repeat = IconButton("repeat", "tonal", 44, 22, tooltip="Repeat")
self.b_repeat.setCheckable(True)
self.b_prev.clicked.connect(player.prev)
self.b_next.clicked.connect(player.next)
self.b_play.clicked.connect(player.play_pause)
self.b_shuffle.clicked.connect(self._toggle_shuffle)
self.b_repeat.clicked.connect(self._cycle_repeat)
# ---- layout: cover | info | lyrics
info = QVBoxLayout()
info.setSpacing(2)
info.addStretch(1)
info.addWidget(self.title)
info.addWidget(self.artist)
info.addWidget(self.album)
info.addWidget(self.meta)
info.addSpacing(12)
prow = QHBoxLayout()
prow.setSpacing(6)
prow.addWidget(self.pos_lbl)
prow.addWidget(self.wave, 1)
prow.addWidget(self.dur_lbl)
info.addLayout(prow)
info.addSpacing(6)
self.controls = QWidget()
brow = QHBoxLayout(self.controls)
brow.setContentsMargins(0, 0, 0, 0)
brow.setSpacing(6)
brow.addStretch(1)
for b in (self.b_shuffle, self.b_prev, self.b_play, self.b_next, self.b_repeat):
brow.addWidget(b)
brow.addStretch(1)
info.addWidget(self.controls)
info.addStretch(1)
self.info_lay = info
self.info_w = QWidget()
self.info_w.setLayout(info)
self.info_w.setMinimumWidth(300)
# lyrics card
self.lcard = QWidget()
self.lcard.setMinimumWidth(280)
self.lcard.setMaximumWidth(460)
lc = QVBoxLayout(self.lcard)
lc.setContentsMargins(0, 0, 0, 0)
lc.setSpacing(8)
hdr = QHBoxLayout()
self.l_icon = QLabel()
self.l_title = QLabel("Lyrics")
self.l_menu = IconButton("more_vert", "tonal", 36, 20, tooltip="Lyrics options")
self.l_menu.clicked.connect(self._lyrics_menu)
hdr.addWidget(self.l_icon)
hdr.addWidget(self.l_title)
self.l_src = QLabel("")
self.l_src.setObjectName("muted")
hdr.addWidget(self.l_src)
hdr.addStretch(1)
hdr.addWidget(self.l_menu)
lc.addLayout(hdr)
self.lyrics = LyricsView()
self.lyrics.seek_requested.connect(player.seek)
lc.addWidget(self.lyrics, 1)
self.love = PillButton("favorite", "Love", split=True)
self.love.setCheckable(True)
self.love.clicked.connect(self._toggle_love)
self.love.menu_requested.connect(lambda: self.open_menu.emit(
self.love.mapToGlobal(self.love.rect().bottomRight())))
lc.addWidget(self.love)
lay = QHBoxLayout(self)
lay.setContentsMargins(18, 14, 18, 14)
lay.setSpacing(22)
lay.addWidget(self.cover)
lay.addWidget(self.info_w, 3)
lay.addWidget(self.lcard, 2)
self.main_lay = lay
self.restyle()
self.set_mode(settings.get("appearance/hero"))
player.song_changed.connect(self.on_song)
player.state_changed.connect(self.on_state)
player.position_changed.connect(self.on_pos)
nowplaying.art_changed.connect(self.on_art)
nowplaying.lyrics_changed.connect(self.on_lyrics)
nowplaying.info_changed.connect(self.on_info)
Th.theme.changed.connect(self.restyle)
self.sync_modes()
# -------------------------------------------------------------- style/mode
def restyle(self):
t = Th.theme
big = self.mode == "full"
self.title.setFont(t.display_font(28 if big else 18, QFont.Weight.DemiBold))
self.artist.setFont(t.display_font(17 if big else 14, QFont.Weight.DemiBold))
self.album.setFont(t.display_font(17 if big else 13, QFont.Weight.DemiBold))
self.l_title.setFont(t.display_font(18, QFont.Weight.DemiBold))
self.title.setStyleSheet(f"color: {t['onSurface'].name()};")
self.artist.setStyleSheet(f"color: {t['onSurface'].name()};")
self.album.setStyleSheet(f"color: {t['primary'].name()};")
self.meta.setStyleSheet(f"color: {t['onSurfaceVariant'].name()}; font-size: 9pt;")
mono = t.display_font(13, QFont.Weight.Medium)
for lbl in (self.pos_lbl, self.dur_lbl):
lbl.setFont(mono)
lbl.setStyleSheet(f"color: {t['onSurfaceVariant'].name()};")
self.l_icon.setPixmap(icon("lyrics", "onSurface").pixmap(QSize(24, 24), self.devicePixelRatioF()))
self._bg = None
self.update()
def set_mode(self, mode):
self.mode = mode if mode in ("full", "compact") else "full"
full = self.mode == "full"
self.cover.show_bars = full and settings.get("appearance/visualizer")
self.cover.setFixedSize(QSize(250, 250) if full else QSize(92, 92))
self.lcard.setVisible(full)
self.album.setVisible(full)
self.meta.setVisible(full)
self.layout().setContentsMargins(*(18, 14, 18, 14) if full else (16, 8, 18, 8))
# compact: transport moves to the right of the info column (one row)
if full and self.main_lay.indexOf(self.controls) >= 0:
self.main_lay.removeWidget(self.controls)
self.info_lay.insertWidget(self.info_lay.count() - 1, self.controls)
elif not full and self.info_lay.indexOf(self.controls) >= 0:
self.info_lay.removeWidget(self.controls)
self.main_lay.insertWidget(2, self.controls)
self.info_lay.setSpacing(2 if full else 0)
self.cover._sync()
self.restyle()
def sync_modes(self):
mgr = self.player.mgr
self.b_shuffle.setChecked(mgr.shuffle)
self.b_repeat.setChecked(mgr.repeat != "off")
self.b_repeat.set_icon("repeat_one" if mgr.repeat == "track" else "repeat")
self.b_repeat.setToolTip({"off": "Repeat: off", "playlist": "Repeat: playlist",
"track": "Repeat: track"}[mgr.repeat])
def _toggle_shuffle(self):
self.player.mgr.set_shuffle(self.b_shuffle.isChecked())
self.player.refresh_next()
self.window().sync_modes()
def _cycle_repeat(self):
mgr = self.player.mgr
nxt = {"off": "playlist", "playlist": "track", "track": "off"}[mgr.repeat]
mgr.set_repeat(nxt)
self.player.refresh_next()
self.window().sync_modes()
def _toggle_love(self):
s = self.player.song
if not s:
self.love.setChecked(False)
return
loved = self.love.isChecked()
from .. import library as L
L.library.set_rating(s, 5 if loved else 0)
self.love.setText("Loved" if loved else "Love")
self.love.icon_name = "favorite_fill" if loved else "favorite"
self.scrobbler.love(s, loved)
# -------------------------------------------------------------- player events
def on_song(self, s):
if s is None:
return
if s.is_stream:
st = s.stream_title
if st and " - " in st:
a, t = st.split(" - ", 1)
self.title.setText(t)
self.artist.setText(a)
else:
self.title.setText(st or s.title or "Radio stream")
self.artist.setText(s.title if st else "")
self.album.setText(s.title if st else s.url)
else:
self.title.setText(s.display_title())
self.artist.setText(s.display_artist())
self.album.setText(s.album + (f" · {s.year}" if s.year else ""))
bits = [s.filetype]
if s.bitdepth and s.samplerate:
bits.append(f"{s.bitdepth}-bit / {s.samplerate / 1000:g} kHz")
elif s.samplerate:
bits.append(f"{s.samplerate / 1000:g} kHz")
if s.bitrate:
bits.append(f"{s.bitrate} kbps")
if s.playcount:
bits.append(f"played {s.playcount}×")
self.meta.setText(" · ".join(b for b in bits if b))
loved = s.rating >= 5
self.love.setChecked(loved)
self.love.setText("Loved" if loved else "Love")
self.love.icon_name = "favorite_fill" if loved else "favorite"
self.love.update()
self.dur_lbl.setText(fmt_time(s.duration()) if not s.is_stream else "LIVE")
if self._show_info:
self.np.load_artist_info()
def on_state(self, st):
playing = st == "playing"
self.b_play.set_icon("pause_fill" if playing else "play_arrow_fill")
self.b_play.set_morph(playing)
self.wave.set_playing(playing)
self.cover.set_playing(playing)
if st == "stopped":
self.wave.set_value(0)
self.pos_lbl.setText("0:00")
def on_pos(self, pos, dur):
if self.wave._drag is None:
self.pos_lbl.setText(fmt_time(pos))
if dur > 0:
self.wave.set_value(pos / dur, dur)
self.dur_lbl.setText(fmt_time(dur))
if not self._show_info:
self.lyrics.set_position(pos)
def on_art(self, img, path):
self.cover.set_image(img)
self._bg_img = img
self._bg = None
self.update()
def on_lyrics(self, text, source, song):
if self._show_info:
return
if source == "loading":
self.lyrics.set_message("Searching for lyrics…", "loading")
elif source == "error":
self.lyrics.set_message("Couldn't reach the lyrics service")
elif source == "nolocal":
self.lyrics.set_message("No .lrc file next to this song.\nUse LRCGET to download them, "
"or pick another source in ⋮.")
elif not text:
self.lyrics.set_message("No lyrics found" if song and not song.is_stream else "No lyrics")
else:
self.lyrics.set_text(text, plain_only=settings.get("lyrics/plain"))
self.lyrics.set_position(self.player.pos)
self.l_title.setText("Lyrics")
shown = source if source not in ("loading", "error", "nolocal", "") else ""
if shown and settings.get("lyrics/plain"):
shown += " · plain"
self.l_src.setText(shown)
def on_info(self, artist, text):
if not self._show_info:
return
self.l_title.setText(artist or "Artist")
if text:
self.lyrics.set_text(text, plain_only=True)
else:
self.lyrics.set_message("No artist information found")
def _lyrics_menu(self):
m = QMenu(self)
if self._show_info:
m.addAction(icon("lyrics"), "Show lyrics", lambda: self._set_info(False))
else:
m.addAction(icon("person"), "Show artist info", lambda: self._set_info(True))
m.addSeparator()
src_menu = m.addMenu(icon("cloud_download"), "Lyrics source")
cur = settings.get("lyrics/source")
for key, label in (("auto", "Auto (local → LRCLIB → NetEase)"), ("lrclib", "LRCLIB"),
("netease", "NetEase Cloud Music"), ("local", "Local .lrc files (LRCGET)"),
("embedded", "Embedded in the audio file")):
a = src_menu.addAction(label)
a.setCheckable(True)
a.setChecked(key == cur)
a.triggered.connect(lambda _c, k=key: self.np.set_source(k))
plain = m.addAction(icon("text_snippet"), "Show as plain text (no sync)")
plain.setCheckable(True)
plain.setChecked(settings.get("lyrics/plain"))
plain.toggled.connect(self._toggle_plain)
m.addSeparator()
m.addAction(icon("refresh"), "Search again", self.np.refetch_lyrics)
m.addAction(icon("file_open"), "Load .lrc / text file…", self._load_lrc)
m.addAction(icon("edit"), "Edit lyrics…", self._edit_lyrics)
m.addSeparator()
m.addAction("Lyrics earlier (−0.5 s)", lambda: self._shift(-0.5))
m.addAction("Lyrics later (+0.5 s)", lambda: self._shift(0.5))
m.addAction("Reset timing", lambda: self._shift(None))
m.exec(self.l_menu.mapToGlobal(self.l_menu.rect().bottomLeft()))
def _toggle_plain(self, on):
settings.set("lyrics/plain", on)
self.on_lyrics(self.np.lyrics, self.np.lyrics_source, self.np.song)
def _shift(self, d):
self.lyrics.time_offset = 0.0 if d is None else self.lyrics.time_offset - d
self.lyrics.set_position(self.player.pos)
def _set_info(self, on):
self._show_info = on
if on:
self.lyrics.set_message("Loading artist info…", "loading")
self.np.load_artist_info()
else:
self.on_lyrics(self.np.lyrics, self.np.lyrics_source, self.np.song)
def _load_lrc(self):
from PyQt6.QtWidgets import QFileDialog
path, _ = QFileDialog.getOpenFileName(self, "Load lyrics", "", "Lyrics (*.lrc *.txt);;All files (*)")
if path:
with open(path, encoding="utf-8", errors="replace") as fh:
self.np.set_lyrics(fh.read())
def _edit_lyrics(self):
from .dialogs import LyricsEditor
dlg = LyricsEditor(self.np.lyrics, self)
if dlg.exec():
self.np.set_lyrics(dlg.text(), dlg.save_to_file())
# -------------------------------------------------------------- painting
def resizeEvent(self, e):
self._bg = None
self._cache = None
def _render_bg(self) -> QPixmap:
"""Card background (blurred art, gradient, lyrics panel) rendered once
and reused every frame — animated children no longer force a full
repaint of the blur."""
dpr = self.devicePixelRatioF()
pm = QPixmap(int(self.width() * dpr), int(self.height() * dpr))
pm.setDevicePixelRatio(dpr)
pm.fill(Qt.GlobalColor.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
r = QRectF(self.rect()).adjusted(6, 4, -6, -2)
rad = 28 if self.mode == "full" else 22
path = QPainterPath()
path.addRoundedRect(r, rad, rad)
p.fillPath(path, C("surfaceContainerLow"))
if self._bg_img is not None and not self._bg_img.isNull():
bg = QPixmap.fromImage(blur_image(self._bg_img, self.width(), self.height()))
p.save()
p.setClipPath(path)
p.setOpacity(0.30 if Th.theme.dark else 0.22)
p.drawPixmap(QRectF(self.rect()), bg, QRectF(bg.rect()))
p.setOpacity(1.0)
g = QLinearGradient(0, 0, self.width(), 0)
base = C("surfaceContainerLow")
g.setColorAt(0, with_alpha(base, 0.15))
g.setColorAt(0.55, with_alpha(base, 0.55))
g.setColorAt(1, with_alpha(base, 0.8))
p.fillPath(path, g)
p.restore()
if self.mode == "full" and self.lcard.isVisible():
lr = QRectF(self.lcard.geometry()).adjusted(-12, -8, 10, 6)
lp = QPainterPath()
lp.addRoundedRect(lr, 22, 22)
p.fillPath(lp, with_alpha(C("surfaceContainerHigh"), 0.55))
p.end()
return pm
def paintEvent(self, e):
key = (self.width(), self.height(), self.devicePixelRatioF(), self.mode,
self.lcard.geometry().getRect() if self.lcard.isVisible() else None,
id(self._bg_img), Th.theme.c["surfaceContainerLow"].rgb(), Th.theme.dark)
if getattr(self, "_cache", None) is None or self._cache_key != key:
self._cache = self._render_bg()
self._cache_key = key
p = QPainter(self)
dpr = self._cache.devicePixelRatio()
r = e.rect()
p.drawPixmap(r, self._cache, QRectF(r.x() * dpr, r.y() * dpr, r.width() * dpr, r.height() * dpr).toRect())