v0.70.0: customize the toolbar — drag items in and out, resize, fill or exact size; a light/dark button

This commit is contained in:
2026-10-19 22:50:40 -07:00
parent a5d4ab27c6
commit aea8f82e74
8 changed files with 1081 additions and 121 deletions
+19
View File
@@ -192,6 +192,25 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
share of the width. Since the Library button left the share of the width. Since the Library button left the
sidebar, `MainWindow` must hand it the first focus, or the playlist tree sidebar, `MainWindow` must hand it the first focus, or the playlist tree
takes it and opens its first playlist at startup. takes it and opens its first playlist at startup.
**Both rows are a customizable toolbar** (Round 101, `gui/toolbar.py`,
View › Customize Toolbar… or a right-click on the bar): preferences'
`toolbar` is two rows of `{id, size: auto|fill|exact, width}`, and
`TransportBar.place_rows` lays them out by hand with the pure
`toolbar.lay_out` (fills share the leftover; an *anchored* slot sits at
its anchor unless the items before it need the room). "auto" is what
reproduces the old bar: the now-playing panel fills row 0, and in row 1
the Library button spans the sidebar, the view's header starts at the
view and seek/bpm sit under the now-playing panel/DJ box
(`ANCHORED_UNDER`) — the Round 69 geometry tests run against the
default. Widgets are measured once (`_natural`/`_least`) and then freed
of their fixed sizes, so a box can go in either row. Customize mode lays
a `CustomizeOverlay` over each row (it takes every click; edges are
resize handles → exact width; right-click → Automatic / Fill space /
Exact size) and a `CustomizePanel` under them (items not shown, both
spacers always; Restore Defaults). Moves are `QDrag`s with
`toolbar.MIME`; a toolbar item dropped anywhere that refuses it is
removed. Library and the view's header are row-1-only and can't be removed.
The light/dark button (`theme` item) is not in the default rows.
The transport-bar visualizer tile (`gui/visualizer.py`, Round 86): a The transport-bar visualizer tile (`gui/visualizer.py`, Round 86): a
click opens it big, and while big the tile stays blank; hovering paints click opens it big, and while big the tile stays blank; hovering paints
two controls over it — a colour wheel (left: colour / gray / off) and ▲/▼ two controls over it — a colour wheel (left: colour / gray / off) and ▲/▼
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux.""" """LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.69.0" __version__ = "0.70.0"
+24
View File
@@ -157,6 +157,28 @@ def _airplay(p, color):
])) ]))
def _sun(p, color):
"""Light mode's glyph: a disc and eight rays."""
import math
p.drawEllipse(QPointF(10, 10), 3.6, 3.6)
pen = QPen(color, 1.8)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
p.setPen(pen)
for i in range(8):
a = i * math.pi / 4
p.drawLine(QPointF(10 + 6 * math.cos(a), 10 + 6 * math.sin(a)),
QPointF(10 + 8.4 * math.cos(a), 10 + 8.4 * math.sin(a)))
def _moon(p, _color):
"""Dark mode's glyph: a crescent."""
disc = QPainterPath()
disc.addEllipse(QPointF(10, 10), 7.5, 7.5)
bite = QPainterPath()
bite.addEllipse(QPointF(13.5, 7), 6.5, 6.5)
p.drawPath(disc.subtracted(bite))
_DRAWERS = { _DRAWERS = {
"play": _play, "play": _play,
"pause": _pause, "pause": _pause,
@@ -167,4 +189,6 @@ _DRAWERS = {
"repeat_one": _repeat_one, "repeat_one": _repeat_one,
"cast": _cast, "cast": _cast,
"airplay": _airplay, "airplay": _airplay,
"sun": _sun,
"moon": _moon,
} }
+3
View File
@@ -498,6 +498,9 @@ class MainWindow(QMainWindow):
self._dj_action.setCheckable(True) self._dj_action.setCheckable(True)
self._dj_action.toggled.connect(self.set_dj_mode) self._dj_action.toggled.connect(self.set_dj_mode)
view_menu.addAction(self._dj_action) view_menu.addAction(self._dj_action)
view_menu.addSeparator()
view_menu.addAction("Customize Toolbar…",
lambda: self._transport.set_customizing(True))
track_menu = bar.addMenu("&Track") track_menu = bar.addMenu("&Track")
self._add_action(track_menu, "Get Info", "Ctrl+I", self._info_for_current_view) self._add_action(track_menu, "Get Info", "Ctrl+I", self._info_for_current_view)
+550
View File
@@ -0,0 +1,550 @@
"""The top two rows as a toolbar trav can rearrange (Round 101).
Like Finder's or Preview's Customize Toolbar: View › Customize Toolbar…
(or a right-click on the bar) puts the rows in *customize mode*. Every item
gets an outline and a handle on each side; dragging an item moves it
(within its row or to the other), dragging it off the rows removes it, and
a palette under the rows holds what isn't shown, to drag back in. Dragging
a handle sets an exact width; a right-click chooses Automatic, Fill space
or Exact size.
The layout is ``preferences.json``'s ``toolbar``: two rows of entries
``{"id", "size": "auto"|"fill"|"exact", "width"}``. ``DEFAULT_ROWS`` is the
bar as it was before this existed, and "auto" is what reproduces it: the
now-playing panel fills the row, the Library button spans the sidebar, the
view's header starts where the view does, the seek row sits under the
now-playing panel and the bpm button under the DJ box (``ANCHORED_UNDER``).
Spacers can appear any number of times, so their ids carry an instance
number (``space:2``).
Everything here but the widgets at the bottom is pure, so the rules are
tested without a window.
"""
import copy
import itertools
from dataclasses import dataclass
from PyQt6.QtCore import Qt, QMimeData, QPoint, QRectF, pyqtSignal
from PyQt6.QtGui import QColor, QDrag, QPainter, QPen, QPixmap
from PyQt6.QtWidgets import (QHBoxLayout, QLabel, QMenu, QPushButton,
QVBoxLayout, QWidget, QFrame, QSizePolicy)
# id → (label, rows it may sit in, removable)
ITEMS = {
"transport": ("Previous · Play · Next", (0, 1), True),
"shuffle": ("Shuffle", (0, 1), True),
"repeat": ("Repeat", (0, 1), True),
"visualizer": ("Visualizer", (0, 1), True),
"volume": ("Volume", (0, 1), True),
"now_playing": ("Now Playing", (0, 1), True),
"dj": ("DJ Mode", (0, 1), True),
"theme": ("Light / Dark", (0, 1), True),
"library": ("Library", (1,), False),
"view": ("Search / Playlist Name", (1,), False),
"seek": ("Seek Bar", (0, 1), True),
"bpm": ("Tap BPM", (0, 1), True),
"space": ("Space", (0, 1), True),
"flex": ("Flexible Space", (0, 1), True),
}
SPACERS = ("space", "flex")
# Items whose "auto" size is to fill what the row leaves.
AUTO_FILL = {"now_playing", "view", "flex"}
# In the second row, "auto" puts these exactly under that first-row item.
ANCHORED_UNDER = {"seek": "now_playing", "bpm": "dj"}
SPACE_WIDTH = 24
MIN_WIDTH = 16
SIZES = ("auto", "fill", "exact")
DEFAULT_ROWS = [
["transport", "shuffle", "repeat", "visualizer", "volume", "now_playing", "dj"],
["library", "view", "seek", "bpm"],
]
MIME = "application/x-lintunes-toolbar-item"
def base_id(item_id: str) -> str:
return item_id.split(":", 1)[0]
def default_config() -> list[list[dict]]:
return [[{"id": i, "size": "auto"} for i in row] for row in DEFAULT_ROWS]
def normalize(saved) -> list[list[dict]]:
"""A saved layout made safe: two rows, known ids only, each item once
(spacers once per instance), every item in a row it may sit in, and the
items that can't be removed present."""
if not (isinstance(saved, list) and len(saved) == 2
and all(isinstance(r, list) for r in saved)):
return default_config()
seen = set()
rows: list[list[dict]] = [[], []]
for r, row in enumerate(saved):
for entry in row:
if isinstance(entry, str):
entry = {"id": entry}
if not isinstance(entry, dict):
continue
item = str(entry.get("id", ""))
known = ITEMS.get(base_id(item))
if known is None or item in seen or r not in known[1]:
continue
seen.add(item)
size = entry.get("size", "auto")
clean = {"id": item, "size": size if size in SIZES else "auto"}
if clean["size"] == "exact":
try:
clean["width"] = max(MIN_WIDTH, int(entry.get("width", 0)))
except (TypeError, ValueError):
clean["size"] = "auto"
rows[r].append(clean)
for item, (_label, allowed, removable) in ITEMS.items():
if not removable and item not in seen:
rows[allowed[0]].append({"id": item, "size": "auto"})
return rows
def shown_ids(rows) -> set[str]:
return {e["id"] for row in rows for e in row}
def palette_ids(rows) -> list[str]:
"""What the palette offers: everything not shown, and always both
spacers (dragging one in makes a new instance)."""
shown = {base_id(i) for i in shown_ids(rows)}
return [i for i in ITEMS if i in SPACERS or (i not in shown)]
def new_instance(rows, item: str) -> str:
"""The id a palette item gets when dropped: a spacer is numbered."""
if item not in SPACERS:
return item
taken = shown_ids(rows)
for n in itertools.count(1):
candidate = f"{item}:{n}"
if candidate not in taken:
return candidate
def find(rows, item: str):
for r, row in enumerate(rows):
for i, entry in enumerate(row):
if entry["id"] == item:
return r, i
return None
def can_place(item: str, row: int) -> bool:
known = ITEMS.get(base_id(item))
return known is not None and row in known[1]
def move(rows, item: str, row: int, index: int):
"""``rows`` with ``item`` at ``index`` of ``row`` (taken from wherever
it was, or new). ``index`` counts the row without the item. Unchanged
when the item can't sit in that row."""
if not can_place(item, row):
return rows
rows = copy.deepcopy(rows)
where = find(rows, item)
entry = {"id": item, "size": "auto"}
if where is not None:
entry = rows[where[0]].pop(where[1])
if where[0] != row:
entry = {"id": item, "size": "auto"} # a new row, a fresh size
index = max(0, min(index, len(rows[row])))
rows[row].insert(index, entry)
return rows
def remove(rows, item: str):
"""``rows`` without ``item``, unless it can't be removed."""
known = ITEMS.get(base_id(item))
if known is None or not known[2]:
return rows
rows = copy.deepcopy(rows)
where = find(rows, item)
if where is not None:
rows[where[0]].pop(where[1])
return rows
def set_size(rows, item: str, size: str, width: int | None = None):
rows = copy.deepcopy(rows)
where = find(rows, item)
if where is None or size not in SIZES:
return rows
entry = rows[where[0]][where[1]]
entry["size"] = size
if size == "exact":
entry["width"] = max(MIN_WIDTH, int(width or MIN_WIDTH))
else:
entry.pop("width", None)
return rows
# ---- the layout engine ----
@dataclass
class Slot:
key: str
width: int = 0 # when not fill
fill: bool = False
min_width: int = MIN_WIDTH
anchor: tuple[int, int] | None = None # (left, right) exclusive, hard
start: int | None = None # a soft left edge (the view's header)
def lay_out(slots: list[Slot], width: int, margin: int, gap: int) -> dict:
"""{key: (x, w)} for one row. Items go left to right, ``gap`` apart and
``margin`` in from both ends; fills share what's left equally. An
anchored slot sits at its anchor, the items before it filling up to it,
unless the items before it need that room — then it is just a fixed
slot of the anchor's width. A ``start`` moves the cursor right to it
when nothing is waiting."""
out = {}
cursor = margin
pending: list[Slot] = []
def need(items):
return sum(s.min_width if s.fill else s.width for s in items) \
+ gap * len(items)
def flush(end):
nonlocal cursor
if not pending:
return
fixed = sum(s.width for s in pending if not s.fill)
fills = [s for s in pending if s.fill]
room = end - cursor - fixed - gap * (len(pending) - 1)
share, extra = divmod(max(0, room), len(fills)) if fills else (0, 0)
x = cursor
for s in pending:
if s.fill:
w = share + (extra if s is fills[-1] else 0)
w = max(s.min_width, w)
else:
w = s.width
out[s.key] = (x, w)
x += w + gap
cursor = x
pending.clear()
for slot in slots:
if slot.start is not None and not pending:
cursor = max(cursor, slot.start)
if slot.anchor is not None:
left, right = slot.anchor
left = max(left, cursor + need(pending))
# An anchor narrower than the item's minimum is still its place.
if right - left >= min(slot.min_width, right - slot.anchor[0]):
flush(left - gap)
out[slot.key] = (left, right - left)
cursor = right + gap
continue
slot = Slot(slot.key, width=max(slot.min_width, right - slot.anchor[0]),
min_width=slot.min_width)
pending.append(slot)
flush(width - margin)
return out
def min_row_width(slots: list[Slot], margin: int, gap: int) -> int:
"""The narrowest a row can be with nothing overlapping, anchors aside."""
if not slots:
return 2 * margin
return (sum(s.min_width if (s.fill or s.anchor) else s.width for s in slots)
+ gap * (len(slots) - 1) + 2 * margin)
# ---- widgets ----
class Spacer(QWidget):
"""A space or flexible space: nothing, except an outline while
customizing (the overlay draws that)."""
class ToolRow(QWidget):
"""One row of the toolbar, placed by hand from the layout engine:
``TransportBar.place_rows`` hands it ``{widget: QRect}``."""
def __init__(self, index: int, parent=None):
super().__init__(parent)
self.index = index
def adopt(self, widget: QWidget):
if widget.parent() is not self:
widget.setParent(self)
widget.show()
class CustomizeOverlay(QWidget):
"""Laid over one row while customizing: draws each item's outline and
handles, and takes every mouse event, so nothing under it is pressed.
The bar (``host``) owns the layout; this reports gestures to it."""
HANDLE = 6 # px each side of an item that grabs as a handle
def __init__(self, row: ToolRow, host):
super().__init__(row)
self._row = row
self._host = host
self.setAcceptDrops(True)
self.setMouseTracking(True)
self._press: QPoint | None = None
self._resizing: tuple[str, str, int, int] | None = None # id, side, x0, w0
self._grab: str | None = None
self.drop_index: int | None = None
self.setGeometry(row.rect())
self.raise_()
self.show()
# what's under the cursor
def _item_at(self, pos: QPoint):
for item, rect in self._host.item_rects(self._row.index).items():
if rect.adjusted(-self.HANDLE, 0, self.HANDLE, 0).contains(pos):
if pos.x() <= rect.left() + self.HANDLE:
return item, "left", rect
if pos.x() >= rect.right() - self.HANDLE:
return item, "right", rect
return item, None, rect
return None, None, None
def mousePressEvent(self, event):
if event.button() != Qt.MouseButton.LeftButton:
return
item, side, rect = self._item_at(event.position().toPoint())
if item is None:
return
if side is not None:
self._resizing = (item, side, event.position().toPoint().x(), rect.width())
else:
self._grab = item
self._press = event.position().toPoint()
def mouseMoveEvent(self, event):
pos = event.position().toPoint()
if self._resizing is not None:
item, side, x0, w0 = self._resizing
dx = pos.x() - x0
width = w0 + (dx if side == "right" else -dx)
self._host.resize_item(item, width, final=False)
return
if self._grab is not None and self._press is not None:
if (pos - self._press).manhattanLength() >= 6:
item, self._grab, self._press = self._grab, None, None
self._host.start_drag(item, self)
return
_item, side, _rect = self._item_at(pos)
self.setCursor(Qt.CursorShape.SizeHorCursor if side
else Qt.CursorShape.OpenHandCursor if _item
else Qt.CursorShape.ArrowCursor)
def mouseReleaseEvent(self, event):
if self._resizing is not None:
item, side, x0, w0 = self._resizing
dx = event.position().toPoint().x() - x0
self._resizing = None
self._host.resize_item(item, w0 + (dx if side == "right" else -dx),
final=True)
self._grab = self._press = None
def contextMenuEvent(self, event):
item, _side, rect = self._item_at(event.pos())
if item is None:
return
self._host.item_menu(item, rect, event.globalPos())
# drops
def dragEnterEvent(self, event):
self.dragMoveEvent(event)
def dragMoveEvent(self, event):
item = _dragged(event)
if item is None or not can_place(item, self._row.index):
self.drop_index = None
event.ignore()
self.update()
return
self.drop_index = self._host.drop_index(self._row.index, item,
event.position().toPoint().x())
event.setDropAction(Qt.DropAction.MoveAction)
event.accept()
self.update()
def dragLeaveEvent(self, _event):
self.drop_index = None
self.update()
def dropEvent(self, event):
item = _dragged(event)
index = self.drop_index
self.drop_index = None
if item is None or index is None:
event.ignore()
return
event.setDropAction(Qt.DropAction.MoveAction)
event.accept()
self._host.drop_item(item, self._row.index, index)
def paintEvent(self, _event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
lit = self.palette().highlight().color()
rects = self._host.item_rects(self._row.index)
for item, rect in rects.items():
r = QRectF(rect).adjusted(0.5, 0.5, -0.5, -0.5)
veil = QColor(lit)
veil.setAlpha(28)
p.setBrush(veil)
pen = QPen(lit, 1, Qt.PenStyle.DashLine)
p.setPen(pen)
p.drawRoundedRect(r, 6, 6)
if base_id(item) in SPACERS:
p.setPen(lit)
p.drawText(rect, Qt.AlignmentFlag.AlignCenter,
"⇔" if base_id(item) == "flex" else "␣")
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(lit)
h = min(rect.height() - 8, 22)
for x in (rect.left() + 1, rect.right() - 3):
p.drawRoundedRect(QRectF(x, rect.center().y() - h / 2, 3, h), 1.5, 1.5)
if self.drop_index is not None:
x = self._host.caret_x(self._row.index, self.drop_index)
p.setPen(QPen(lit, 3))
p.drawLine(x, 2, x, self.height() - 2)
p.end()
def _dragged(event) -> str | None:
data = event.mimeData()
if data is None or not data.hasFormat(MIME):
return None
return bytes(data.data(MIME)).decode()
class PaletteChip(QPushButton):
"""One item in the palette, dragged into the rows to add it."""
def __init__(self, item: str, host, parent=None):
super().__init__(ITEMS[item][0], parent)
self.item = item
self._host = host
self._press = None
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setCursor(Qt.CursorShape.OpenHandCursor)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._press = event.position().toPoint()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self._press is not None and \
(event.position().toPoint() - self._press).manhattanLength() >= 6:
self._press = None
self.setDown(False)
self._host.start_drag(self.item, self, from_palette=True)
return
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
self._press = None
super().mouseReleaseEvent(event)
class CustomizePanel(QFrame):
"""Under the rows while customizing: the items not shown, a hint, and
Restore Defaults / Done. Dropping a toolbar item here removes it."""
done = pyqtSignal()
restore = pyqtSignal()
def __init__(self, host, parent=None):
super().__init__(parent)
self._host = host
self.setObjectName("customizePanel")
self.setAcceptDrops(True)
self.setFrameShape(QFrame.Shape.StyledPanel)
column = QVBoxLayout(self)
column.setContentsMargins(12, 8, 12, 8)
hint = QLabel("Drag items into the toolbar, or off it to remove them. "
"Drag an item's edge to resize it; right-click for "
"Automatic, Fill space or Exact size.")
hint.setWordWrap(True)
column.addWidget(hint)
buttons = QHBoxLayout()
self._chips = QHBoxLayout()
self._chips.setSpacing(6)
buttons.addLayout(self._chips)
buttons.addStretch(1)
reset = QPushButton("Restore Defaults")
reset.clicked.connect(self.restore)
finish = QPushButton("Done")
finish.setDefault(True)
finish.clicked.connect(self.done)
buttons.addWidget(reset)
buttons.addWidget(finish)
column.addLayout(buttons)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
def show_items(self, items: list[str]):
while self._chips.count():
got = self._chips.takeAt(0)
if got.widget() is not None:
got.widget().deleteLater()
for item in items:
self._chips.addWidget(PaletteChip(item, self._host))
def dragEnterEvent(self, event):
if _dragged(event) is not None:
event.setDropAction(Qt.DropAction.MoveAction)
event.accept()
def dragMoveEvent(self, event):
self.dragEnterEvent(event)
def dropEvent(self, event):
item = _dragged(event)
if item is not None:
event.setDropAction(Qt.DropAction.MoveAction)
event.accept()
self._host.remove_item(item)
def drag_pixmap(widget: QWidget) -> QPixmap:
pixmap = widget.grab()
if pixmap.width() > 240:
pixmap = pixmap.scaledToWidth(240, Qt.TransformationMode.SmoothTransformation)
return pixmap
def make_drag(source: QWidget, item: str) -> QDrag:
drag = QDrag(source)
data = QMimeData()
data.setData(MIME, item.encode())
drag.setMimeData(data)
return drag
def context_menu(parent, item: str, entry: dict, current_width: int):
"""The right-click menu: (menu, {action: (size, width) | "remove"})."""
menu = QMenu(parent)
choices = {}
label = ITEMS[base_id(item)][0]
title = menu.addAction(label)
title.setEnabled(False)
menu.addSeparator()
for size, text in (("auto", "Automatic"), ("fill", "Fill space"),
("exact", f"Exact size ({current_width} px)")):
action = menu.addAction(text)
action.setCheckable(True)
action.setChecked(entry.get("size", "auto") == size)
choices[action] = (size, current_width)
if ITEMS[base_id(item)][2]:
menu.addSeparator()
choices[menu.addAction("Remove from Toolbar")] = "remove"
return menu, choices
+311 -111
View File
@@ -13,6 +13,8 @@ from lintunes.gui.track_table import format_time
from lintunes.gui.visualizer import VisualizerWidget from lintunes.gui.visualizer import VisualizerWidget
from lintunes.player import REPEAT_MODES from lintunes.player import REPEAT_MODES
from lintunes import theme 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 ICON_GRAY = QColor("#4A4A4A") # light mode's; theme.icon_gray() follows the mode
@@ -295,12 +297,14 @@ class BpmButton(QPushButton):
self.setText("bpm") self.setText("bpm")
class HeaderRow(QWidget): class HeaderRow(ToolRow):
"""The band under the row of boxes, laid out by hand because its three """The band under the row of boxes — the toolbar's second row. It owns
parts answer to three different things: the Library button is as wide as two things lent to it (the sidebar's Library button and the shown
the sidebar below it, the seek row sits exactly under the now-playing view's header) and the vertical rules every item in it follows; *where*
panel above it, and the current view's header (search box or playlist things go across is the bar's layout (``TransportBar.place_rows``),
name) takes what lies between — which is where that view starts.""" 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 GAP = 6
# Above the boxes (Library button, search box) and below them to the # Above the boxes (Library button, search box) and below them to the
@@ -313,15 +317,11 @@ class HeaderRow(QWidget):
LIFT = 2 LIFT = 2
def __init__(self, seek: QWidget, parent=None): def __init__(self, seek: QWidget, parent=None):
super().__init__(parent) super().__init__(1, parent)
self.seek = seek self.seek = seek
seek.setParent(self)
self.left: QWidget | None = None self.left: QWidget | None = None
self.view_header: QWidget | None = None self.view_header: QWidget | None = None
self._split = (0, 0, 0) # list left, list right, content left self.bar = None # the TransportBar that places us
self._panel = QRect() # now-playing panel, in our coordinates
self.right: QWidget | None = None # the DJ button, under the bpm box
self._right = QRect()
def set_left(self, widget: QWidget): def set_left(self, widget: QWidget):
self.left = widget self.left = widget
@@ -330,7 +330,7 @@ class HeaderRow(QWidget):
self.place() self.place()
def set_view_header(self, widget: QWidget | None): def set_view_header(self, widget: QWidget | None):
"""Show ``widget`` (a view's header) in the middle slot. The one it """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 replaces goes back to its own view, hidden, so it lives and dies with
that view.""" that view."""
old = self.view_header old = self.view_header
@@ -345,57 +345,32 @@ class HeaderRow(QWidget):
widget.show() widget.show()
self.place() self.place()
def set_split(self, list_left: int, list_right: int, content_left: int):
self._split = (list_left, list_right, content_left)
self.place()
def set_panel(self, rect: QRect):
self._panel = rect
self.place()
def set_right(self, widget: QWidget, rect: QRect):
"""``widget`` sits under the bpm box, ``rect`` its column."""
if widget.parent() is not self:
widget.setParent(self)
widget.show()
self.right = widget
self._right = rect
self.place()
def resizeEvent(self, event): def resizeEvent(self, event):
super().resizeEvent(event) super().resizeEvent(event)
self.place() self.place()
def place(self): 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 floor = self.height() - self.BOTTOM
box_h = max(0, floor - self.TOP_PAD) box_h = max(0, floor - self.TOP_PAD)
list_left, list_right, content_left = self._split if widget is self.seek:
if self.left is not None:
self.left.setGeometry(list_left, self.TOP_PAD,
max(0, list_right - list_left), box_h)
# The playhead's knob and the times' baselines stand on the floor. # The playhead's knob and the times' baselines stand on the floor.
panel = self._panel
seek_left = max(panel.left(), content_left + self.GAP)
drop = self._drop(self.seek) drop = self._drop(self.seek)
self.seek.drop.changeSize(0, drop, QSizePolicy.Policy.Minimum, self.seek.drop.changeSize(0, drop, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Fixed) QSizePolicy.Policy.Fixed)
self.seek.layout().invalidate() self.seek.layout().invalidate()
self.seek.setGeometry(seek_left, self.TOP_PAD, widget.setGeometry(x, self.TOP_PAD, width, box_h + drop - self.LIFT)
max(0, panel.right() + 1 - seek_left), elif isinstance(widget, QLabel):
box_h + drop - self.LIFT) widget.setAlignment(Qt.AlignmentFlag.AlignLeft
if self.right is not None and not self._right.isNull():
self.right.setGeometry(self._right.left(), self.TOP_PAD,
self._right.width(), box_h)
header = self.view_header
if header is not None:
width = max(0, seek_left - self.GAP - content_left)
if isinstance(header, QLabel):
header.setAlignment(Qt.AlignmentFlag.AlignLeft
| Qt.AlignmentFlag.AlignBottom) | Qt.AlignmentFlag.AlignBottom)
header.setGeometry(content_left, self.TOP_PAD, width, widget.setGeometry(x, self.TOP_PAD, width,
box_h + self._drop(header) - self.LIFT) box_h + self._drop(widget) - self.LIFT)
else: else:
header.setGeometry(content_left, self.TOP_PAD, width, box_h) widget.setGeometry(x, self.TOP_PAD, width, box_h)
def _drop(self, widget) -> int: def _drop(self, widget) -> int:
"""Text stands on its baseline: its descenders hang below the """Text stands on its baseline: its descenders hang below the
@@ -425,18 +400,15 @@ class TransportBar(QWidget):
outer = QVBoxLayout(self) outer = QVBoxLayout(self)
outer.setContentsMargins(0, TOP_MARGIN, 0, 0) outer.setContentsMargins(0, TOP_MARGIN, 0, 0)
outer.setSpacing(ROW_GAP) outer.setSpacing(ROW_GAP)
# The panel's width is set from the bar's (_size_now_playing), so the # The panel's width is set from the bar's (place_rows), so the bar's
# bar's minimum must not come from the panel's current width, or a # minimum must not come from the panel's current width, or a window
# window could never shrink past the width it last had. # could never shrink past the width it last had.
outer.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint) outer.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
self._outer = outer self._outer = outer
layout = QHBoxLayout() # The row of boxes: toolbar row 0, placed by hand (place_rows).
layout.setContentsMargins(GAP, 0, GAP, 0) self._top_row = ToolRow(0)
layout.setSpacing(0) self._top_row.setFixedHeight(CONTROL_HEIGHT)
outer.addLayout(layout) outer.addWidget(self._top_row)
def gap():
layout.addSpacing(GAP)
# Rounded button boxes carry a user-tunable grayscale fill, decoupled # Rounded button boxes carry a user-tunable grayscale fill, decoupled
# from the stripe color they used to share via palette(alternate-base). # from the stripe color they used to share via palette(alternate-base).
@@ -455,8 +427,6 @@ class TransportBar(QWidget):
bg=box_bg, margins=(3, 3, 3, 3), bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True) height=CONTROL_HEIGHT, split=True)
self._boxes.append(transport_box) self._boxes.append(transport_box)
layout.addWidget(transport_box, alignment=TOP)
gap()
self._shuffle_btn = FlashButton("shuffle") self._shuffle_btn = FlashButton("shuffle")
self._shuffle_btn.setMinimumWidth(50) self._shuffle_btn.setMinimumWidth(50)
@@ -465,8 +435,6 @@ class TransportBar(QWidget):
shuffle_box = _box(self._shuffle_btn, bg=box_bg, margins=(3, 3, 3, 3), shuffle_box = _box(self._shuffle_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True) height=CONTROL_HEIGHT, split=True)
self._boxes.append(shuffle_box) self._boxes.append(shuffle_box)
layout.addWidget(shuffle_box, alignment=TOP)
gap()
# Repeat cycles off → all → one, like iTunes': lit while on, with a # Repeat cycles off → all → one, like iTunes': lit while on, with a
# "1" in the loop for one. # "1" in the loop for one.
@@ -477,14 +445,10 @@ class TransportBar(QWidget):
repeat_box = _box(self._repeat_btn, bg=box_bg, margins=(3, 3, 3, 3), repeat_box = _box(self._repeat_btn, bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True) height=CONTROL_HEIGHT, split=True)
self._boxes.append(repeat_box) self._boxes.append(repeat_box)
layout.addWidget(repeat_box, alignment=TOP)
self._show_repeat(player.repeat_mode()) self._show_repeat(player.repeat_mode())
gap()
self._visualizer = VisualizerWidget(player, prefs) self._visualizer = VisualizerWidget(player, prefs)
self._visualizer.setFixedHeight(CONTROL_HEIGHT) self._visualizer.setFixedHeight(CONTROL_HEIGHT)
layout.addWidget(self._visualizer, alignment=TOP)
gap()
# Master output volume: a slim horizontal slider in its own slot # Master output volume: a slim horizontal slider in its own slot
# between the visualizer and the timeline. The HBox centers it # between the visualizer and the timeline. The HBox centers it
@@ -508,8 +472,6 @@ class TransportBar(QWidget):
self._volume_save_timer.setInterval(400) self._volume_save_timer.setInterval(400)
self._volume_save_timer.timeout.connect(self._save_volume) self._volume_save_timer.timeout.connect(self._save_volume)
self._volume_slider.valueChanged.connect(self._on_volume_changed) self._volume_slider.valueChanged.connect(self._on_volume_changed)
layout.addWidget(self._volume_slider, alignment=TOP)
gap()
# White rounded now-playing panel: holds only the song title and the # White rounded now-playing panel: holds only the song title and the
# artist/album line, centered, filling the zone above the seek row. # artist/album line, centered, filling the zone above the seek row.
@@ -569,12 +531,8 @@ class TransportBar(QWidget):
# their top edge, so boxes, visualizer, panel and bpm read as one row; # their top edge, so boxes, visualizer, panel and bpm read as one row;
# the seek row hangs underneath the panel, in the header row. # the seek row hangs underneath the panel, in the header row.
self._now_playing.setFixedHeight(CONTROL_HEIGHT) self._now_playing.setFixedHeight(CONTROL_HEIGHT)
# Its width is set by _size_now_playing: all the room the controls # Its width is set by place_rows: by default all the room the
# and gaps leave. # controls and gaps leave.
self._now_playing.setFixedWidth(NOW_PLAYING_MIN)
layout.addWidget(self._now_playing, alignment=TOP)
self._now_playing.installEventFilter(self)
gap()
# DJ mode's button is the far-right box (Round 94: it swapped with # 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 # bpm, so it stays put while the window parts under it); the bpm
@@ -591,14 +549,20 @@ class TransportBar(QWidget):
dj_box = _box(self.dj_button, bg=box_bg, margins=(3, 3, 3, 3), dj_box = _box(self.dj_button, bg=box_bg, margins=(3, 3, 3, 3),
hug=True, height=CONTROL_HEIGHT, split=True) hug=True, height=CONTROL_HEIGHT, split=True)
self._boxes.append(dj_box) self._boxes.append(dj_box)
layout.addWidget(dj_box, alignment=TOP)
self._fixed_controls = (transport_box, shuffle_box, repeat_box,
self._visualizer,
self._volume_slider, dj_box)
self._bpm_button = BpmButton(player, manager) self._bpm_button = BpmButton(player, manager)
self._bpm_button.setObjectName("bpmHeader") self._bpm_button.setObjectName("bpmHeader")
self._bpm_button.setFlat(False) 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()
# Library button · the current view's header · seek row. MainWindow # Library button · the current view's header · seek row. MainWindow
# hands over the first two (see set_sidebar_header / set_view_header) # hands over the first two (see set_sidebar_header / set_view_header)
# and says where the sidebar ends (track_split). # and says where the sidebar ends (track_split).
@@ -607,6 +571,32 @@ class TransportBar(QWidget):
self.set_header_height(34) self.set_header_height(34)
outer.addWidget(self._header_row) 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, "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._dj_box = dj_box
self._apply_dj_button_style() self._apply_dj_button_style()
self._split_widgets: tuple = () self._split_widgets: tuple = ()
@@ -736,51 +726,258 @@ class TransportBar(QWidget):
def eventFilter(self, obj, event): def eventFilter(self, obj, event):
if event.type() in (QEvent.Type.Resize, QEvent.Type.Move): if event.type() in (QEvent.Type.Resize, QEvent.Type.Move):
self._place_header() self.place_rows()
return super().eventFilter(obj, event) return super().eventFilter(obj, event)
def resizeEvent(self, event): def resizeEvent(self, event):
super().resizeEvent(event) super().resizeEvent(event)
self._size_now_playing() self.place_rows()
self._place_header()
def _controls_width(self) -> int: # ---- the toolbar's layout (gui/toolbar.py) ----
"""Everything in the row of boxes but the now-playing panel: the
controls and a GAP before, between and after them."""
# A fixed width shows in the minimum, not the size hint.
return (sum(max(w.sizeHint().width(), w.minimumWidth())
for w in self._fixed_controls)
+ (len(self._fixed_controls) + 2) * GAP)
def _size_now_playing(self): def _widget(self, item: str) -> QWidget | None:
"""The panel fills whatever the controls and gaps leave.""" base = toolbar.base_id(item)
self._now_playing.setFixedWidth( if base == "library":
max(NOW_PLAYING_MIN, self.width() - self._controls_width())) 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 minimumSizeHint(self): def _width_of(self, item: str) -> int:
hint = super().minimumSizeHint() base = toolbar.base_id(item)
hint.setWidth(self._controls_width() + NOW_PLAYING_MIN) if base == "space":
return hint 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 sizeHint(self): def _least_of(self, item: str) -> int:
hint = super().sizeHint() return self._least.get(toolbar.base_id(item), toolbar.MIN_WIDTH)
hint.setWidth(self._controls_width() + NOW_PLAYING_MIN * 2)
return hint
def _place_header(self): 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()
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(toolbar.ANCHORED_UNDER.get(base, ""))
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 row = self._header_row
def x_of(widget, x=0): # siblings, not ancestors: go via global def x_of(widget, x=0): # siblings, not ancestors: go via global
return row.mapFromGlobal(widget.mapToGlobal(QPoint(x, 0))).x() return row.mapFromGlobal(widget.mapToGlobal(QPoint(x, 0))).x()
return x_of(lists), x_of(lists, lists.width()), x_of(content)
row.set_panel(QRect(x_of(self._now_playing), 0, _ROW_SPACING = {0: (GAP, GAP), 1: (8, HeaderRow.GAP)} # (margin, gap)
self._now_playing.width(), row.height()))
box = self._dj_box def place_rows(self):
row.set_right(self._bpm_button, QRect(x_of(box), 0, box.width(), row.height())) """Put every item where the layout says, row 0 first (row 1's
if self._split_widgets: automatic items line up under it)."""
lists, content = self._split_widgets if not hasattr(self, "_rows"):
row.set_split(x_of(lists), x_of(lists, lists.width()), return # still being built
x_of(content)) 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))
# ---- 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): def refresh_theme(self):
"""Re-apply everything driven by Preferences: button glyphs (highlight """Re-apply everything driven by Preferences: button glyphs (highlight
@@ -796,7 +993,10 @@ class TransportBar(QWidget):
self._apply_now_playing_font() self._apply_now_playing_font()
self._apply_dj_button_style() self._apply_dj_button_style()
self._on_dj_button_icon(self.dj_button.isChecked()) self._on_dj_button_icon(self.dj_button.isChecked())
self._theme_btn.refresh_icons()
self._show_theme_kind()
self._visualizer.update() # dim-mode bar color may have changed self._visualizer.update() # dim-mode bar color may have changed
self.apply_toolbar()
def _apply_now_playing_bg(self): def _apply_now_playing_bg(self):
bg = theme.surface(self._prefs, "color_now_playing_bg") bg = theme.surface(self._prefs, "color_now_playing_bg")
+161
View File
@@ -93,3 +93,164 @@ def test_the_dark_mode_box_follows_the_pref(qapp, tmp_path):
assert not dialog._dark_check.isChecked() assert not dialog._dark_check.isChecked()
dialog.deleteLater() dialog.deleteLater()
theme.apply_theme(qapp, Preferences(tmp_path / "light")) theme.apply_theme(qapp, Preferences(tmp_path / "light"))
# ---- the toolbar configurator ----
from unittest.mock import MagicMock
from PyQt6.QtCore import QPoint, QPointF, Qt
from PyQt6.QtGui import QMouseEvent
from PyQt6.QtCore import QEvent
from lintunes.gui import toolbar
from lintunes.gui.toolbar import Slot, lay_out
def test_normalize_keeps_what_must_stay_and_drops_junk():
rows = toolbar.normalize([[{"id": "shuffle"}, {"id": "shuffle"}, {"id": "nope"},
{"id": "library"}, "space:1"], []])
assert [e["id"] for e in rows[0]] == ["shuffle", "space:1"]
# library may only sit in row 1, and it and the view can't be removed
assert {e["id"] for e in rows[1]} == {"library", "view"}
assert toolbar.normalize("garbage") == toolbar.default_config()
def test_move_remove_and_sizes():
rows = toolbar.default_config()
rows = toolbar.move(rows, "dj", 0, 0)
assert rows[0][0]["id"] == "dj"
rows = toolbar.move(rows, "theme", 1, 2)
assert [e["id"] for e in rows[1]][:3] == ["library", "view", "theme"]
assert toolbar.move(rows, "library", 0, 0) == rows # row 1 only
assert toolbar.remove(rows, "view") == rows # required
rows = toolbar.remove(rows, "theme")
assert toolbar.find(rows, "theme") is None
rows = toolbar.set_size(rows, "visualizer", "exact", 200)
entry = rows[0][toolbar.find(rows, "visualizer")[1]]
assert entry == {"id": "visualizer", "size": "exact", "width": 200}
rows = toolbar.set_size(rows, "visualizer", "fill")
assert "width" not in rows[0][toolbar.find(rows, "visualizer")[1]]
def test_spacers_are_numbered_and_always_offered():
rows = toolbar.default_config()
first = toolbar.new_instance(rows, "space")
rows = toolbar.move(rows, first, 0, 1)
assert first == "space:1"
assert toolbar.new_instance(rows, "space") == "space:2"
assert "space" in toolbar.palette_ids(rows)
assert "theme" in toolbar.palette_ids(rows)
assert "shuffle" not in toolbar.palette_ids(rows)
def test_lay_out_knolls_and_shares_fill():
spots = lay_out([Slot("a", width=50), Slot("b", fill=True), Slot("c", width=30),
Slot("d", fill=True)], 400, 10, 10)
assert spots["a"] == (10, 50)
# 400 - 2*10 margins - 80 fixed - 3*10 gaps = 270, split 135/135
assert spots["b"] == (70, 135) and spots["d"][1] == 135
assert spots["d"][0] + spots["d"][1] == 390
def test_lay_out_anchors_and_falls_back():
spots = lay_out([Slot("lib", anchor=(8, 200)), Slot("view", fill=True, start=208),
Slot("seek", anchor=(500, 900))], 1000, 8, 6)
assert spots["lib"] == (8, 192)
assert spots["view"] == (208, 500 - 6 - 208)
assert spots["seek"] == (500, 400)
# an anchor the items before it overrun is just a fixed slot after them
spots = lay_out([Slot("big", width=600), Slot("seek", anchor=(100, 300))], 1000, 0, 10)
assert spots["seek"] == (610, 200)
def _bar(tmp_path, rows=None):
from lintunes.gui.transport import TransportBar
player = MagicMock()
player.repeat_mode.return_value = "off"
prefs = Preferences(tmp_path)
if rows is not None:
prefs.set("toolbar", rows)
bar = TransportBar(player, MagicMock(), prefs)
bar.resize(1280, 140)
bar.show()
QApplication.processEvents()
return bar, prefs
def test_dropping_an_item_in_adds_it_and_saves(qapp, tmp_path):
bar, prefs = _bar(tmp_path)
assert not bar._theme_btn.parentWidget().isVisible()
bar.drop_item("theme", 0, 3)
QApplication.processEvents()
assert [e["id"] for e in prefs.get("toolbar")[0]][3] == "theme"
box = bar._theme_btn.parentWidget()
assert box.isVisible() and box.parentWidget() is bar._top_row
shuffle = bar._shuffle_btn.parentWidget().geometry()
assert box.geometry().left() > shuffle.right()
bar.remove_item("theme")
assert not box.isVisible()
def test_the_theme_button_flips_dark_mode(qapp, tmp_path):
bar, prefs = _bar(tmp_path)
bar._theme_btn.click()
assert prefs.get("dark_mode") is True
bar._theme_btn.click()
assert prefs.get("dark_mode") is False
def test_an_exact_width_and_fill(qapp, tmp_path):
bar, prefs = _bar(tmp_path)
bar._save_toolbar(toolbar.set_size(bar._rows, "visualizer", "exact", 300))
assert bar._visualizer.width() == 300
panel = bar._now_playing.width()
bar._save_toolbar(toolbar.set_size(bar._rows, "volume", "fill"))
# two fills now share what the fixed items leave
assert abs(bar._volume_slider.width() - bar._now_playing.width()) <= 1
assert bar._now_playing.width() < panel
def _mouse(widget, kind, pos, button=Qt.MouseButton.LeftButton):
event = QMouseEvent(kind, QPointF(pos), QPointF(widget.mapToGlobal(pos)), button,
button if kind != QEvent.Type.MouseButtonRelease
else Qt.MouseButton.NoButton,
Qt.KeyboardModifier.NoModifier)
QApplication.sendEvent(widget, event)
def test_customize_mode_resizes_by_the_handle(qapp, tmp_path):
bar, prefs = _bar(tmp_path)
bar.set_customizing(True)
QApplication.processEvents()
assert bar.is_customizing() and len(bar._overlays) == 2
overlay = bar._overlays[0]
rect = bar._rects[0]["visualizer"]
start = QPoint(rect.right() - 1, rect.center().y())
_mouse(overlay, QEvent.Type.MouseButtonPress, start)
_mouse(overlay, QEvent.Type.MouseMove, start + QPoint(40, 0))
_mouse(overlay, QEvent.Type.MouseButtonRelease, start + QPoint(40, 0))
entry = prefs.get("toolbar")[0][toolbar.find(bar._rows, "visualizer")[1]]
assert entry["size"] == "exact" and entry["width"] == rect.width() + 40
assert bar._visualizer.width() == rect.width() + 40
# the overlay takes the clicks, so a button under it isn't pressed
played = []
bar.play_clicked.connect(lambda: played.append(1))
play = bar._play_btn.mapTo(bar._top_row, bar._play_btn.rect().center())
_mouse(overlay, QEvent.Type.MouseButtonPress, play)
_mouse(overlay, QEvent.Type.MouseButtonRelease, play)
assert played == []
bar.set_customizing(False)
QApplication.processEvents()
assert bar._overlays == [] and bar._panel is None
def test_restore_defaults(qapp, tmp_path):
rows = toolbar.remove(toolbar.default_config(), "shuffle")
bar, prefs = _bar(tmp_path, rows)
assert not bar._shuffle_btn.parentWidget().isVisible()
bar.set_customizing(True)
bar._panel.restore.emit()
assert prefs.get("toolbar") == toolbar.default_config()
assert bar._shuffle_btn.parentWidget().isVisible()
bar.set_customizing(False)
+5 -2
View File
@@ -180,7 +180,10 @@ def test_dj_button_up_top_bpm_below_and_a_tall_volume(qapp, tmp_path):
with tempfile.TemporaryDirectory() as d: with tempfile.TemporaryDirectory() as d:
bar = TransportBar(player, MagicMock(), Preferences(Path(d))) bar = TransportBar(player, MagicMock(), Preferences(Path(d)))
assert bar.dj_button.parentWidget() is bar._dj_box assert bar.dj_button.parentWidget() is bar._dj_box
assert bar._dj_box in bar._fixed_controls bar.resize(1280, 120)
bar._place_header() # what a resize does bar._place_header() # what a resize does
assert bar._header_row.right is bar._bpm_button assert bar._dj_box.parentWidget() is bar._top_row
assert bar._bpm_button.parentWidget() is bar._header_row
dj, bpm = bar._dj_box.geometry(), bar._bpm_button.geometry()
assert (bpm.left(), bpm.width()) == (dj.left(), dj.width())
assert bar._volume_slider.property("tall") is True assert bar._volume_slider.property("tall") is True