Files
lintunes/lintunes/gui/transport.py
T

1544 lines
65 KiB
Python

import time
from PyQt6.QtWidgets import (
QWidget, QFrame, QHBoxLayout, QVBoxLayout, QLabel, QToolButton, QSlider,
QPushButton, QSizePolicy, QStyle, QStyleOptionSlider, QLayout, QSpacerItem,
)
from PyQt6.QtCore import Qt, QTimer, QEvent, QPoint, QPointF, QRect, QSize, pyqtSignal
from PyQt6.QtGui import (QColor, QFont, QFontInfo, QFontMetrics, QIcon,
QPainter, QPalette, QPen, QPixmap)
from lintunes.tap_tempo import TapTempo
from lintunes.gui.icons import transport_icon
from lintunes.gui.track_table import format_time
from lintunes.gui.visualizer import VisualizerWidget
from lintunes.player import REPEAT_MODES
from lintunes import theme
from lintunes.gui import toolbar
from lintunes.gui.toolbar import ToolRow, Slot
ICON_GRAY = QColor("#4A4A4A") # light mode's; theme.icon_gray() follows the mode
# Breathing room between the menu bar and the row of boxes.
TOP_MARGIN = 9
# Between the row of boxes and the header row under it.
ROW_GAP = 4
# The row of boxes is knolled: one GAP before the first control, between
# each pair and after the last, always. The now-playing panel (and the seek
# row under it) takes all the width that's left.
GAP = 16
NOW_PLAYING_MIN = 150
# Shared height for the boxed side controls (transport, shuffle, bpm) and the
# visualizer, so they line up. ~midway between their old heights: the stretchy
# boxes/visualizer used to fill the bar (~78px) while the hugging bpm box sat
# at ~46px. Tune to taste.
CONTROL_HEIGHT = 62
# Every control in the bar hangs from the same top edge as the now-playing
# panel (the seek row sits below the panel, not beside the boxes).
TOP = Qt.AlignmentFlag.AlignTop
# Height floor for the whole bar: margin, the row of boxes, and the header row
# (Library button · search or playlist name · seek) at the medium UI scale.
BAR_HEIGHT = TOP_MARGIN + CONTROL_HEIGHT + ROW_GAP + 34
def _box_style(bg: QColor) -> str:
"""A transport box is its buttons: each one carries the shared button
face (emboss, outline, darker on hover, sunk and darker while held), and
the box itself draws nothing. The play box's three are separate buttons
that touch — square where they meet, sharing one line (TILE_STYLE)."""
face = "QFrame#transportBox { border: none; background: transparent; }"
for kind in ("QToolButton", "QPushButton"):
face += theme.button_face_qss(f"QFrame#transportBox > {kind}", bg,
radius=8)
# Greyed in DJ mode: flat and pale, so it reads as switched off.
for kind in ("QToolButton", "QPushButton"):
face += (f"QFrame#transportBox > {kind}:disabled {{ background:"
f" {bg.lighter(104).name()}; border-color: {bg.darker(112).name()}; }}")
text = theme.text_color().name()
return face + TILE_STYLE + f"""
QFrame#transportBox QPushButton, QFrame#transportBox QPushButton:disabled {{
color: {text};
}}
"""
# Where tiles meet: square corners, and one shared line (the later tile
# drops its left border), as the Library button and its ▾ do.
TILE_STYLE = "".join(
f"QFrame#transportBox > {kind}[tile=\"{tile}\"] {{ {rule} }}"
for kind in ("QToolButton", "QPushButton")
for tile, rule in (
("first", "border-top-right-radius: 0; border-bottom-right-radius: 0;"),
("middle", "border-radius: 0; border-left: none;"),
("last", "border-top-left-radius: 0; border-bottom-left-radius: 0;"
" border-left: none;")))
def _nowplaying_style(bg: QColor) -> str:
"""Debossed: pushed in as far as the buttons stand out. While a song is
on it is also a button (Go to Current Song): under the cursor it stands
out in the buttons' hover face, and held it sinks, darker."""
sel = "QFrame#nowPlayingBox"
hover = bg.darker(theme.HOVER_DARKER)
down = bg.darker(theme.PRESSED_DARKER)
return (theme.deboss_qss(sel, bg, radius=8)
+ f'{sel}[face="hover"] {{ {theme.emboss_edges(hover)}'
f" background: {theme.emboss_gradient(hover)}; }}"
+ f'{sel}[face="down"] {{ {theme.deboss_edges(down)}'
f" background: {theme.emboss_gradient(down, pressed=True)}; }}")
class NowPlayingPanel(QFrame):
"""The now-playing panel. A QFrame has no :pressed in a style sheet, and
its :hover can't be switched off, so the face is a property."""
clicked = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("nowPlayingBox")
self._clickable = False
self._inside = False
self._held = False
def set_clickable(self, on: bool):
self._clickable = on
self._held = self._held and on
self.setToolTip("Go to Current Song" if on else "")
self._refresh()
def _refresh(self):
face = ""
if self._clickable and self._inside:
face = "down" if self._held else "hover"
if (self.property("face") or "") != face:
self.setProperty("face", face)
self.style().unpolish(self)
self.style().polish(self)
self.update()
def enterEvent(self, event):
super().enterEvent(event)
self._inside = True
self._refresh()
def leaveEvent(self, event):
super().leaveEvent(event)
self._inside = False
self._refresh()
def mousePressEvent(self, event):
if self._clickable and event.button() == Qt.MouseButton.LeftButton:
self._held = True
self._refresh()
return
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self._held: # the press grabs the mouse: no enter/leave
self._inside = self.rect().contains(event.position().toPoint())
self._refresh()
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self._held and event.button() == Qt.MouseButton.LeftButton:
self._held = False
self._inside = self.rect().contains(event.position().toPoint())
self._refresh()
if self._inside and self._clickable:
self.clicked.emit()
return
super().mouseReleaseEvent(event)
class NowPlayingText(QWidget):
"""The now-playing panel's words (Round 130). With room for the song's
title *beside* its artist and album, the title sits on the left and the
artist over the album on its right, the group centred. Without it, the
old stack: the title over one "Artist — Album" line. Which one is decided
from the text's own widths on every resize and every new song, so the
side-by-side shape is only ever used when nothing in it is cut off.
Side by side, the words grow to fill the panel: the title up to the
whole height, artist and album up to half of it each, both by the same
share of the way from their normal size to that, as far as the width
allows (trav: "the song title should really max out that space"). The
stack keeps the normal sizes.
The normal fonts come from ``TransportBar._apply_now_playing_font``
through ``set_fonts``."""
GAP = 18 # least space between the title and the column
LINE_GAP = 2 # between stacked lines
def __init__(self, parent=None):
super().__init__(parent)
self.title = QLabel(self)
self.artist = QLabel(self) # "Artist — Album" when stacked
self.album = QLabel(self)
self._song: tuple[str, str, str] | None = None
self._lines = ("", "")
self._title_font = QFont(self.title.font())
self._line_font = QFont(self.artist.font())
self.side = False # side by side, as last arranged
self.arrange()
def set_fonts(self, title: QFont, line: QFont):
"""The normal (stacked) sizes; side by side grows from these."""
self._title_font = QFont(title)
self._line_font = QFont(line)
self.arrange()
def sizeHint(self):
return QSize(200, self.minimumSizeHint().height())
def minimumSizeHint(self):
return QSize(0, self.title.fontMetrics().height() + self.LINE_GAP
+ self.artist.fontMetrics().height())
def set_song(self, title: str, artist: str, album: str):
self._song = (title or "", artist or "", album or "")
self.arrange()
def set_lines(self, top: str, bottom: str):
"""Two fixed lines, always stacked (DJ mode, nothing playing)."""
self._song = None
self._lines = (top or "", bottom or "")
self.arrange()
def _width(self, label: QLabel, text: str) -> int:
return label.fontMetrics().horizontalAdvance(text) if text else 0
@staticmethod
def _sized(font: QFont, px: float) -> QFont:
sized = QFont(font)
sized.setPixelSize(max(1, round(px)))
return sized
@classmethod
def _largest_px(cls, font: QFont, height: int, lines: int) -> int:
"""The biggest pixel size at which ``lines`` lines fit ``height``."""
lo, hi = 1, max(2, height * 2)
while lo < hi:
mid = (lo + hi + 1) // 2
line = QFontMetrics(cls._sized(font, mid)).height()
if line * lines + cls.LINE_GAP * (lines - 1) <= height:
lo = mid
else:
hi = mid - 1
return lo
def side_fonts(self, width: int, height: int):
"""(title font, line font, gap) for side by side at this size, as
big as fits; None when even the normal sizes don't fit."""
if self._song is None:
return None
title, artist, album = self._song
right = [t for t in (artist, album) if t]
if not title or not right:
return None
base_t = QFontInfo(self._title_font).pixelSize()
base_l = QFontInfo(self._line_font).pixelSize()
top_t = max(base_t, self._largest_px(self._title_font, height, 1))
top_l = max(base_l, self._largest_px(self._line_font, height,
len(right)))
def at(share):
tf = self._sized(self._title_font,
base_t + share * (top_t - base_t))
lf = self._sized(self._line_font,
base_l + share * (top_l - base_l))
gap = max(self.GAP, round(tf.pixelSize() * 0.6))
line = QFontMetrics(lf)
need = (QFontMetrics(tf).horizontalAdvance(title) + gap
+ max(line.horizontalAdvance(t) for t in right))
return need <= width, (tf, lf, gap)
fits, fonts = at(1.0)
if fits:
return fonts
fits, fonts = at(0.0)
if not fits:
return None
lo, hi = 0.0, 1.0
for _ in range(12):
mid = (lo + hi) / 2
ok, found = at(mid)
if ok:
lo, fonts = mid, found
else:
hi = mid
return fonts
def fits_side(self, width: int) -> bool:
return self.side_fonts(width, max(1, self.height())) is not None
def resizeEvent(self, event):
super().resizeEvent(event)
self.arrange()
def arrange(self):
w, h = self.width(), self.height()
fonts = self.side_fonts(w, h)
self.side = fonts is not None
left = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
centre = Qt.AlignmentFlag.AlignCenter
if self.side:
title_font, line_font, gap = fonts
self.title.setFont(title_font)
self.artist.setFont(line_font)
self.album.setFont(line_font)
title, artist, album = self._song
self.title.setText(title)
self.artist.setText(artist)
self.album.setText(album)
tw = self._width(self.title, title)
rw = max(self._width(self.artist, artist),
self._width(self.album, album))
x = max(0, (w - (tw + gap + rw)) // 2)
self.title.setAlignment(left)
self.title.setGeometry(x, 0, tw + 1, h)
column = [lab for lab, text in ((self.artist, artist),
(self.album, album)) if text]
heights = [lab.fontMetrics().height() for lab in column]
y = (h - sum(heights) - self.LINE_GAP * (len(column) - 1)) // 2
for lab, lh in zip(column, heights):
lab.setAlignment(left)
lab.setGeometry(x + tw + gap, y, rw + 1, lh)
y += lh + self.LINE_GAP
self.artist.setVisible(bool(artist))
self.album.setVisible(bool(album))
self.title.show()
return
if self._song is not None:
title, artist, album = self._song
top = title
bottom = " — ".join(p for p in (artist, album) if p)
else:
top, bottom = self._lines
self.title.setFont(self._title_font)
self.artist.setFont(self._line_font)
# Too long for the panel: an ellipsis, never both ends cut off.
elide = Qt.TextElideMode.ElideRight
self.title.setText(self.title.fontMetrics().elidedText(top, elide, w))
self.artist.setText(self.artist.fontMetrics().elidedText(bottom,
elide, w))
self.album.hide()
th = self.title.fontMetrics().height()
ah = self.artist.fontMetrics().height()
y = (h - th - self.LINE_GAP - ah) // 2
for lab, lh in ((self.title, th), (self.artist, ah)):
lab.setAlignment(centre)
lab.setGeometry(0, y, w, lh)
lab.show()
y += lh + self.LINE_GAP
# Title sits this many points above the artist/album line, both following the
# UI-scale app font (see theme.UI_SCALES).
TITLE_PT_BUMP = 2
def _clamp_volume(value) -> float:
"""Coerce a stored preference to a logical 0..1 volume."""
try:
return max(0.0, min(1.0, float(value)))
except (TypeError, ValueError):
return 0.8
def turntable_icon(color: QColor, size: int = 18) -> QIcon:
"""DJ mode's glyph: a small turntable — plinth, platter, tonearm."""
from PyQt6.QtCore import QRectF
pix = QPixmap(round(size * 4 / 3), size)
pix.fill(Qt.GlobalColor.transparent)
p = QPainter(pix)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
s = size / 18
pen = QPen(color, 1.5 * s)
p.setPen(pen)
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawRoundedRect(QRectF(1 * s, 1.5 * s, 22 * s, 15 * s), 2 * s, 2 * s)
p.drawEllipse(QRectF(5 * s, 4 * s, 10 * s, 10 * s))
p.setBrush(color)
p.drawEllipse(QRectF(9.2 * s, 8.2 * s, 1.6 * s, 1.6 * s))
p.setBrush(Qt.BrushStyle.NoBrush)
p.drawLine(QPointF(19.5 * s, 4 * s), QPointF(19.5 * s, 10.5 * s))
p.drawLine(QPointF(19.5 * s, 10.5 * s), QPointF(16 * s, 13 * s))
p.end()
return QIcon(pix)
class FlashButton(QToolButton):
"""Transport button: dark-gray glyph that shows the highlight color
while pressed (a quick flash on click, sustained while held). A checkable
button (shuffle) keeps the highlight color while checked."""
def __init__(self, kind: str, parent=None):
super().__init__(parent)
self._kind = kind
self.setAutoRaise(True)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.pressed.connect(lambda: self._apply_icon(active=True))
self.released.connect(lambda: self._apply_icon())
self.toggled.connect(lambda _: self._apply_icon())
self.refresh_icons()
def set_kind(self, kind: str):
if kind != self._kind:
self._kind = kind
self._apply_icon(active=self.isDown())
def refresh_icons(self):
self._apply_icon(active=self.isDown())
def changeEvent(self, event):
super().changeEvent(event)
if event.type() == QEvent.Type.EnabledChange:
self._apply_icon()
def _apply_icon(self, active: bool = False):
show_active = active or (self.isCheckable() and self.isChecked())
rest = theme.icon_gray()
color = self.palette().highlight().color() if show_active else rest
if not self.isEnabled():
color = rest.lighter(160) if not theme.is_dark() else rest.darker(180)
self.setIcon(transport_icon(self._kind, color))
def _box(*widgets, bg: QColor, margins=(10, 3, 10, 3), hug=False,
height=None, split=False) -> QFrame:
"""A small rounded frame with its content centered inside.
With hug=True the frame stays at its size hint instead of stretching
to fill the row it sits in. height pins the frame's height (width is
left untouched), so several boxes can be lined up to the same height.
bg is the rounded-rectangle fill (a user-tunable grayscale).
With split=True the widgets tile the frame's interior in equal shares
instead of hugging their size hints in the middle — each widget becomes
a full-bleed tap target with its content centered in its share."""
frame = QFrame()
frame.setObjectName("transportBox")
frame.setProperty("tiles", len(widgets) > 1)
if len(widgets) > 1:
for i, widget in enumerate(widgets):
widget.setProperty("tile", "first" if i == 0 else
"last" if i == len(widgets) - 1 else "middle")
frame.setStyleSheet(_box_style(bg))
inner = QHBoxLayout(frame)
# A split box is all button, edge to edge: the face is the buttons'.
inner.setContentsMargins(*((0, 0, 0, 0) if split else margins))
if split:
inner.setSpacing(0)
for widget in widgets:
widget.setSizePolicy(QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
inner.addWidget(widget, stretch=1)
else:
inner.addStretch()
for widget in widgets:
inner.addWidget(widget)
inner.addStretch()
if height is not None:
frame.setFixedHeight(height)
if hug:
frame.setSizePolicy(QSizePolicy.Policy.Maximum,
QSizePolicy.Policy.Maximum)
return frame
class ClickJumpSlider(QSlider):
"""Horizontal slider where clicking anywhere jumps the handle straight to
the clicked spot (instead of paging one step toward it); dragging tracks
the cursor. Shared by the timeline and the volume slider."""
def __init__(self, parent=None):
super().__init__(Qt.Orientation.Horizontal, parent)
def _value_at(self, x: float) -> int:
"""The value that puts the handle's centre under ``x``: the handle
travels the groove less its own width, so a click at either end of
the groove is the end value."""
option = QStyleOptionSlider()
self.initStyleOption(option)
style = self.style()
CC, SC = QStyle.ComplexControl.CC_Slider, QStyle.SubControl
groove = style.subControlRect(CC, option, SC.SC_SliderGroove, self)
handle = style.subControlRect(CC, option, SC.SC_SliderHandle, self)
span = groove.width() - handle.width()
if span <= 0:
return QStyle.sliderValueFromPosition(
self.minimum(), self.maximum(), int(x), self.width())
pos = round(x - groove.left() - handle.width() / 2)
return QStyle.sliderValueFromPosition(
self.minimum(), self.maximum(), max(0, min(span, pos)), span)
def mousePressEvent(self, event):
if (event.button() == Qt.MouseButton.LeftButton
and self.maximum() > self.minimum()):
self.setSliderDown(True) # emits sliderPressed
self.setSliderPosition(self._value_at(event.position().x()))
event.accept()
return
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.isSliderDown():
self.setSliderPosition(self._value_at(event.position().x()))
event.accept()
return
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton and self.isSliderDown():
self.setSliderDown(False) # emits sliderReleased
event.accept()
return
super().mouseReleaseEvent(event)
class SeekSlider(ClickJumpSlider):
"""Timeline slider: clicking anywhere jumps the handle (and playhead)
straight to the clicked spot instead of paging; dragging scrubs.
Two looks (pref ``timeline``, Round 133). ``plain`` is Fusion's sunk
groove. ``waveform`` paints the groove itself: embossed like a button,
the played part a light tint of the highlight, and over that tint the
song's waveform (``lintunes/waveform.py``) in the highlight itself,
centred on the groove — revealed as the handle passes. Time maps onto
where the handle's *centre* travels, so what's under it is now. The
picture is an image in device pixels, rebuilt from the bins on any
resize, so it is exact at every width; columns hold the stretch's
peak (lighter) and RMS (solid), the bar's ends partial pixels."""
TINT = 0.45 # the fill: this much highlight over the groove
PEAK_ALPHA = 0.45 # the peaks, under the solid RMS
INSET = 2 # px between the groove's edge and the waveform
def __init__(self, parent=None):
super().__init__(parent)
self._look = "plain"
self._bins = None
self._image = None
self._image_key = None
def look(self) -> str:
return self._look
def set_look(self, look: str):
look = "waveform" if look == "waveform" else "plain"
if look != self._look:
self._look = look
self.update()
def set_bins(self, bins):
"""The playing song's bins (None: none yet, or no song)."""
self._bins = bins
self._image = self._image_key = None
self.update()
def has_bins(self) -> bool:
return self._bins is not None
def _geometry(self):
"""(option, groove, x at the start, x at the end)."""
option = QStyleOptionSlider()
self.initStyleOption(option)
style = self.style()
CC, SC = QStyle.ComplexControl.CC_Slider, QStyle.SubControl
groove = style.subControlRect(CC, option, SC.SC_SliderGroove, self)
ends = []
for value in (self.minimum(), self.maximum()):
at = QStyleOptionSlider(option)
at.sliderPosition = at.sliderValue = value
ends.append(style.subControlRect(
CC, at, SC.SC_SliderHandle, self).center().x() + 0.5)
return option, groove, ends[0], ends[1]
def waveform_image(self, x0: float, x1: float, height: float):
"""The waveform at this span, in device pixels (cached)."""
from PyQt6.QtGui import QImage
import numpy as np
from lintunes import waveform
dpr = self.devicePixelRatioF()
width_px = max(0, round((x1 - x0) * dpr))
height_px = max(0, round(height * dpr))
color = self.palette().color(QPalette.ColorRole.Highlight)
key = (width_px, height_px, self.maximum(), color.rgba(), dpr)
if self._image is not None and key == self._image_key:
return self._image
self._image_key = key
if self._bins is None or not width_px or not height_px \
or self.maximum() <= 0:
self._image = None
return None
peak, rms = waveform.columns(self._bins, self.maximum(), width_px)
half = height_px / 2
peak_cov = waveform.coverage(peak * half, height_px)
rms_cov = waveform.coverage(rms * half, height_px)
alpha = rms_cov + peak_cov * self.PEAK_ALPHA * (1 - rms_cov)
alpha *= color.alphaF()
rgba = np.empty((height_px, width_px, 4), np.uint8) # BGRA, premul.
for i, channel in enumerate((color.blue(), color.green(), color.red())):
rgba[..., i] = np.round(alpha * channel)
rgba[..., 3] = np.round(alpha * 255)
image = QImage(rgba.tobytes(), width_px, height_px, width_px * 4,
QImage.Format.Format_ARGB32_Premultiplied).copy()
image.setDevicePixelRatio(dpr)
self._image = image
return image
def paintEvent(self, event):
if self._look != "waveform":
return super().paintEvent(event)
from PyQt6.QtCore import QRectF, QPointF
from PyQt6.QtGui import QPainterPath
option, groove, x0, x1 = self._geometry()
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
rect = QRectF(groove).adjusted(0.5, 0.5, -0.5, -0.5)
radius = min(theme.BUTTON_RADIUS, rect.height() / 2)
palette = self.palette()
base = palette.color(QPalette.ColorRole.Button)
path = theme.paint_emboss(painter, rect, base, radius, like=rect.height())
if self.maximum() > self.minimum():
span = self.maximum() - self.minimum()
done = x0 + (x1 - x0) * (self.sliderPosition() - self.minimum()) / span
highlight = palette.color(QPalette.ColorRole.Highlight)
tint = QColor.fromRgbF(
*(h * self.TINT + b * (1 - self.TINT) for h, b in zip(
highlight.getRgbF()[:3], base.getRgbF()[:3])))
painter.save()
played = QPainterPath()
played.addRect(QRectF(rect.left() - 1, rect.top() - 1,
done - rect.left() + 1, rect.height() + 2))
painter.setClipPath(path.intersected(played))
theme.paint_emboss(painter, rect, tint, radius, like=rect.height())
inner = rect.adjusted(self.INSET - 0.5, self.INSET - 0.5,
-(self.INSET - 0.5), -(self.INSET - 0.5))
image = self.waveform_image(x0, x1, inner.height())
if image is not None:
painter.setClipRect(QRectF(x0, inner.top(), done - x0,
inner.height()),
Qt.ClipOperation.IntersectClip)
painter.drawImage(QPointF(x0, inner.top()), image)
painter.restore()
option.subControls = QStyle.SubControl.SC_SliderHandle
self.style().drawComplexControl(QStyle.ComplexControl.CC_Slider,
option, painter, self)
painter.end()
class BpmButton(QPushButton):
"""Tap-tempo button: tap along to the music; when the cursor leaves,
the shown bpm is saved to the playing track 3 seconds later."""
SAVE_DELAY_MS = 3000
def __init__(self, player, manager, parent=None):
super().__init__("bpm", parent)
self._player = player
self._manager = manager
self._tempo = TapTempo()
self._target_track_id: int | None = None
self.setFixedWidth(52) # shuffle and repeat's width: "bpm" or 3 digits
self.setFlat(True) # flat text inside its box, like the transport icons
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setEnabled(False)
self.setToolTip("Tap along to set this track's BPM")
self._save_timer = QTimer(self)
self._save_timer.setSingleShot(True)
self._save_timer.setInterval(self.SAVE_DELAY_MS)
self._save_timer.timeout.connect(self._save_bpm)
self.clicked.connect(self._on_tap)
player.track_changed.connect(self._on_track_changed)
def _on_track_changed(self, track):
# Track switched: any in-progress tap series no longer applies
self._reset()
self.setEnabled(track is not None)
def _on_tap(self):
self._save_timer.stop()
track = self._player.current_track
if track is None:
return
if self._tempo.tap_count == 0:
self._target_track_id = track.track_id
bpm = self._tempo.tap(time.monotonic())
self.setText(str(bpm) if bpm is not None else "...")
def leaveEvent(self, event):
if self._tempo.tap_count >= 2 and self._tempo.bpm() is not None:
self._save_timer.start()
super().leaveEvent(event)
def _save_bpm(self):
bpm = self._tempo.bpm()
track = (self._manager.library.tracks.get(self._target_track_id)
if self._target_track_id is not None else None)
if bpm is not None and track is not None:
# Writes the bpm tag to the file and records it for undo.
self._manager.edit_track_fields(track.track_id, {"bpm": bpm})
self._reset()
def _reset(self):
self._save_timer.stop()
self._tempo.reset()
self._target_track_id = None
self.setText("bpm")
class HeaderRow(ToolRow):
"""The band under the row of boxes — the toolbar's second row. It owns
two things lent to it (the sidebar's Library button and the shown
view's header) and the vertical rules every item in it follows; *where*
things go across is the bar's layout (``TransportBar.place_rows``),
which by default puts the Library button over the sidebar, the view's
header where that view starts and the seek row under the now-playing
panel."""
GAP = 6
# Above the boxes (Library button, search box) and below them to the
# lists: every item in the row stands on one floor, BOTTOM px up.
TOP_PAD = 2
BOTTOM = 5
# Text and the playhead have no hard bottom edge, so on the floor itself
# they read as sitting lower than the Library button beside them; this
# lifts them onto the button's bottom line by eye.
LIFT = 2
def __init__(self, seek: QWidget, parent=None):
super().__init__(1, parent)
self.seek = seek
self.left: QWidget | None = None
self.view_header: QWidget | None = None
self.bar = None # the TransportBar that places us
def set_left(self, widget: QWidget):
self.left = widget
widget.setParent(self)
widget.show()
self.place()
def set_view_header(self, widget: QWidget | None):
"""Show ``widget`` (a view's header) in the view's slot. The one it
replaces goes back to its own view, hidden, so it lives and dies with
that view."""
old = self.view_header
if old is widget:
return
if old is not None:
old.hide()
old.setParent(getattr(old, "header_owner", None))
self.view_header = widget
if widget is not None:
widget.setParent(self)
widget.show()
self.place()
def resizeEvent(self, event):
super().resizeEvent(event)
self.place()
def place(self):
if self.bar is not None:
self.bar.place_rows()
def put(self, widget: QWidget, x: int, width: int):
"""``widget`` across [x, x + width), standing on the floor."""
floor = self.height() - self.BOTTOM
box_h = max(0, floor - self.TOP_PAD)
if widget is self.seek:
# The playhead's knob stands on the floor, the times beside it.
drop = self._drop(self.seek)
self.seek.drop.changeSize(0, drop, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Fixed)
self.seek.layout().invalidate()
widget.setGeometry(x, self.TOP_PAD, width, box_h + drop - self.LIFT)
elif isinstance(widget, QLabel):
widget.setAlignment(Qt.AlignmentFlag.AlignLeft
| Qt.AlignmentFlag.AlignBottom)
widget.setGeometry(x, self.TOP_PAD, width,
box_h + self._drop(widget) - self.LIFT)
else:
widget.setGeometry(x, self.TOP_PAD, width, box_h)
def _drop(self, widget) -> int:
"""Text stands on its baseline: its descenders hang below the
floor, as they would below a line of print."""
return max(0, min(self.BOTTOM, widget.fontMetrics().descent() - 1))
class TransportBar(QWidget):
"""Top bar: boxed transport buttons and shuffle (left), visualizer,
now-playing text, seek slider, boxed bpm tap button (right)."""
play_clicked = pyqtSignal() # MainWindow decides what "play" means
dj_toggled = pyqtSignal(bool)
volume_level_changed = pyqtSignal(float) # the slider, 0..1 perceptual
now_playing_clicked = pyqtSignal() # Go to Current Song
speakers_clicked = pyqtSignal(QWidget) # pop the speaker menu under it
identify_clicked = pyqtSignal()
def __init__(self, player, manager, prefs, cast=None, airplay=None,
mumble=None,
parent=None):
super().__init__(parent)
self._player = player
self._prefs = prefs
self._cast = cast
self._scrubbing = False
self._current_track = None
self._dj_on = False
self.setMinimumHeight(BAR_HEIGHT)
outer = QVBoxLayout(self)
outer.setContentsMargins(0, TOP_MARGIN, 0, 0)
outer.setSpacing(ROW_GAP)
# The panel's width is set from the bar's (place_rows), so the bar's
# minimum must not come from the panel's current width, or a window
# could never shrink past the width it last had.
outer.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
self._outer = outer
# The row of boxes: toolbar row 0, placed by hand (place_rows).
self._top_row = ToolRow(0)
self._top_row.setFixedHeight(CONTROL_HEIGHT)
outer.addWidget(self._top_row)
# Rounded button boxes carry a user-tunable grayscale fill, decoupled
# from the stripe color they used to share via palette(alternate-base).
self._boxes = []
box_bg = theme.surface(prefs, "color_button")
self._prev_btn = FlashButton("previous")
self._play_btn = FlashButton("play")
self._next_btn = FlashButton("next")
# split=True turns each button into a full-bleed tap target tiling the
# bubble; the minimum widths keep the bubbles at their pre-split
# footprint (the centering stretches/margins used to pad them out).
for btn in (self._prev_btn, self._play_btn, self._next_btn):
btn.setMinimumWidth(36)
transport_box = _box(self._prev_btn, self._play_btn, self._next_btn,
bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(transport_box)
self._shuffle_btn = FlashButton("shuffle")
self._shuffle_btn.setMinimumWidth(50)
self._shuffle_btn.setCheckable(True)
self._shuffle_btn.setToolTip("Shuffle (doesn't change playlist order)")
shuffle_box = _box(self._shuffle_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(shuffle_box)
# Repeat cycles off → all → one, like iTunes': lit while on, with a
# "1" in the loop for one.
self._repeat_btn = FlashButton("repeat")
self._repeat_btn.setMinimumWidth(50)
self._repeat_btn.setCheckable(True)
self._repeat_btn.clicked.connect(self._cycle_repeat)
repeat_box = _box(self._repeat_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(repeat_box)
self._show_repeat(player.repeat_mode())
self._visualizer = VisualizerWidget(player, prefs)
self._visualizer.setFixedHeight(CONTROL_HEIGHT)
# Master output volume: a slim horizontal slider in its own slot
# between the visualizer and the timeline. The HBox centers it
# vertically, so nothing stacks above or below it (iTunes-style).
self._volume_slider = ClickJumpSlider()
self._volume_slider.setProperty("tall", True) # the scrubber's height
self._volume_slider.setRange(0, 100)
self._volume_slider.setFixedWidth(96)
# As tall as the boxes, so its groove (drawn centered) sits on the
# same midline as everything else in the row.
self._volume_slider.setFixedHeight(CONTROL_HEIGHT)
self._volume_slider.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self._volume_slider.setToolTip("Volume")
initial_volume = _clamp_volume(self._prefs.get("volume", 0.8))
self._volume_slider.setValue(round(initial_volume * 100))
player.set_volume(initial_volume)
# Persisting volume re-applies the theme (Preferences.changed), so save
# only after the user stops sliding — audio still tracks every tick.
self._volume_save_timer = QTimer(self)
self._volume_save_timer.setSingleShot(True)
self._volume_save_timer.setInterval(400)
self._volume_save_timer.timeout.connect(self._save_volume)
self._volume_slider.valueChanged.connect(self._on_volume_changed)
# White rounded now-playing panel: holds only the song title and the
# artist/album line, centered, filling the zone above the seek row.
self._now_playing = NowPlayingPanel()
self._now_playing.clicked.connect(self.now_playing_clicked)
self._apply_now_playing_bg()
np = QVBoxLayout(self._now_playing)
np.setContentsMargins(12, 6, 12, 6)
np.setSpacing(2)
self._np_text = NowPlayingText()
self._title_label = self._np_text.title
self._artist_label = self._np_text.artist
self._album_label = self._np_text.album
np.addWidget(self._np_text)
self._apply_now_playing_font()
seek = QWidget()
self._elapsed_label = QLabel("")
self._elapsed_label.setFixedWidth(50)
self._remaining_label = QLabel("")
self._remaining_label.setFixedWidth(50)
# The times sit at the timeline's two ends, centred on its line.
self._elapsed_label.setAlignment(Qt.AlignmentFlag.AlignLeft
| Qt.AlignmentFlag.AlignVCenter)
self._remaining_label.setAlignment(Qt.AlignmentFlag.AlignRight
| Qt.AlignmentFlag.AlignVCenter)
self._slider = SeekSlider()
self._slider.setProperty("tall", True) # twice Fusion's height
self._slider.setRange(0, 0)
self._slider.setFocusPolicy(Qt.FocusPolicy.NoFocus)
# The slider sets the line's height; the times centre on it.
for label in (self._elapsed_label, self._remaining_label):
label.setSizePolicy(QSizePolicy.Policy.Fixed,
QSizePolicy.Policy.Ignored)
line = QHBoxLayout()
line.setContentsMargins(0, 0, 0, 0)
line.addWidget(self._elapsed_label)
line.addWidget(self._slider, 1)
line.addWidget(self._remaining_label)
# The playhead's knob stands on the header row's floor: the row
# reaches below it by the text's descent and the line is held up by
# the same amount. HeaderRow.place sets both.
seek_col = QVBoxLayout(seek)
seek_col.setContentsMargins(0, 0, 0, 0)
seek_col.setSpacing(0)
seek_col.addStretch(1)
seek_col.addLayout(line)
seek.drop = QSpacerItem(0, 0, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Fixed)
seek_col.addSpacerItem(seek.drop)
# The now-playing panel is exactly as tall as the boxes and shares
# their top edge, so boxes, visualizer, panel and bpm read as one row;
# the seek row hangs underneath the panel, in the header row.
self._now_playing.setFixedHeight(CONTROL_HEIGHT)
# Its width is set by place_rows: by default all the room the
# controls and gaps leave.
# DJ mode's button is the far-right box (Round 94: it swapped with
# bpm, so it stays put while the window parts under it); the bpm
# tap button sits under it, in the header row.
self.dj_button = QToolButton()
self.dj_button.setObjectName("djButton")
self.dj_button.setCheckable(True)
self.dj_button.setToolTip("DJ mode")
self.dj_button.setIcon(turntable_icon(theme.icon_gray(), 22))
self.dj_button.setIconSize(QSize(30, 22))
self.dj_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.dj_button.setFixedWidth(52)
self.dj_button.toggled.connect(self._on_dj_button)
dj_box = _box(self.dj_button, bg=box_bg, margins=(3, 3, 3, 3),
hug=True, height=CONTROL_HEIGHT, split=True)
self._boxes.append(dj_box)
self._bpm_button = BpmButton(player, manager)
self._bpm_button.setObjectName("bpmHeader")
self._bpm_button.setFlat(False)
# Light / dark: not in the bar by default; drag it in from
# Customize Toolbar.
self._theme_btn = FlashButton("moon")
self._theme_btn.setMinimumWidth(50)
self._theme_btn.clicked.connect(self._toggle_dark)
theme_box = _box(self._theme_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(theme_box)
self._show_theme_kind()
# Not in the bar by default either: a speaker menu (Chromecast /
# AirPlay, lit while one plays) and Identify Track.
self._speakers_on = False
self._speakers_btn = FlashButton("speakers")
self._speakers_btn.setCheckable(True) # lit = playing on a speaker
self._speakers_btn.setToolTip("Play on a speaker")
self._speakers_btn.setMinimumWidth(50)
self._speakers_btn.clicked.connect(self._on_speakers)
speakers_box = _box(self._speakers_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._identify_btn = FlashButton("identify")
self._identify_btn.setToolTip("Identify Track")
self._identify_btn.setMinimumWidth(50)
self._identify_btn.clicked.connect(self.identify_clicked)
identify_box = _box(self._identify_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes += [speakers_box, identify_box]
# Library button · the current view's header · seek row. MainWindow
# hands over the first two (see set_sidebar_header / set_view_header)
# and says where the sidebar ends (track_split).
self._header_row = HeaderRow(seek)
self._header_strip = 34
self.set_header_height(34)
outer.addWidget(self._header_row)
# The toolbar's items (toolbar.ITEMS) and how wide each is when
# left to itself — measured now, before place_rows frees them of
# the fixed sizes they were built with.
self._items = {"transport": transport_box, "shuffle": shuffle_box,
"repeat": repeat_box, "visualizer": self._visualizer,
"volume": self._volume_slider,
"now_playing": self._now_playing, "dj": dj_box,
"theme": theme_box, "speakers": speakers_box,
"identify": identify_box,
"bpm": self._bpm_button, "seek": seek}
self._natural, self._least = {}, {}
for item, widget in self._items.items():
self._natural[item] = max(widget.sizeHint().width(), widget.minimumWidth())
self._least[item] = max(toolbar.MIN_WIDTH, widget.minimumSizeHint().width())
widget.setMinimumSize(0, 0)
widget.setMaximumSize(16777215, 16777215)
widget.hide()
self._least["now_playing"] = NOW_PLAYING_MIN
self._least["seek"] = 80
self._least["bpm"] = 40
self._spacers: dict[str, QWidget] = {}
self._rects: dict[int, dict[str, QRect]] = {0: {}, 1: {}}
self._rows = toolbar.normalize(prefs.get("toolbar"))
self._overlays: list = []
self._panel = None
self._dragging: str | None = None
self._header_row.bar = self
self._dj_box = dj_box
self._apply_dj_button_style()
self._split_widgets: tuple = ()
# Wiring
self._prev_btn.clicked.connect(player.previous)
self._play_btn.clicked.connect(self.play_clicked)
self._next_btn.clicked.connect(player.next)
self._shuffle_btn.toggled.connect(player.set_shuffle)
self._slider.sliderPressed.connect(self._on_scrub_start)
self._slider.sliderReleased.connect(self._on_scrub_end)
self._slider.sliderMoved.connect(self._on_scrub_move)
player.track_changed.connect(self._on_track_changed)
player.playing_changed.connect(self._on_playing_changed)
player.position_changed.connect(self._on_position_changed)
player.duration_changed.connect(self._on_duration_changed)
self._waveforms = None # made the first time it's wanted
self._apply_timeline_look()
if cast is not None:
# While casting, the visualizer panel *is* the cast indicator —
# there is no spectrum to show, so a click there stops casting.
# Only one of them is ever connected; the other's disconnect is
# a no-op.
self._visualizer.cast_stop_requested.connect(
lambda: (cast.disconnect(),
airplay is not None and airplay.disconnect(),
mumble is not None and mumble.disconnect()))
# ---- DJ mode ----
def _apply_dj_button_style(self):
"""The bpm button under the DJ box wears the shared face (radius 8);
the DJ button is styled by its box like shuffle and repeat."""
bg = theme.surface(self._prefs, "color_button")
self._bpm_button.setStyleSheet(theme.button_face_qss(
"QPushButton#bpmHeader", bg, radius=8,
extra=f"padding: 0; color: {theme.text_color().name()};"))
def _on_dj_button(self, on: bool):
self._on_dj_button_icon(on)
self.dj_toggled.emit(on)
def insert_shelf(self, shelf: QWidget):
"""The DJ shelf goes between the row of boxes and the header row,
so the window parts there: the boxes stay, the Library button and
everything under it slides down."""
if self._outer.indexOf(shelf) < 0:
self._outer.insertWidget(1, shelf)
def set_dj_mode(self, on: bool, titles: str = ""):
"""Grey what DJ mode doesn't use: each deck has its own play and
position, so the main transport and seek bar would only mislead."""
for widget in (self._prev_btn, self._play_btn, self._next_btn,
self._shuffle_btn, self._repeat_btn, self._slider):
widget.setEnabled(not on)
for label in (self._elapsed_label, self._remaining_label):
label.setEnabled(not on)
if self.dj_button.isChecked() != on:
self.dj_button.blockSignals(True)
self.dj_button.setChecked(on)
self.dj_button.blockSignals(False)
self._on_dj_button_icon(on)
self._dj_on = on
if on:
self._now_playing.set_clickable(False)
self.set_dj_titles(titles)
else:
self._on_track_changed(self._current_track)
def _on_dj_button_icon(self, on: bool):
color = self.palette().highlight().color() if on else theme.icon_gray()
self.dj_button.setIcon(turntable_icon(color, 22))
def volume_level(self) -> float:
"""The volume slider, 0..1 (perceptual, as Player takes it)."""
return self._volume_slider.value() / 100
def set_dj_titles(self, text: str):
self._np_text.set_lines(text or "DJ mode",
"Drag songs onto the records" if not text
else "DJ mode")
# ---- repeat ----
_REPEAT_TIPS = {"off": "Repeat: off", "all": "Repeat: all",
"one": "Repeat: this song"}
def _cycle_repeat(self):
modes = REPEAT_MODES
mode = modes[(modes.index(self._player.repeat_mode()) + 1) % len(modes)]
self._player.set_repeat(mode)
self._show_repeat(mode)
def _show_repeat(self, mode: str):
# The click already toggled the check; the mode decides it.
self._repeat_btn.setChecked(mode != "off")
self._repeat_btn.set_kind("repeat_one" if mode == "one" else "repeat")
self._repeat_btn.setToolTip(self._REPEAT_TIPS[mode])
# ---- the header row ----
def set_sidebar_header(self, widget: QWidget):
"""The Library button strip, laid over the sidebar's width."""
self._header_row.set_left(widget)
self.set_header_height(self._header_strip)
def set_view_header(self, widget: QWidget | None):
"""The shown view's header (search box, playlist name), between the
Library button and the seek row."""
self._header_row.set_view_header(widget)
def set_header_height(self, height: int):
"""``height`` is the UI scale's header strip: the Library button's
own height plus its old 2px margins; the floor gap is added on."""
row = self._header_row
self._header_strip = height
box = height - 4
if row.left is not None:
# Never shorter than the Library button can be drawn at this
# font, or it would poke through the floor.
box = max(box, row.left.minimumSizeHint().height())
row.setFixedHeight(box + HeaderRow.TOP_PAD + HeaderRow.BOTTOM)
def track_split(self, lists: QWidget, content: QWidget):
"""Keep the header row's Library button exactly over ``lists`` (the
playlist list, scrollbar included) and the view header starting where
``content`` does, as the splitter or window moves them."""
self._split_widgets = (lists, content)
for widget in self._split_widgets:
widget.installEventFilter(self)
self._place_header()
def eventFilter(self, obj, event):
if event.type() in (QEvent.Type.Resize, QEvent.Type.Move):
self.place_rows()
return super().eventFilter(obj, event)
def resizeEvent(self, event):
super().resizeEvent(event)
self.place_rows()
# ---- the toolbar's layout (gui/toolbar.py) ----
def _widget(self, item: str) -> QWidget | None:
base = toolbar.base_id(item)
if base == "library":
return self._header_row.left
if base == "view":
return self._header_row.view_header
if base in toolbar.SPACERS:
if item not in self._spacers:
self._spacers[item] = toolbar.Spacer()
return self._spacers[item]
return self._items.get(base)
def _width_of(self, item: str) -> int:
base = toolbar.base_id(item)
if base == "space":
return toolbar.SPACE_WIDTH
if base == "library":
left = self._header_row.left
return left.sizeHint().width() if left is not None else 120
return self._natural.get(base, toolbar.MIN_WIDTH)
def _least_of(self, item: str) -> int:
return self._least.get(toolbar.base_id(item), toolbar.MIN_WIDTH)
def _slots(self, row: int) -> list:
"""The layout engine's slots for ``row``. Row 1's automatic items
follow what they belong under: the sidebar, the view, row 0."""
split = self._split()
partners = toolbar.column_partners(self._rows)
slots = []
for entry in self._rows[row]:
item, size = entry["id"], entry.get("size", "auto")
base = toolbar.base_id(item)
least = self._least_of(item)
if size == "exact":
slots.append(Slot(item, width=max(least, entry["width"]), min_width=least))
continue
if size == "fill":
slots.append(Slot(item, fill=True, min_width=least))
continue
above = self._rects[0].get(partners.get(item, ""))
if row == 1 and base == "library" and split is not None:
slots.append(Slot(item, anchor=(split[0], split[1]), min_width=least))
elif row == 1 and above is not None:
slots.append(Slot(item, anchor=(above.left(), above.right() + 1),
min_width=least))
elif base == "view":
start = split[2] if (row == 1 and split is not None) else None
slots.append(Slot(item, fill=True, start=start, min_width=least))
elif base in toolbar.AUTO_FILL or base == "seek":
slots.append(Slot(item, fill=True, min_width=least))
else:
slots.append(Slot(item, width=self._width_of(item), min_width=least))
return slots
def _split(self):
"""(list left, list right, content left) in the bar, or None."""
if not getattr(self, "_split_widgets", ()):
return None
lists, content = self._split_widgets
row = self._header_row
def x_of(widget, x=0): # siblings, not ancestors: go via global
return row.mapFromGlobal(widget.mapToGlobal(QPoint(x, 0))).x()
return x_of(lists), x_of(lists, lists.width()), x_of(content)
_ROW_SPACING = {0: (GAP, GAP), 1: (8, HeaderRow.GAP)} # (margin, gap)
def place_rows(self):
"""Put every item where the layout says, row 0 first (row 1's
automatic items line up under it)."""
if not hasattr(self, "_rows"):
return # still being built
width = self.width()
shown = set()
for row, widget_row in ((0, self._top_row), (1, self._header_row)):
margin, gap = self._ROW_SPACING[row]
spots = toolbar.lay_out(self._slots(row), width, margin, gap)
rects = {}
for entry in self._rows[row]:
item = entry["id"]
widget = self._widget(item)
if widget is None or item not in spots:
continue
x, w = spots[item]
widget_row.adopt(widget)
shown.add(widget)
if row == 1:
self._header_row.put(widget, x, w)
elif widget is self._header_row.seek:
widget.drop.changeSize(0, 0, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Fixed)
widget.layout().invalidate()
h = min(CONTROL_HEIGHT, 34)
widget.setGeometry(x, (CONTROL_HEIGHT - h) // 2, w, h)
else:
widget.setGeometry(x, 0, w, CONTROL_HEIGHT)
rects[item] = widget.geometry()
self._rects[row] = rects
for widget in list(self._items.values()) + list(self._spacers.values()):
if widget not in shown:
widget.hide()
for overlay in self._overlays:
overlay.setGeometry(overlay.parentWidget().rect())
overlay.raise_()
overlay.update()
def minimumSizeHint(self):
hint = super().minimumSizeHint()
if not hasattr(self, "_rows"):
return hint
hint.setWidth(max(toolbar.min_row_width(self._slots(r), *self._ROW_SPACING[r])
for r in (0, 1)))
return hint
def sizeHint(self):
hint = super().sizeHint()
if hasattr(self, "_rows"):
hint.setWidth(self.minimumSizeHint().width() + NOW_PLAYING_MIN)
return hint
def _place_header(self):
self.place_rows()
def apply_toolbar(self, rows=None):
"""Lay out ``rows`` (or Preferences' toolbar) — live, not saved."""
rows = toolbar.normalize(self._prefs.get("toolbar") if rows is None else rows)
if rows != self._rows:
self._rows = rows
self.updateGeometry()
self.place_rows()
if self._panel is not None:
self._panel.show_items(toolbar.palette_ids(self._rows))
def _save_toolbar(self, rows):
self.apply_toolbar(rows)
self._prefs.set("toolbar", rows)
# ---- customize mode ----
def is_customizing(self) -> bool:
return self._panel is not None
def set_customizing(self, on: bool):
if on == self.is_customizing():
return
if on:
self._overlays = [toolbar.CustomizeOverlay(row, self)
for row in (self._top_row, self._header_row)]
self._panel = toolbar.CustomizePanel(self)
self._panel.done.connect(lambda: self.set_customizing(False))
self._panel.restore.connect(
lambda: self._save_toolbar(toolbar.default_config()))
self._panel.show_items(toolbar.palette_ids(self._rows))
self._outer.addWidget(self._panel)
else:
for overlay in self._overlays:
overlay.deleteLater()
self._overlays = []
self._outer.removeWidget(self._panel)
self._panel.deleteLater()
self._panel = None
self.place_rows()
def contextMenuEvent(self, event):
if self.is_customizing():
return
from PyQt6.QtWidgets import QMenu
menu = QMenu(self)
menu.addAction("Customize Toolbar…", lambda: self.set_customizing(True))
menu.exec(event.globalPos())
def item_rects(self, row: int) -> dict:
return {k: v for k, v in self._rects[row].items() if k != self._dragging}
def start_drag(self, item: str, source: QWidget, from_palette: bool = False):
widget = self._widget(item) if not from_palette else source
drag = toolbar.make_drag(source, item)
if widget is not None and widget.isVisible():
drag.setPixmap(toolbar.drag_pixmap(widget))
self._dragging = None if from_palette else item
for overlay in self._overlays:
overlay.update()
try:
result = drag.exec(Qt.DropAction.MoveAction)
finally:
self._dragging = None
if not from_palette and result == Qt.DropAction.IgnoreAction:
self.remove_item(item) # dropped off the rows
self.place_rows()
def drop_index(self, row: int, item: str, x: int) -> int:
rects = [r for k, r in self._rects[row].items() if k != item]
return sum(1 for r in rects if r.center().x() < x)
def caret_x(self, row: int, index: int) -> int:
rects = sorted((r for k, r in self._rects[row].items() if k != self._dragging),
key=lambda r: r.left())
if not rects:
return self._ROW_SPACING[row][0]
if index <= 0:
return max(1, rects[0].left() - 3)
if index >= len(rects):
return min(self.width() - 2, rects[-1].right() + 3)
return (rects[index - 1].right() + rects[index].left()) // 2
def drop_item(self, item: str, row: int, index: int):
if toolbar.find(self._rows, item) is None:
item = toolbar.new_instance(self._rows, item)
self._save_toolbar(toolbar.move(self._rows, item, row, index))
def remove_item(self, item: str):
self._save_toolbar(toolbar.remove(self._rows, item))
def resize_item(self, item: str, width: int, final: bool):
width = max(self._least_of(item), int(width))
rows = toolbar.set_size(self._rows, item, "exact", width)
if final:
self._save_toolbar(rows)
else:
self.apply_toolbar(rows)
def item_menu(self, item: str, rect: QRect, pos):
where = toolbar.find(self._rows, item)
if where is None:
return
entry = self._rows[where[0]][where[1]]
menu, choices = toolbar.context_menu(self, item, entry, rect.width())
chosen = menu.exec(pos)
choice = choices.get(chosen)
if choice == "remove":
self.remove_item(item)
elif choice is not None:
self._save_toolbar(toolbar.set_size(self._rows, item, *choice))
# ---- speakers ----
def _on_speakers(self):
self._speakers_btn.setChecked(self._speakers_on) # a click isn't a toggle
self.speakers_clicked.emit(self._speakers_btn)
def set_speakers_active(self, on: bool, name: str = ""):
"""Lit while playing on a Chromecast or AirPlay speaker."""
self._speakers_on = on
self._speakers_btn.setChecked(on)
self._speakers_btn.setToolTip(f"Playing on {name}" if on and name
else "Play on a speaker")
# ---- light / dark ----
def _toggle_dark(self):
self._prefs.set("dark_mode", theme.mode(self._prefs) != "dark")
def _show_theme_kind(self):
dark = theme.mode(self._prefs) == "dark"
self._theme_btn.set_kind("sun" if dark else "moon")
self._theme_btn.setToolTip("Light mode" if dark else "Dark mode")
def refresh_theme(self):
"""Re-apply everything driven by Preferences: button glyphs (highlight
color), the tunable grayscale button boxes, and the now-playing panel
background + text color."""
for button in (self._prev_btn, self._play_btn, self._next_btn,
self._shuffle_btn, self._repeat_btn):
button.refresh_icons()
box_bg = theme.surface(self._prefs, "color_button")
for box in self._boxes:
box.setStyleSheet(_box_style(box_bg))
self._apply_now_playing_bg()
self._apply_now_playing_font()
self._apply_timeline_look()
self._apply_dj_button_style()
self._on_dj_button_icon(self.dj_button.isChecked())
for button in (self._theme_btn, self._speakers_btn, self._identify_btn):
button.refresh_icons()
self._show_theme_kind()
self._visualizer.update() # dim-mode bar color may have changed
self.apply_toolbar()
def _apply_now_playing_bg(self):
bg = theme.surface(self._prefs, "color_now_playing_bg")
self._now_playing.setStyleSheet(_nowplaying_style(bg))
def _on_volume_changed(self, value: int):
"""Slider moved: update audio live, defer the (theme-reapplying) save."""
self._player.set_volume(value / 100)
self.volume_level_changed.emit(value / 100)
self._volume_save_timer.start()
def _save_volume(self):
self._prefs.set("volume", self._volume_slider.value() / 100)
def _apply_now_playing_font(self):
"""Set the now-playing labels to Century Gothic (or the user's chosen
substitute); title slightly larger than artist/album. Sizes track the
app font so they follow the UI-scale preference; the text color is the
user-tunable grayscale (black by default)."""
family = theme.now_playing_font_family(self._prefs)
base_pt = self.font().pointSize()
text_color = theme.gray(theme.gray_value(self._prefs, "color_now_playing_text"))
fonts = []
for delta in (TITLE_PT_BUMP, 0):
font = QFont(family) if family else QFont(self.font())
font.setPointSize(max(1, base_pt + delta))
fonts.append(font)
for label in (self._title_label, self._artist_label,
self._album_label):
label.setStyleSheet(f"color: {text_color.name()};")
self._np_text.set_fonts(*fonts)
# ---- player events ----
def _on_track_changed(self, track):
self._current_track = track
self._request_waveform()
self._now_playing.set_clickable(track is not None and not self._dj_on)
if self._dj_on:
return # the panel names the decks' songs meanwhile
if track is None:
self._np_text.set_lines("", "")
self._slider.setRange(0, 0)
self._elapsed_label.setText("")
self._remaining_label.setText("")
return
self._np_text.set_song(track.name, track.artist, track.album)
def _on_playing_changed(self, playing):
self._play_btn.set_kind("pause" if playing else "play")
def _on_position_changed(self, position):
if not self._scrubbing:
self._slider.setValue(position)
self._update_time_labels(position)
def _on_duration_changed(self, duration):
self._slider.setRange(0, max(0, duration))
def _update_time_labels(self, position):
duration = self._slider.maximum()
self._elapsed_label.setText(format_time(position) or "0:00")
if duration > 0:
self._remaining_label.setText("-" + (format_time(duration - position) or "0:00"))
# ---- the timeline's look (Round 133) ----
def _apply_timeline_look(self):
look = self._prefs.get("timeline", "plain")
was = self._slider.look()
self._slider.set_look(look)
if self._slider.look() != was:
self._request_waveform()
def _request_waveform(self):
"""Ask for the playing song's waveform — only while it's shown."""
track = getattr(self, "_current_track", None)
path = getattr(track, "location", None) if track is not None else None
self._waveform_path = path
self._slider.set_bins(None)
if not path or self._slider.look() != "waveform":
return
from lintunes import waveform
if self._waveforms is None:
if not waveform.ffmpeg_available():
return # plain-looking groove; nothing to draw
self._waveforms = waveform.WaveformLoader(parent=self)
self._waveforms.ready.connect(self._on_waveform_ready)
self._waveforms.request(str(path))
def _on_waveform_ready(self, path, bins):
if path == str(self._waveform_path or ""):
self._slider.set_bins(bins)
# ---- scrubbing ----
def _on_scrub_start(self):
self._scrubbing = True
def _on_scrub_move(self, value):
self._update_time_labels(value)
def _on_scrub_end(self):
self._scrubbing = False
self._player.seek(self._slider.value())