Files
lintunes/lintunes/gui/device_sync_dialog.py
T
trav 3888248231 v0.32.0: folder tree in Rabbit Sync Settings, quieter art pass, tink, VLC-style Preferences
- Rabbit Sync Settings shows the sidebar's folder tree. A folder has its own
  tristate checkbox; a fully ticked folder is stored as device_sync.folder_ids
  and follows the folder, so playlists added to it later sync too.
- The album-art pass compares covers against the sizes the planner's device
  scan already read (plan.art_sizes) instead of an MTP stat per album, caches
  "no art" as a .none marker, and only unlinks covers that are really there.
  The summary reports covers actually updated rather than every cover.
- A quiet tink when a Rabbit sync, export or URL import finishes, with an
  on/off switch (sound_effects, on by default).
- Preferences is now General / Appearance / Integrations, a list on the left
  and the page on the right, opened big enough for the tallest page.
2026-10-01 00:45:42 -07:00

270 lines
10 KiB
Python

"""Pick which playlists live on the Rabbit.
The old menu synced whichever playlist happened to be open, which made
"remove this from the device" an operation with no button: nothing ever
deleted a playlist folder. Here the ticked set *is* the device's contents —
unticking is how a playlist comes off, and the next sync does it.
The selection is stored in preferences.json, so it rides the same Syncthing
share as the library and both machines agree on what belongs on the device.
Playlists are shown in the sidebar's folder tree (Round 70), and a folder has
a checkbox of its own. A *fully* ticked folder is stored as the folder
(``folder_ids``), not as the playlists it held that day, so a playlist added
to it later goes to the device too. Untick one playlist inside and the folder
goes back to being remembered playlist by playlist.
"""
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (
QCheckBox, QDialog, QDialogButtonBox, QLabel, QLineEdit, QTreeWidget,
QTreeWidgetItem, QVBoxLayout,
)
from ..models.playlist import PlaylistType
PID_ROLE = Qt.ItemDataRole.UserRole
CHECKED = Qt.CheckState.Checked
UNCHECKED = Qt.CheckState.Unchecked
def _is_folder(playlist) -> bool:
return playlist.playlist_type == PlaylistType.FOLDER
def _syncable(playlist) -> bool:
return not _is_folder(playlist) and not playlist.is_system
def syncable_playlists(library) -> list:
"""Playlists a user can put on a device, in name order.
Folders hold no tracks and system playlists aren't the user's to sync;
a smart playlist is fine — by the time we see it, its membership has
already been computed.
"""
return sorted((p for p in library.playlists.values() if _syncable(p)),
key=lambda p: p.name.casefold())
def _children(library) -> dict:
"""parent pid ("" for the top level) -> its playlists and folders in the
sidebar's order. A parent that doesn't resolve counts as the top level,
exactly as the sidebar draws it."""
playlists = library.playlists
children: dict[str, list] = {}
for playlist in playlists.values():
if playlist.is_system:
continue
parent = playlist.parent_persistent_id
if parent not in playlists:
parent = ""
children.setdefault(parent, []).append(playlist)
for level in children.values():
level.sort(key=lambda p: p.name.lower())
return children
def _descendants(children, folder_pid) -> list:
"""Every syncable playlist under a folder, at any depth, in tree order."""
found = []
for playlist in children.get(folder_pid, []):
if _is_folder(playlist):
found += _descendants(children, playlist.persistent_id)
else:
found.append(playlist)
return found
def resolve_sync_playlists(library, device_sync: dict) -> list:
"""The playlists a sync carries: explicitly ticked ones in their stored
order, then everything under each ticked folder, without repeats.
Ids that no longer resolve are skipped rather than cleaned up: a playlist
can be missing because the other machine hasn't synced yet, and silently
forgetting the choice would be worse than ignoring it.
"""
playlists = library.playlists
result, seen = [], set()
def add(playlist):
if playlist.persistent_id not in seen and _syncable(playlist):
seen.add(playlist.persistent_id)
result.append(playlist)
for pid in device_sync.get("playlist_ids", []):
if pid in playlists:
add(playlists[pid])
children = None
for fid in device_sync.get("folder_ids", []):
if fid in playlists and _is_folder(playlists[fid]):
children = children if children is not None else _children(library)
for playlist in _descendants(children, fid):
add(playlist)
return result
class DeviceSyncSettingsDialog(QDialog):
def __init__(self, prefs, library, parent=None, device_name="Rabbit"):
super().__init__(parent)
self.setWindowTitle(f"{device_name} Sync Settings")
self.resize(460, 620)
self._prefs = prefs
self._library = library
layout = QVBoxLayout(self)
intro = QLabel(
f"Playlists to keep on the {device_name}. Unticking one removes "
"it from the device on the next sync. A ticked folder also brings "
"along playlists you add to it later.")
intro.setWordWrap(True)
layout.addWidget(intro)
# 500 playlists is a normal library here, so the tree is unusable
# without a filter.
self._filter = QLineEdit(self)
self._filter.setPlaceholderText("Filter playlists…")
self._filter.setClearButtonEnabled(True)
self._filter.textChanged.connect(self._apply_filter)
layout.addWidget(self._filter)
self._tree = QTreeWidget(self)
self._tree.setHeaderHidden(True)
self._tree.setIndentation(14)
self._build_tree(prefs.device_sync)
layout.addWidget(self._tree, stretch=1)
self._count = QLabel(self)
layout.addWidget(self._count)
self._tree.itemChanged.connect(lambda _item, _col: self._refresh_count())
self._refresh_count()
self._art = QCheckBox("Copy album art to the device", self)
self._art.setChecked(bool(prefs.device_sync.get("copy_art", True)))
self._art.setToolTip(
"Covers are read from the tags and scaled to 480 px — one file "
"per album, not per song.")
layout.addWidget(self._art)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok
| QDialogButtonBox.StandardButton.Cancel, parent=self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
# ---- tree ----
def _build_tree(self, device_sync: dict):
children = _children(self._library)
selected = set(device_sync.get("playlist_ids", []))
folders = set(device_sync.get("folder_ids", []))
def add_level(parent_item, parent_pid, inherited: bool):
for playlist in children.get(parent_pid, []):
pid = playlist.persistent_id
if _is_folder(playlist):
# A folder with nothing syncable anywhere inside has no
# checkbox worth offering.
if not _descendants(children, pid):
continue
item = self._new_item(parent_item, playlist)
item.setFlags(item.flags()
| Qt.ItemFlag.ItemIsAutoTristate)
add_level(item, pid, inherited or pid in folders)
item.setExpanded(item.checkState(0) != UNCHECKED)
else:
item = self._new_item(parent_item, playlist)
item.setCheckState(
0, CHECKED if inherited or pid in selected
else UNCHECKED)
self._tree.blockSignals(True)
add_level(None, "", False)
self._tree.blockSignals(False)
def _new_item(self, parent_item, playlist) -> QTreeWidgetItem:
label = (playlist.name if _is_folder(playlist)
else f"{playlist.name} ({len(playlist.track_ids)})")
item = QTreeWidgetItem([label])
item.setData(0, PID_ROLE, playlist.persistent_id)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
item.setCheckState(0, UNCHECKED)
if parent_item is None:
self._tree.addTopLevelItem(item)
else:
parent_item.addChild(item)
return item
def _items(self, parent=None):
"""Every item, depth first."""
parent = parent or self._tree.invisibleRootItem()
for i in range(parent.childCount()):
child = parent.child(i)
yield child
yield from self._items(child)
def _apply_filter(self, text: str):
needle = text.strip().casefold()
def visit(item, ancestor_matches: bool) -> bool:
"""Show/hide item's subtree; True when anything in it shows."""
matches = ancestor_matches or not needle or (
needle in item.text(0).casefold())
if item.childCount() == 0:
item.setHidden(not matches)
return matches
shown = False
for i in range(item.childCount()):
shown |= visit(item.child(i), matches)
item.setHidden(not shown)
if needle and shown:
item.setExpanded(True)
return shown
root = self._tree.invisibleRootItem()
for i in range(root.childCount()):
visit(root.child(i), False)
# ---- selection ----
def _refresh_count(self):
n = len(self._ticked_playlist_ids())
self._count.setText(
f"{n} playlist{'' if n == 1 else 's'} selected"
if n else "No playlists selected — nothing will be synced.")
def _ticked_playlist_ids(self) -> list:
return [item.data(0, PID_ROLE) for item in self._items()
if item.childCount() == 0 and item.checkState(0) == CHECKED]
def selection(self) -> tuple[list, list]:
"""(playlist_ids, folder_ids) as stored: a fully ticked folder
stands for everything under it, so nothing beneath it is listed."""
playlist_ids, folder_ids = [], []
def visit(item):
if item.childCount():
if item.checkState(0) == CHECKED:
folder_ids.append(item.data(0, PID_ROLE))
return
for i in range(item.childCount()):
visit(item.child(i))
elif item.checkState(0) == CHECKED:
playlist_ids.append(item.data(0, PID_ROLE))
root = self._tree.invisibleRootItem()
for i in range(root.childCount()):
visit(root.child(i))
return playlist_ids, folder_ids
def selected_ids(self) -> list:
return self._ticked_playlist_ids()
def accept(self):
playlist_ids, folder_ids = self.selection()
self._prefs.update_device_sync(playlist_ids=playlist_ids,
folder_ids=folder_ids,
copy_art=self._art.isChecked())
super().accept()