Mulberry/mulberry/widgets/m3.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

569 lines
20 KiB
Python

"""Hand-painted Material 3 (Expressive) components."""
from __future__ import annotations
import math
from PyQt6.QtCore import (QEasingCurve, QPointF, QRectF, QSize, Qt, QTimer, QVariantAnimation,
pyqtProperty, pyqtSignal)
from PyQt6.QtGui import QColor, QFontMetrics, QPainter, QPainterPath, QPen
from PyQt6.QtWidgets import QAbstractButton, QLabel, QLineEdit, QSizePolicy, QWidget
from .. import theme as Th
from ..icons import paint_icon
def C(role) -> QColor:
return QColor(Th.theme.c[role])
def with_alpha(c: QColor, a: float) -> QColor:
c = QColor(c)
c.setAlphaF(a)
return c
from ..clock import FrameClock # noqa: E402 (shared display-rate clock)
# ---------------------------------------------------------------------- buttons
class IconButton(QAbstractButton):
"""M3 icon button. variant: standard | tonal | filled | outlined.
`wide` gives the expressive rounded-rect play button that morphs on toggle."""
def __init__(self, icon_name: str, variant="standard", size=40, icon_size=24, wide=0,
checked_icon: str | None = None, tooltip="", parent=None):
super().__init__(parent)
self.icon_name, self.checked_icon = icon_name, checked_icon
self.variant, self.btn_size, self.icon_px, self.wide = variant, size, icon_size, wide
self._hover = 0.0
self._press = 0.0
self._morph = 0.0
self.toggle_style = False
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFixedSize(QSize(wide or size, size))
if tooltip:
self.setToolTip(tooltip)
self._anim = QVariantAnimation(self, duration=220, easingCurve=QEasingCurve.Type.OutCubic)
self._anim.valueChanged.connect(self._set_morph)
self._hanim = QVariantAnimation(self, duration=120)
self._hanim.valueChanged.connect(lambda v: (setattr(self, "_hover", v), self.update()))
self.toggled.connect(self._on_toggled)
def set_icon(self, name):
self.icon_name = name
self.update()
def _set_morph(self, v):
self._morph = v
self.update()
def set_morph(self, on: bool, animate=True):
target = 1.0 if on else 0.0
if animate:
self._anim.stop()
self._anim.setStartValue(self._morph)
self._anim.setEndValue(target)
self._anim.start()
else:
self._set_morph(target)
def _on_toggled(self, on):
if self.toggle_style:
self.set_morph(on)
self.update()
def enterEvent(self, e):
self._hanim.stop()
self._hanim.setStartValue(self._hover)
self._hanim.setEndValue(1.0)
self._hanim.start()
def leaveEvent(self, e):
self._hanim.stop()
self._hanim.setStartValue(self._hover)
self._hanim.setEndValue(0.0)
self._hanim.start()
def sizeHint(self):
return QSize(self.wide or self.btn_size, self.btn_size)
def colors(self):
on = self.isChecked()
v = self.variant
if v == "filled":
return C("primary"), C("onPrimary")
if v == "tonal":
if self.isCheckable() and on:
return C("primary"), C("onPrimary")
return C("secondaryContainer"), C("onSecondaryContainer")
if v == "outlined":
return QColor(0, 0, 0, 0), C("onSurfaceVariant")
if self.isCheckable() and on:
return QColor(0, 0, 0, 0), C("primary")
return QColor(0, 0, 0, 0), C("onSurfaceVariant")
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
r = QRectF(self.rect()).adjusted(1, 1, -1, -1)
bg, fg = self.colors()
if not self.isEnabled():
fg = with_alpha(C("onSurface"), 0.38)
if bg.alpha():
bg = with_alpha(C("onSurface"), 0.12)
h = r.height()
if self.wide:
# expressive: square-ish when "on" (playing), pill when off
rad = h / 2 - (h / 2 - h * 0.3) * self._morph
elif self.toggle_style:
rad = h / 2 - (h / 2 - h * 0.3) * self._morph
else:
rad = h / 2
path = QPainterPath()
path.addRoundedRect(r, rad, rad)
if bg.alpha():
p.fillPath(path, bg)
if self.variant == "outlined":
p.setPen(QPen(C("outlineVariant"), 1))
p.drawPath(path)
state = self._hover * 0.08 + (0.1 if self.isDown() else 0)
if state > 0 and self.isEnabled():
p.fillPath(path, with_alpha(fg, state))
name = self.checked_icon if (self.isChecked() and self.checked_icon) else self.icon_name
s = self.icon_px
ir = QRectF(r.center().x() - s / 2, r.center().y() - s / 2, s, s)
paint_icon(p, ir, name, fg)
class PillButton(QAbstractButton):
"""Tonal pill with icon + text (+ optional split dropdown)."""
menu_requested = pyqtSignal()
def __init__(self, icon_name, text, split=False, parent=None):
super().__init__(parent)
self.icon_name, self.split = icon_name, split
self.setText(text)
self._hover_part = 0
self.setMouseTracking(True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFixedHeight(40)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
def sizeHint(self):
fm = QFontMetrics(self.font())
return QSize(fm.horizontalAdvance(self.text()) + 80 + (44 if self.split else 0), 40)
def mouseMoveEvent(self, e):
part = 2 if self.split and e.position().x() > self.width() - 44 else 1
if part != self._hover_part:
self._hover_part = part
self.update()
def leaveEvent(self, e):
self._hover_part = 0
self.update()
def mouseReleaseEvent(self, e):
if self.split and e.position().x() > self.width() - 44 and self.rect().contains(e.position().toPoint()):
self.setDown(False)
self.menu_requested.emit()
return
super().mouseReleaseEvent(e)
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
bg = C("primaryContainer") if self.isChecked() else C("secondaryContainer")
fg = C("onPrimaryContainer") if self.isChecked() else C("onSecondaryContainer")
main = QRectF(r.left(), r.top(), r.width() - (46 if self.split else 0), r.height())
mainpath = QPainterPath()
if self.split:
self._split_left(mainpath, main)
else:
mainpath.addRoundedRect(main, 20, 20)
p.fillPath(mainpath, bg)
if self._hover_part == 1:
p.fillPath(mainpath, with_alpha(fg, 0.08))
fm = QFontMetrics(self.font())
tw = fm.horizontalAdvance(self.text())
total = 20 + 8 + tw
x = main.center().x() - total / 2
paint_icon(p, QRectF(x, main.center().y() - 10, 20, 20), self.icon_name, fg)
p.setPen(fg)
p.drawText(QRectF(x + 28, main.top(), tw + 4, main.height()),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text())
if self.split:
dr = QRectF(r.right() - 44, r.top(), 44, r.height())
dpath = QPainterPath()
self._split_right(dpath, dr)
p.fillPath(dpath, bg)
if self._hover_part == 2:
p.fillPath(dpath, with_alpha(fg, 0.08))
paint_icon(p, QRectF(dr.center().x() - 11, dr.center().y() - 11, 22, 22), "expand_more", fg)
@staticmethod
def _split_left(path: QPainterPath, r: QRectF):
R, rr = 20, 5
path.moveTo(r.left() + R, r.top())
path.lineTo(r.right() - rr, r.top())
path.quadTo(r.right(), r.top(), r.right(), r.top() + rr)
path.lineTo(r.right(), r.bottom() - rr)
path.quadTo(r.right(), r.bottom(), r.right() - rr, r.bottom())
path.lineTo(r.left() + R, r.bottom())
path.arcTo(QRectF(r.left(), r.bottom() - 2 * R, 2 * R, 2 * R), 270, -180)
path.closeSubpath()
@staticmethod
def _split_right(path: QPainterPath, r: QRectF):
R, rr = 20, 5
path.moveTo(r.left() + rr, r.top())
path.lineTo(r.right() - R, r.top())
path.arcTo(QRectF(r.right() - 2 * R, r.top(), 2 * R, 2 * R), 90, -180)
path.lineTo(r.left() + rr, r.bottom())
path.quadTo(r.left(), r.bottom(), r.left(), r.bottom() - rr)
path.lineTo(r.left(), r.top() + rr)
path.quadTo(r.left(), r.top(), r.left() + rr, r.top())
path.closeSubpath()
# ---------------------------------------------------------------------- wavy slider
class WavySlider(QWidget):
"""M3 Expressive wavy progress/seek bar."""
seek_requested = pyqtSignal(float) # 0..1
dragging = pyqtSignal(float)
def __init__(self, parent=None):
super().__init__(parent)
self.value = 0.0
self.playing = False
self._amp = 0.0
self._phase = 0.0
self._drag = None
self._hover = False
self.setMinimumHeight(28)
self.setMouseTracking(True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._ticking = False
self.duration = 0.0
self._target = None
def set_value(self, v, duration: float = 0.0):
"""Reported position. Between reports the thumb is extrapolated each
frame so it glides instead of stepping."""
v = max(0.0, min(1.0, v))
if duration > 0:
self.duration = duration
if self._drag is not None:
return
if not self._ticking or abs(v - self.value) * max(self.duration, 1) > 0.6:
self.value = v # seek / big jump: snap
if not self._ticking:
self.update()
else:
self._target = v
def set_playing(self, on):
self.playing = on
self._ensure_tick()
def _ensure_tick(self):
need = self.isVisible() and (self.playing or self._amp > 0.01)
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
def showEvent(self, e):
self._ensure_tick()
def hideEvent(self, e):
if self._ticking:
FrameClock.unsubscribe(self._tick)
self._ticking = False
def _tick(self, dt=1 / 60):
target = 1.0 if self.playing else 0.0
self._amp += (target - self._amp) * min(1.0, dt * 7)
self._phase = (self._phase + dt * 6.6) % (2 * math.pi)
if self.playing and self.duration > 0 and self._drag is None:
self.value = min(1.0, self.value + dt / self.duration)
if self._target is not None:
self.value += (self._target - self.value) * min(1.0, dt * 3)
self._target = None if abs(self._target - self.value) < 1e-5 else self._target
self.update()
if not self.playing and self._amp < 0.01:
self._amp = 0.0
self._ensure_tick()
def _val_at(self, x):
m = 8
return max(0.0, min(1.0, (x - m) / max(1, self.width() - 2 * m)))
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self._drag = self._val_at(e.position().x())
self.dragging.emit(self._drag)
self.update()
def mouseMoveEvent(self, e):
if self._drag is not None:
self._drag = self._val_at(e.position().x())
self.dragging.emit(self._drag)
self.update()
def mouseReleaseEvent(self, e):
if self._drag is not None:
v = self._drag
self._drag = None
self.value = v
self.seek_requested.emit(v)
self.update()
def enterEvent(self, e):
self._hover = True
self.update()
def leaveEvent(self, e):
self._hover = False
self.update()
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
m = 8.0
w = self.width() - 2 * m
cy = self.height() / 2
v = self._drag if self._drag is not None else self.value
tx = m + w * v
gap = 6.0
stroke = 4.0
prim = C("primary")
track = C("secondaryContainer")
# remaining track
if tx + gap < m + w:
p.setPen(QPen(track, stroke, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
p.drawLine(QPointF(tx + gap, cy), QPointF(m + w, cy))
# stop indicator
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(prim)
p.drawEllipse(QPointF(m + w - 2, cy), 2, 2)
# wavy active part: amplitude eases in from a flat start and eases
# out before the thumb, so the line never starts on a sharp point
if tx - gap > m:
amp = 3.4 * self._amp
wl = 34.0
x_end = tx - gap
ramp = 14.0
path = QPainterPath(QPointF(m, cy))
x = m
step = 1.5
while x < x_end:
x = min(x + step, x_end)
env = min(1.0, (x - m) / ramp, (x_end - x) / ramp)
env = env * env * (3 - 2 * env) # smoothstep
y = cy + amp * env * math.sin((x - m) / wl * 2 * math.pi - self._phase)
path.lineTo(QPointF(x, y))
p.setPen(QPen(prim, stroke, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawPath(path)
# thumb (vertical bar)
th = 22 if (self._hover or self._drag is not None) else 18
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(prim)
p.drawRoundedRect(QRectF(tx - 2.5, cy - th / 2, 5, th), 2.5, 2.5)
class VolumeSlider(QWidget):
changed = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
self.value = 70
self.setFixedHeight(28)
self.setMinimumWidth(90)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._drag = False
def set_value(self, v):
self.value = int(v)
self.update()
def _set_from(self, x):
v = int(round(max(0.0, min(1.0, (x - 6) / max(1, self.width() - 12))) * 100))
if v != self.value:
self.value = v
self.changed.emit(v)
self.update()
def mousePressEvent(self, e):
self._drag = True
self._set_from(e.position().x())
def mouseMoveEvent(self, e):
if self._drag:
self._set_from(e.position().x())
def mouseReleaseEvent(self, e):
self._drag = False
def wheelEvent(self, e):
d = 5 if e.angleDelta().y() > 0 else -5
self.value = max(0, min(100, self.value + d))
self.changed.emit(self.value)
self.update()
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
m = 6
w = self.width() - 2 * m
cy = self.height() / 2
x = m + w * self.value / 100
h = 16.0
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(C("secondaryContainer"))
if x + 5 < m + w:
p.drawRoundedRect(QRectF(x + 5, cy - h / 2 + 2, m + w - x - 5, h - 4), 4, 4)
p.setBrush(C("primary"))
if x - 5 > m:
p.drawRoundedRect(QRectF(m, cy - h / 2, x - 5 - m, h), 7, 7)
p.drawRoundedRect(QRectF(x - 2, cy - 12, 4, 24), 2, 2)
# ---------------------------------------------------------------------- labels/fields
class ElideLabel(QLabel):
def __init__(self, text="", parent=None):
super().__init__(text, parent)
self._full = text
self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
self.setMinimumWidth(10)
def setText(self, t):
self._full = t or ""
self.setToolTip(self._full if len(self._full) > 30 else "")
self._elide()
def text(self):
return self._full
def resizeEvent(self, e):
self._elide()
def _elide(self):
fm = QFontMetrics(self.font())
super().setText(fm.elidedText(self._full, Qt.TextElideMode.ElideRight, max(10, self.width())))
class SearchField(QLineEdit):
def __init__(self, placeholder="Search", parent=None):
super().__init__(parent)
self.setObjectName("search")
self.setFixedHeight(40)
self.setPlaceholderText(placeholder)
self.setClearButtonEnabled(True)
def paintEvent(self, e):
super().paintEvent(e)
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
paint_icon(p, QRectF(12, self.height() / 2 - 10, 20, 20), "search", C("onSurfaceVariant"))
class NavTabs(QWidget):
"""Icon-over-label tabs with a short pill indicator (like the M3 shell bar)."""
changed = pyqtSignal(int)
def __init__(self, items: list[tuple[str, str]], parent=None):
super().__init__(parent)
self.items = items
self.current = 0
self._hover = -1
self._ind = 0.0
self.setFixedHeight(58)
self.setMouseTracking(True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self._anim = QVariantAnimation(self, duration=260, easingCurve=QEasingCurve.Type.OutCubic)
self._anim.valueChanged.connect(lambda v: (setattr(self, "_ind", v), self.update()))
def set_current(self, i, animate=True):
if i == self.current and animate:
return
self._anim.stop()
if animate:
self._anim.setStartValue(float(self._ind))
self._anim.setEndValue(float(i))
self._anim.start()
else:
self._ind = float(i)
self.current = i
self.update()
self.changed.emit(i)
def _idx(self, x):
n = len(self.items)
return max(0, min(n - 1, int(x / (self.width() / n))))
def mouseMoveEvent(self, e):
i = self._idx(e.position().x())
if i != self._hover:
self._hover = i
self.update()
def leaveEvent(self, e):
self._hover = -1
self.update()
def mousePressEvent(self, e):
self.set_current(self._idx(e.position().x()))
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
n = len(self.items)
cw = self.width() / n
f = self.font()
f.setPointSizeF(max(7.5, f.pointSizeF() * 0.86))
p.setFont(f)
fm = QFontMetrics(f)
for i, (icon_name, label) in enumerate(self.items):
r = QRectF(i * cw, 0, cw, self.height() - 6)
active = i == self.current
col = C("primary") if active else C("onSurfaceVariant")
if i == self._hover and not active:
hp = QPainterPath()
hp.addRoundedRect(r.adjusted(4, 4, -4, 0), 12, 12)
p.fillPath(hp, with_alpha(C("onSurface"), 0.06))
paint_icon(p, QRectF(r.center().x() - 11, 8, 22, 22), icon_name, col)
p.setPen(col)
p.drawText(QRectF(r.left(), 32, r.width(), 18), Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,
fm.elidedText(label, Qt.TextElideMode.ElideRight, int(cw - 4)))
# indicator
iw = 28
x = self._ind * cw + cw / 2 - iw / 2
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(C("primary"))
p.drawRoundedRect(QRectF(x, self.height() - 5, iw, 3), 1.5, 1.5)
p.setPen(QPen(C("outlineVariant"), 1))
p.drawLine(QPointF(4, self.height() - 0.5), QPointF(self.width() - 4, self.height() - 0.5))
class Card(QWidget):
"""Rounded surface container."""
def __init__(self, role="surfaceContainerLow", radius=24, parent=None):
super().__init__(parent)
self.role, self.radius = role, radius
def paintEvent(self, e):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(QRectF(self.rect()), self.radius, self.radius)
p.fillPath(path, C(self.role))
def make_alpha_prop():
return pyqtProperty(float)