Files
lintunes/lintunes/gui/preferences_dialog.py
T
trav 312748d05e v0.15.0: ask the song what it is
Right-click → Identify Track… fingerprints the file with Chromaprint's
fpcalc and asks AcoustID who it is, then proposes the tags it found.

The year is the point. A 60s song kept getting stamped with the year its
CD reissue came out, which sorts the library wrong, so every candidate
carries the recording's *original* year — the earliest release across all
of its release groups — including the candidate that proposes a later
greatest-hits as the album. Ranking separately prefers a plain studio
Album over EP/Single over anything wearing a Compilation or Live
secondary type, so the default proposal is the real album as well.

Nothing is written until accepted: the dialog shows each current value
beside an editable proposed one, and a row starts checked only where the
proposal actually differs from what the file already has, so an untouched
field can never quietly blank a tag. Applying goes through
edit_track_fields, which is what buys the tag write, the abort-if-it-fails
rule, artist/album file relocation and one undo step without re-deriving
any of them.

A selection is a queue reviewed one track at a time; a failure is a
status-bar message that moves on rather than ending the batch. fpcalc is
detected at runtime like ffmpeg and the AcoustID key lives in preferences
(so it syncs, and stays out of git) — the round adds no new dependency.

Also fixes a pre-existing round 40 test that used the real tummult mount
point as its stand-in for an unreachable path, so it failed whenever that
drive was plugged in.

Claude-Session: https://claude.ai/code/session_01NsiFHdyVg1UhBSxDJfTNRm
2026-09-02 15:40:52 -04:00

315 lines
12 KiB
Python

