Files
lintunes/lintunes/gui/toolbar.py
T

551 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The 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