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
+318 -118
View File
@@ -13,6 +13,8 @@ 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
@@ -295,12 +297,14 @@ class BpmButton(QPushButton):
self.setText("bpm")
class HeaderRow(QWidget):
"""The band under the row of boxes, laid out by hand because its three
parts answer to three different things: the Library button is as wide as
the sidebar below it, the seek row sits exactly under the now-playing
panel above it, and the current view's header (search box or playlist
name) takes what lies between — which is where that view starts."""
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
@@ -313,15 +317,11 @@ class HeaderRow(QWidget):
LIFT = 2
def __init__(self, seek: QWidget, parent=None):
super().__init__(parent)
super().__init__(1, parent)
self.seek = seek
seek.setParent(self)
self.left: QWidget | None = None
self.view_header: QWidget | None = None
self._split = (0, 0, 0) # list left, list right, content left
self._panel = QRect() # now-playing panel, in our coordinates
self.right: QWidget | None = None # the DJ button, under the bpm box
self._right = QRect()
self.bar = None # the TransportBar that places us
def set_left(self, widget: QWidget):
self.left = widget
@@ -330,7 +330,7 @@ class HeaderRow(QWidget):
self.place()
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
that view."""
old = self.view_header
@@ -345,57 +345,32 @@ class HeaderRow(QWidget):
widget.show()
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):
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)
list_left, list_right, content_left = self._split
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.
panel = self._panel
seek_left = max(panel.left(), content_left + self.GAP)
drop = self._drop(self.seek)
self.seek.drop.changeSize(0, drop, QSizePolicy.Policy.Minimum,
QSizePolicy.Policy.Fixed)
self.seek.layout().invalidate()
self.seek.setGeometry(seek_left, self.TOP_PAD,
max(0, panel.right() + 1 - seek_left),
box_h + drop - self.LIFT)
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)
header.setGeometry(content_left, self.TOP_PAD, width,
box_h + self._drop(header) - self.LIFT)
else:
header.setGeometry(content_left, self.TOP_PAD, width, box_h)
if widget is self.seek:
# The playhead's knob and the times' baselines stand on the floor.
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
@@ -425,18 +400,15 @@ class TransportBar(QWidget):
outer = QVBoxLayout(self)
outer.setContentsMargins(0, TOP_MARGIN, 0, 0)
outer.setSpacing(ROW_GAP)
# The panel's width is set from the bar's (_size_now_playing), 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.
# 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
layout = QHBoxLayout()
layout.setContentsMargins(GAP, 0, GAP, 0)
layout.setSpacing(0)
outer.addLayout(layout)
def gap():
layout.addSpacing(GAP)
# 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).
@@ -455,8 +427,6 @@ class TransportBar(QWidget):
bg=box_bg, margins=(3, 3, 3, 3),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(transport_box)
layout.addWidget(transport_box, alignment=TOP)
gap()
self._shuffle_btn = FlashButton("shuffle")
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),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(shuffle_box)
layout.addWidget(shuffle_box, alignment=TOP)
gap()
# Repeat cycles off → all → one, like iTunes': lit while on, with a
# "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),
height=CONTROL_HEIGHT, split=True)
self._boxes.append(repeat_box)
layout.addWidget(repeat_box, alignment=TOP)
self._show_repeat(player.repeat_mode())
gap()
self._visualizer = VisualizerWidget(player, prefs)
self._visualizer.setFixedHeight(CONTROL_HEIGHT)
layout.addWidget(self._visualizer, alignment=TOP)
gap()
# Master output volume: a slim horizontal slider in its own slot
# 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.timeout.connect(self._save_volume)
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
# 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;
# the seek row hangs underneath the panel, in the header row.
self._now_playing.setFixedHeight(CONTROL_HEIGHT)
# Its width is set by _size_now_playing: all the room the controls
# and gaps leave.
self._now_playing.setFixedWidth(NOW_PLAYING_MIN)
layout.addWidget(self._now_playing, alignment=TOP)
self._now_playing.installEventFilter(self)
gap()
# 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
@@ -591,14 +549,20 @@ class TransportBar(QWidget):
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)
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.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()
# 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).
@@ -607,6 +571,32 @@ class TransportBar(QWidget):
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, "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 = ()
@@ -736,51 +726,258 @@ class TransportBar(QWidget):
def eventFilter(self, obj, event):
if event.type() in (QEvent.Type.Resize, QEvent.Type.Move):
self._place_header()
self.place_rows()
return super().eventFilter(obj, event)
def resizeEvent(self, event):
super().resizeEvent(event)
self._size_now_playing()
self._place_header()
self.place_rows()
def _controls_width(self) -> int:
"""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)
# ---- the toolbar's layout (gui/toolbar.py) ----
def _size_now_playing(self):
"""The panel fills whatever the controls and gaps leave."""
self._now_playing.setFixedWidth(
max(NOW_PLAYING_MIN, self.width() - self._controls_width()))
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 minimumSizeHint(self):
hint = super().minimumSizeHint()
hint.setWidth(self._controls_width() + NOW_PLAYING_MIN)
return hint
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 sizeHint(self):
hint = super().sizeHint()
hint.setWidth(self._controls_width() + NOW_PLAYING_MIN * 2)
return hint
def _least_of(self, item: str) -> int:
return self._least.get(toolbar.base_id(item), toolbar.MIN_WIDTH)
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
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.set_panel(QRect(x_of(self._now_playing), 0,
self._now_playing.width(), row.height()))
box = self._dj_box
row.set_right(self._bpm_button, QRect(x_of(box), 0, box.width(), row.height()))
if self._split_widgets:
lists, content = self._split_widgets
row.set_split(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))
# ---- 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
@@ -796,7 +993,10 @@ class TransportBar(QWidget):
self._apply_now_playing_font()
self._apply_dj_button_style()
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.apply_toolbar()
def _apply_now_playing_bg(self):
bg = theme.surface(self._prefs, "color_now_playing_bg")