from PyQt6.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QGroupBox, QLabel, QSlider,
QRadioButton, QButtonGroup, QLineEdit, QPushButton, QCheckBox,
QFormLayout, QFontComboBox,
)
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont
from lintunes import theme
from lintunes.theme import HIGHLIGHT_COLORS
_SCALES = ["small", "medium", "large"]
# (preference key, row label) for the per-area grayscale sliders.
_COLOR_ROWS = [
("color_background", "Background:"),
("color_button", "Buttons:"),
("color_now_playing_bg", "Now-playing panel:"),
("color_now_playing_text", "Now-playing text:"),
("color_stripe", "Stripes:"),
("color_visualizer_gray", "Visualizer (gray mode):"),
]
class PreferencesDialog(QDialog):
"""App preferences. Applies immediately — there is no OK/Cancel.
``music_folder``/``on_music_folder_change`` are optional callbacks rather
than a LibraryManager reference, keeping this dialog manager-free (the same
injection style as track_table's ``playlists_for_track``). When they are
omitted the music-folder row is simply left out.
"""
def __init__(self, prefs, lastfm, parent=None, *,
music_folder=None, on_music_folder_change=None):
super().__init__(parent)
self._prefs = prefs
self._lastfm = lastfm
self._music_folder = music_folder
self._on_music_folder_change = on_music_folder_change
self.setWindowTitle("Preferences")
self.setMinimumWidth(420)
# Color sliders preview live (set_live emits without writing); persist
# once the user pauses so a drag doesn't hammer the disk.
self._color_save_timer = QTimer(self)
self._color_save_timer.setSingleShot(True)
self._color_save_timer.setInterval(400)
self._color_save_timer.timeout.connect(self._prefs.save)
layout = QVBoxLayout(self)
layout.addWidget(self._build_general_group())
if self._music_folder is not None:
layout.addWidget(self._build_music_group())
layout.addWidget(self._build_colors_group())
layout.addWidget(self._build_lastfm_group())
layout.addWidget(self._build_acoustid_group())
layout.addStretch()
lastfm.login_finished.connect(self._on_login_finished)
self._refresh_lastfm_state()
# ---- General ----
def _build_general_group(self) -> QGroupBox:
group = QGroupBox("General")
form = QFormLayout(group)
# UI size: 3-position slider
size_row = QHBoxLayout()
self._size_slider = QSlider(Qt.Orientation.Horizontal)
self._size_slider.setRange(0, 2)
self._size_slider.setPageStep(1)
self._size_slider.setTickPosition(QSlider.TickPosition.TicksBelow)
self._size_slider.setTickInterval(1)
self._size_slider.setFixedWidth(160)
current_scale = self._prefs.get("ui_scale", "medium")
self._size_slider.setValue(
_SCALES.index(current_scale) if current_scale in _SCALES else 1)
self._size_label = QLabel(current_scale.capitalize())
self._size_slider.valueChanged.connect(self._on_size_changed)
size_row.addWidget(QLabel("Small"))
size_row.addWidget(self._size_slider)
size_row.addWidget(QLabel("Large"))
size_row.addSpacing(8)
size_row.addWidget(self._size_label)
size_row.addStretch()
form.addRow("UI size:", size_row)
# Highlight color swatches
color_row = QHBoxLayout()
self._color_group = QButtonGroup(self)
for name, hex_value in HIGHLIGHT_COLORS.items():
radio = QRadioButton(name)
radio.setIcon(theme.swatch_icon(hex_value))
radio.setChecked(self._prefs.get("highlight") == name)
radio.toggled.connect(
lambda checked, n=name: checked and self._prefs.set("highlight", n))
self._color_group.addButton(radio)
color_row.addWidget(radio)
color_row.addStretch()
form.addRow("Highlight:", color_row)
# Now-playing font. Three states, so three radios: automatic (None),
# the app's own font (""), or an explicit family.
font_row = QHBoxLayout()
self._font_mode = QButtonGroup(self)
self._font_auto = QRadioButton("Automatic")
self._font_auto.setToolTip(
"Century Gothic if you have it, otherwise the closest match installed")
self._font_default = QRadioButton("Same as the app")
self._font_pick = QRadioButton("Choose:")
for button in (self._font_auto, self._font_default, self._font_pick):
self._font_mode.addButton(button)
font_row.addWidget(button)
self._font_combo = QFontComboBox()
font_row.addWidget(self._font_combo, stretch=1)
# State before signals, or building the dialog would write a pref.
saved = self._prefs.get("now_playing_font")
resolved = theme.now_playing_font_family(self._prefs) or self.font().family()
self._font_combo.setCurrentFont(QFont(resolved))
self._font_combo.setEnabled(bool(saved))
(self._font_default if saved == ""
else self._font_pick if saved
else self._font_auto).setChecked(True)
self._font_auto.toggled.connect(
lambda on: on and self._set_font_mode(None))
self._font_default.toggled.connect(
lambda on: on and self._set_font_mode(""))
self._font_pick.toggled.connect(
lambda on: on and self._set_font_mode(self._font_combo.currentFont().family()))
self._font_combo.currentFontChanged.connect(self._on_font_chosen)
form.addRow("Now-playing font:", font_row)
return group
def _set_font_mode(self, value):
self._font_combo.setEnabled(value not in (None, ""))
self._prefs.set("now_playing_font", value)
if value is None:
# Show what "automatic" actually landed on.
resolved = theme.now_playing_font_family(self._prefs)
if resolved:
self._font_combo.blockSignals(True)
self._font_combo.setCurrentFont(QFont(resolved))
self._font_combo.blockSignals(False)
def _on_font_chosen(self, font):
if self._font_pick.isChecked():
self._prefs.set("now_playing_font", font.family())
# ---- music folder ----
def _build_music_group(self) -> QGroupBox:
group = QGroupBox("Music folder")
form = QFormLayout(group)
row = QHBoxLayout()
self._music_edit = QLineEdit()
self._music_edit.setReadOnly(True)
row.addWidget(self._music_edit, stretch=1)
change = QPushButton("Change…")
change.clicked.connect(self._change_music_folder)
row.addWidget(change)
form.addRow("Keep music in:", row)
self._music_note = QLabel()
self._music_note.setWordWrap(True)
form.addRow("", self._music_note)
self.refresh_music_folder()
return group
def refresh_music_folder(self):
"""Repopulate the row from the injected getter."""
if self._music_folder is None or not hasattr(self, "_music_edit"):
return
folder, note = self._music_folder()
self._music_edit.setText(folder)
self._music_edit.setPlaceholderText("Not set")
self._music_note.setText(note)
def _change_music_folder(self):
if self._on_music_folder_change is not None:
self._on_music_folder_change()
self.refresh_music_folder()
def _on_size_changed(self, value: int):
scale = _SCALES[value]
self._size_label.setText(scale.capitalize())
self._prefs.set("ui_scale", scale)
# ---- Colors ----
def _build_colors_group(self) -> QGroupBox:
group = QGroupBox("Colors")
form = QFormLayout(group)
note = QLabel("Each slider runs black → white and updates instantly.")
note.setWordWrap(True)
form.addRow(note)
self._color_sliders = {}
for key, label in _COLOR_ROWS:
slider = QSlider(Qt.Orientation.Horizontal)
slider.setRange(0, 255)
slider.setValue(theme.gray_value(self._prefs, key)) # before connect
slider.valueChanged.connect(
lambda value, k=key: self._on_color_changed(k, value))
self._color_sliders[key] = slider
form.addRow(label, slider)
return group
def _on_color_changed(self, key: str, value: int):
self._prefs.set_live(key, value) # live preview, no disk write yet
self._color_save_timer.start() # persist once the drag settles
# ---- Last.fm ----
def _build_lastfm_group(self) -> QGroupBox:
group = QGroupBox("Last.fm")
form = QFormLayout(group)
hint = QLabel(
'Needs a free API account: '
'<a href="https://www.last.fm/api/account/create">'
'last.fm/api/account/create</a>')
hint.setOpenExternalLinks(True)
form.addRow(hint)
lf = self._prefs.lastfm
self._api_key = QLineEdit(lf.get("api_key", ""))
self._api_secret = QLineEdit(lf.get("api_secret", ""))
self._api_secret.setEchoMode(QLineEdit.EchoMode.Password)
self._username = QLineEdit(lf.get("username", ""))
self._password = QLineEdit()
self._password.setEchoMode(QLineEdit.EchoMode.Password)
form.addRow("API key:", self._api_key)
form.addRow("Shared secret:", self._api_secret)
form.addRow("Username:", self._username)
form.addRow("Password:", self._password)
button_row = QHBoxLayout()
self._login_button = QPushButton("Log in")
self._login_button.clicked.connect(self._on_login_clicked)
self._status_label = QLabel("")
button_row.addWidget(self._login_button)
button_row.addWidget(self._status_label)
button_row.addStretch()
form.addRow("", button_row)
self._scrobble_check = QCheckBox("Enable scrobbling")
self._scrobble_check.setChecked(lf.get("scrobble_enabled", False))
self._scrobble_check.toggled.connect(
lambda on: self._prefs.update_lastfm(scrobble_enabled=on))
form.addRow("", self._scrobble_check)
return group
def _on_login_clicked(self):
if self._lastfm.is_logged_in():
self._lastfm.logout()
self._refresh_lastfm_state()
return
api_key = self._api_key.text().strip()
secret = self._api_secret.text().strip()
username = self._username.text().strip()
password = self._password.text()
if not all((api_key, secret, username, password)):
self._status_label.setText("Fill in all four fields first")
return
self._login_button.setEnabled(False)
self._status_label.setText("Logging in…")
self._lastfm.login(api_key, secret, username, password)
def _on_login_finished(self, success: bool, message: str):
self._status_label.setText(message)
self._login_button.setEnabled(True)
if success:
self._password.clear()
self._refresh_lastfm_state()
def _refresh_lastfm_state(self):
logged_in = self._lastfm.is_logged_in()
self._login_button.setText("Log out" if logged_in else "Log in")
self._scrobble_check.setEnabled(logged_in)
if logged_in and not self._status_label.text():
self._status_label.setText(
f"Logged in as {self._prefs.lastfm.get('username', '')}")
# ---- Track identification (AcoustID) ----
def _build_acoustid_group(self) -> QGroupBox:
group = QGroupBox("Track Identification")
form = QFormLayout(group)
hint = QLabel(
'Right-click a track → Identify Track… Needs a free application '
'key: <a href="https://acoustid.org/new-application">'
'acoustid.org/new-application</a>')
hint.setOpenExternalLinks(True)
hint.setWordWrap(True)
form.addRow(hint)
self._acoustid_key = QLineEdit(
self._prefs.acoustid.get("api_key", ""))
self._acoustid_key.editingFinished.connect(self._save_acoustid_key)
form.addRow("AcoustID key:", self._acoustid_key)
return group
def _save_acoustid_key(self):
key = self._acoustid_key.text().strip()
if key != self._prefs.acoustid.get("api_key", ""):
self._prefs.update_acoustid(api_key=key)