They bob to the bass, dance when the music is fast and full, and lie down to sleep after a few seconds of quiet. Gray, highlight and black lines on the panel's gray; every frame re-wobbled, never tweened.
1395 lines
60 KiB
Python
1395 lines
60 KiB
Python
import math
|
||
import threading
|
||
|
||
from PyQt6.QtWidgets import (
|
||
QDialog, QVBoxLayout, QHBoxLayout, QGroupBox, QLabel, QSlider,
|
||
QRadioButton, QButtonGroup, QLineEdit, QPushButton, QCheckBox,
|
||
QFormLayout, QFontComboBox, QListWidget, QScrollArea, QSplitter,
|
||
QStackedWidget, QWidget, QDialogButtonBox, QFrame, QToolButton,
|
||
QColorDialog, QMenu, QDoubleSpinBox, QComboBox, QInputDialog,
|
||
QMessageBox, QApplication, QSizePolicy,
|
||
)
|
||
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
|
||
from PyQt6.QtGui import QDoubleValidator, QFont, QColor, QFontInfo
|
||
|
||
from lintunes import loudness, theme
|
||
from lintunes.config import load_config, save_config
|
||
from lintunes.export import upload
|
||
from lintunes.gui import visualizer_styles
|
||
from lintunes.gui.range_slider import RangeSlider
|
||
from lintunes.gui.scope_drawing import ScopeDrawing
|
||
from lintunes.gui.transport import ClickJumpSlider
|
||
from lintunes.gui.mac_tabs import MacTab, TabStrip
|
||
from lintunes.gui import visualizer_presets as presets
|
||
from lintunes.gui import sounds
|
||
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_base", "Lists:"),
|
||
("color_visualizer_gray", "Visualizer (gray mode):"),
|
||
]
|
||
|
||
|
||
# Room for the widest value a visualizer slider shows ("400 ms").
|
||
_VALUE_WIDTH = 56
|
||
|
||
|
||
def _viz_slider_widget() -> ClickJumpSlider:
|
||
"""The visualizer page's sliders: as tall as the seek bar, so they're
|
||
easy to hit, and a click puts the handle where it lands instead of
|
||
paging toward it."""
|
||
slider = ClickJumpSlider()
|
||
slider.setProperty("tall", True)
|
||
return slider
|
||
|
||
|
||
HEADING_EXTRA_PX = 2 # section headings: this much over the text
|
||
_EDIT_PRESETS = "\0edit" # the preset drop-down's last item
|
||
_SPEAKER_KEYS = ("visualizer_laser_low_hz", "visualizer_laser_high_hz")
|
||
|
||
# The oscilloscope's frequency range: 20 Hz – 20 kHz in log steps of 1/30 octave.
|
||
SPEAKER_STEPS = 300
|
||
|
||
|
||
def _step_to_hz(step: int) -> int:
|
||
lo, hi = visualizer_styles.LIMITS["visualizer_laser_low_hz"]
|
||
return int(round(lo * (hi / lo) ** (step / SPEAKER_STEPS)))
|
||
|
||
|
||
def _hz_to_step(hz: float) -> int:
|
||
lo, hi = visualizer_styles.LIMITS["visualizer_laser_low_hz"]
|
||
return int(round(SPEAKER_STEPS * math.log(max(lo, hz) / lo) / math.log(hi / lo)))
|
||
|
||
|
||
def _speaker_gap() -> int:
|
||
"""The third-octave the speaker can't be narrower than, in steps."""
|
||
lo, hi = visualizer_styles.LIMITS["visualizer_laser_low_hz"]
|
||
return math.ceil(SPEAKER_STEPS * math.log(visualizer_styles.SPEAKER_MIN_RATIO)
|
||
/ math.log(hi / lo))
|
||
|
||
|
||
def _hz_text(hz: int) -> str:
|
||
if hz < 1000:
|
||
return f"{hz} Hz"
|
||
return f"{hz / 1000:.1f}".removesuffix(".0") + " kHz"
|
||
|
||
|
||
def _fade_text(seconds: float) -> str:
|
||
return "Off" if seconds <= 0 else f"{seconds:.2f} s"
|
||
|
||
|
||
# visualizer_styles' style keys, as the radios name them.
|
||
_VISUALIZER_STYLES = visualizer_styles.STYLE_NAMES
|
||
|
||
|
||
def _dot_text(scale: float) -> str:
|
||
"""The radial dot size as a share of the spacing between dots. The pref
|
||
is a multiple of the automatic size, which is 70% of that spacing."""
|
||
return f"{round(scale * visualizer_styles.RADIAL_DOT_SHARE * 100)}%"
|
||
|
||
|
||
def _sync_text(ms: int) -> str:
|
||
if ms < 0:
|
||
return f"{-ms} ms sooner"
|
||
return f"{ms} ms later" if ms else "0 ms"
|
||
|
||
|
||
class PreferencesDialog(QDialog):
|
||
"""App preferences. Applies immediately — there is no OK/Cancel.
|
||
|
||
Laid out like VLC's (and Sync Settings'): categories on the left, the
|
||
chosen page on the right — General, Appearance, Integrations.
|
||
|
||
``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.
|
||
"""
|
||
|
||
# The split cache's size in bytes, measured on a worker thread.
|
||
_stem_cache_measured = pyqtSignal(int)
|
||
|
||
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)
|
||
|
||
self._headings = []
|
||
general = [self._build_playback_group(), self._build_import_group(),
|
||
self._build_sound_group(), self._build_wrapped_group()]
|
||
if self._music_folder is not None:
|
||
general.insert(0, self._build_music_group())
|
||
self.pages_list = QListWidget()
|
||
self.pages = QStackedWidget()
|
||
for title, groups in (
|
||
("General", general),
|
||
("Appearance", [self._build_general_group(),
|
||
self._build_colors_group()]),
|
||
("Visualizer", [self._build_visualizer_group()]),
|
||
("DJ", [self._build_dj_engine_group(), self._build_dj_group(),
|
||
self._build_dj_cache_group()]),
|
||
("Integrations", [self._build_lastfm_group(),
|
||
self._build_acoustid_group(),
|
||
self._build_web_server_group()])):
|
||
self._add_page(title, groups)
|
||
self.pages_list.currentRowChanged.connect(self._show_page)
|
||
self._style_headings()
|
||
self._prefs.changed.connect(self._style_headings)
|
||
|
||
splitter = QSplitter(Qt.Orientation.Horizontal)
|
||
splitter.addWidget(self.pages_list)
|
||
splitter.addWidget(self.pages)
|
||
splitter.setCollapsible(1, False)
|
||
list_width = self.pages_list.sizeHintForColumn(0) + 32
|
||
self.pages_list.setFixedWidth(list_width)
|
||
splitter.setStretchFactor(1, 1)
|
||
|
||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||
buttons.rejected.connect(self.reject)
|
||
|
||
layout = QVBoxLayout(self)
|
||
layout.addWidget(splitter, stretch=1)
|
||
layout.addWidget(buttons)
|
||
|
||
# Open big enough for the tallest page, so nothing starts cut off
|
||
# (the scroll areas are only a net for a small screen).
|
||
tallest = max(self.pages.widget(i).widget().sizeHint().height()
|
||
for i in range(self.pages.count()))
|
||
widest = max(self.pages.widget(i).widget().sizeHint().width()
|
||
for i in range(self.pages.count()))
|
||
screen = self.screen().availableGeometry() if self.screen() else None
|
||
height = tallest + buttons.sizeHint().height() + 48
|
||
if screen is not None:
|
||
height = min(height, screen.height() - 80)
|
||
self.resize(list_width + widest + 64, height)
|
||
self.pages_list.setCurrentRow(PreferencesDialog._last_page)
|
||
|
||
lastfm.login_finished.connect(self._on_login_finished)
|
||
self._refresh_lastfm_state()
|
||
|
||
_last_page = 0 # the page last viewed, for this session only
|
||
|
||
def _add_page(self, title: str, groups: list):
|
||
body = QWidget()
|
||
column = QVBoxLayout(body)
|
||
for group in groups:
|
||
# The heading is a label of its own above the box, not the box's
|
||
# title: a font set on a QGroupBox spreads to everything in it.
|
||
header = QLabel(group.title())
|
||
header.setObjectName("prefs-heading")
|
||
group.setTitle("")
|
||
self._headings.append(header)
|
||
column.addWidget(header)
|
||
column.addWidget(group)
|
||
column.addStretch()
|
||
scroll = QScrollArea()
|
||
scroll.setWidgetResizable(True)
|
||
scroll.setFrameShape(QFrame.Shape.NoFrame)
|
||
scroll.setHorizontalScrollBarPolicy(
|
||
Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||
# Never narrower than the page wants: only height may scroll.
|
||
scroll.setMinimumWidth(body.sizeHint().width()
|
||
+ scroll.verticalScrollBar().sizeHint().width())
|
||
scroll.setWidget(body)
|
||
self.pages.addWidget(scroll)
|
||
self.pages_list.addItem(title)
|
||
|
||
def _style_headings(self):
|
||
"""Section headings: bold, 2 px larger than the text. Re-run when
|
||
the UI size changes, since the app font moves with it."""
|
||
size = QFontInfo(QApplication.font()).pixelSize() + HEADING_EXTRA_PX
|
||
for header in self._headings:
|
||
# A style sheet, not setFont: the app's own style sheet (theme)
|
||
# re-polishes widgets and would quietly put the plain font back.
|
||
header.setStyleSheet(f"font-weight: bold; font-size: {size}px;")
|
||
|
||
def _show_page(self, row: int):
|
||
self.pages.setCurrentIndex(row)
|
||
PreferencesDialog._last_page = row
|
||
|
||
# ---- Playback ----
|
||
|
||
def _build_playback_group(self) -> QGroupBox:
|
||
group = QGroupBox("Playback")
|
||
column = QVBoxLayout(group)
|
||
self._normalize_check = QCheckBox("Normalize volume")
|
||
self._normalize_check.setChecked(
|
||
bool(self._prefs.get("normalize_volume", False)))
|
||
self._normalize_check.toggled.connect(
|
||
lambda on: self._prefs.set("normalize_volume", on))
|
||
column.addWidget(self._normalize_check)
|
||
if loudness.ffmpeg_available():
|
||
note = ("Plays every song at the same loudness, so a quiet old "
|
||
"recording and a loud new one sit at one level. Each song "
|
||
"is measured once as it comes up; the files aren't "
|
||
"changed. Quiet songs can only be raised while the volume "
|
||
"slider is below the top.")
|
||
else:
|
||
note = "Needs ffmpeg, which isn't installed."
|
||
self._normalize_check.setEnabled(False)
|
||
column.addWidget(self._note(note))
|
||
# Controls → Normalize Volume flips the same pref while this is open.
|
||
self._prefs.changed.connect(self._sync_normalize_check)
|
||
return group
|
||
|
||
def _sync_normalize_check(self):
|
||
on = bool(self._prefs.get("normalize_volume", False))
|
||
if self._normalize_check.isChecked() != on:
|
||
self._normalize_check.blockSignals(True)
|
||
self._normalize_check.setChecked(on)
|
||
self._normalize_check.blockSignals(False)
|
||
|
||
# ---- Sound ----
|
||
|
||
def _build_import_group(self) -> QGroupBox:
|
||
"""Compress lossless imports (importers/lossless.py)."""
|
||
from lintunes.importers import lossless
|
||
group = QGroupBox("Importing")
|
||
column = QVBoxLayout(group)
|
||
row = QHBoxLayout()
|
||
on, kbps = lossless.settings(self._prefs)
|
||
self._compress_check = QCheckBox("Compress lossless imports to MP3 at")
|
||
self._compress_check.setToolTip(
|
||
"FLAC, WAV, AIFF and Apple Lossless files you add are converted to "
|
||
"MP3, and the MP3 goes in your library. The file you added from "
|
||
"isn't changed or moved.")
|
||
self._compress_check.setChecked(on)
|
||
self._compress_kbps = QComboBox()
|
||
for rate in lossless.BITRATES:
|
||
self._compress_kbps.addItem(f"{rate} kbps", rate)
|
||
self._compress_kbps.setCurrentIndex(lossless.BITRATES.index(kbps))
|
||
self._compress_kbps.setEnabled(on)
|
||
self._compress_cassette = QCheckBox("Convert songs from Cassette friends too")
|
||
self._compress_cassette.setToolTip(
|
||
"Lossless songs a friend sends you are converted before they go "
|
||
"in your library. Songs from playlists you follow aren't.")
|
||
self._compress_cassette.setChecked(
|
||
bool(self._prefs.get("import_compress_cassette", False)))
|
||
self._compress_cassette.setEnabled(on)
|
||
self._compress_cassette.toggled.connect(
|
||
lambda checked: self._prefs.set("import_compress_cassette", checked))
|
||
self._compress_check.toggled.connect(self._on_compress_toggled)
|
||
self._compress_kbps.currentIndexChanged.connect(
|
||
lambda _i: self._prefs.set("import_compress_kbps",
|
||
self._compress_kbps.currentData()))
|
||
row.addWidget(self._compress_check)
|
||
row.addWidget(self._compress_kbps)
|
||
row.addStretch(1)
|
||
column.addLayout(row)
|
||
column.addWidget(self._compress_cassette)
|
||
if lossless.ffmpeg_available():
|
||
note = ("FLAC, WAV, AIFF and Apple Lossless files you add are "
|
||
"converted, and the MP3 goes in your library — a fraction "
|
||
"of the size. The file you added from isn't changed or "
|
||
"moved. To shrink songs already in your library, "
|
||
"right-click them and choose Convert to MP3.")
|
||
else:
|
||
note = "Needs ffmpeg, which isn't installed."
|
||
self._compress_check.setEnabled(False)
|
||
self._compress_cassette.setEnabled(False)
|
||
column.addWidget(self._note(note))
|
||
return group
|
||
|
||
def _on_compress_toggled(self, on: bool):
|
||
self._compress_kbps.setEnabled(on)
|
||
self._compress_cassette.setEnabled(on)
|
||
self._prefs.set("import_compress", on)
|
||
|
||
def _build_sound_group(self) -> QGroupBox:
|
||
group = QGroupBox("Sound effects")
|
||
row = QHBoxLayout(group)
|
||
self._sound_check = QCheckBox("Play a sound when a sync, export or "
|
||
"import finishes")
|
||
self._sound_check.setChecked(bool(self._prefs.get("sound_effects", True)))
|
||
self._sound_check.toggled.connect(
|
||
lambda on: self._prefs.set("sound_effects", on))
|
||
row.addWidget(self._sound_check, stretch=1)
|
||
preview = QPushButton("Play")
|
||
preview.clicked.connect(lambda: sounds.play_done(self._prefs, force=True))
|
||
row.addWidget(preview)
|
||
return group
|
||
|
||
# ---- DJ ----
|
||
|
||
def _build_dj_engine_group(self) -> QGroupBox:
|
||
"""Instant (Spleeter) or High quality (Demucs): which a deck starts
|
||
splitting with, and the download that unlocks Instant on this
|
||
computer. Each deck can swap its song to the other."""
|
||
from lintunes.dj import instant, stems
|
||
group = QGroupBox("Vocal splitting")
|
||
column = QVBoxLayout(group)
|
||
column.addWidget(QLabel("When a song loads onto a deck, start splitting with:"))
|
||
self._dj_engine_group = QButtonGroup(self)
|
||
self._dj_engine_radios = {}
|
||
for engine, text in ((stems.FAST, "Instant (Spleeter): seconds a song, rougher vocals"),
|
||
(stems.HQ, "High quality (Demucs, the model below): "
|
||
"minutes a song, clean vocals")):
|
||
radio = QRadioButton(text)
|
||
self._dj_engine_group.addButton(radio)
|
||
self._dj_engine_radios[engine] = radio
|
||
column.addWidget(radio)
|
||
chosen = self._prefs.get("dj_stem_default", stems.HQ)
|
||
self._dj_engine_radios[stems.FAST if chosen == stems.FAST else stems.HQ].setChecked(True)
|
||
for engine, radio in self._dj_engine_radios.items():
|
||
radio.toggled.connect(
|
||
lambda on, e=engine: on and self._prefs.set("dj_stem_default", e))
|
||
self._dj_instant_note = self._note("")
|
||
column.addWidget(self._dj_instant_note)
|
||
row = QHBoxLayout()
|
||
self._dj_instant_button = QPushButton()
|
||
self._dj_instant_button.clicked.connect(self._on_instant_button)
|
||
row.addWidget(self._dj_instant_button)
|
||
row.addStretch(1)
|
||
column.addLayout(row)
|
||
self._instant_setup = None
|
||
self._refresh_instant()
|
||
return group
|
||
|
||
def _refresh_instant(self, note: str | None = None):
|
||
from lintunes.dj import instant
|
||
ready = instant.available()
|
||
busy = self._instant_setup is not None and self._instant_setup.busy()
|
||
self._dj_engine_radios["instant"].setEnabled(ready)
|
||
button = self._dj_instant_button
|
||
button.setEnabled(not busy)
|
||
if ready:
|
||
button.setText("Remove Instant Vocal Splitting")
|
||
text = ("Instant vocal splitting is set up on this computer. Each deck "
|
||
"has a button to swap its song between Instant and HQ.")
|
||
else:
|
||
button.setText(f"Download Instant Vocal Splitting (Spleeter, "
|
||
f"~{instant.DOWNLOAD_MB} MB)")
|
||
text = ("Instant isn't set up on this computer yet. Until it is, decks "
|
||
"split with Demucs.")
|
||
self._dj_instant_note.setText(note or text)
|
||
|
||
def _on_instant_button(self):
|
||
from lintunes.dj import instant
|
||
if instant.available():
|
||
instant.remove()
|
||
if self._prefs.get("dj_stem_default") == "instant":
|
||
self._dj_engine_radios["hq"].setChecked(True)
|
||
self._refresh_instant()
|
||
return
|
||
setup = instant.InstantSetup(self)
|
||
setup.progress.connect(lambda text: self._refresh_instant(text))
|
||
setup.finished.connect(lambda: self._refresh_instant())
|
||
setup.failed.connect(lambda why: self._refresh_instant(f"Couldn't set it up: {why}"))
|
||
self._instant_setup = setup
|
||
setup.start()
|
||
self._refresh_instant("Starting…")
|
||
|
||
def _build_dj_group(self) -> QGroupBox:
|
||
"""Vocals separation (Demucs): which model, and how hard it may run
|
||
the CPU. Both apply to the next song split."""
|
||
from lintunes.dj import stems
|
||
group = QGroupBox("High quality (Demucs)")
|
||
form = QFormLayout(group)
|
||
model = QComboBox()
|
||
for key, (label, cost) in stems.MODELS.items():
|
||
model.addItem(f"{label} — {cost}", key)
|
||
model.setCurrentIndex(max(0, model.findData(stems.model_choice(self._prefs))))
|
||
model.currentIndexChanged.connect(
|
||
lambda _i: self._prefs.set("dj_stem_model", model.currentData()))
|
||
form.addRow("Model:", model)
|
||
gentle = QCheckBox("Gentle on the CPU: a quarter of the cores, lowest "
|
||
"priority (cooler, a little slower)")
|
||
gentle.setChecked(stems.gentle_choice(self._prefs))
|
||
gentle.toggled.connect(lambda on: self._prefs.set("dj_stem_gentle", on))
|
||
form.addRow("", gentle)
|
||
if stems.available():
|
||
note = QLabel("Demucs is set up. Songs are split when they load onto "
|
||
"a deck, or ahead of time with a playlist's or "
|
||
"song's “Prepare for DJ”.")
|
||
else:
|
||
note = QLabel("Demucs isn't set up on this computer (a one-time ~1 GB "
|
||
"download). In a terminal:\n" + stems.setup_command())
|
||
note.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||
note.setWordWrap(True)
|
||
form.addRow("", note)
|
||
self._dj_model_combo = model
|
||
self._dj_gentle_check = gentle
|
||
return group
|
||
|
||
def _build_dj_cache_group(self) -> QGroupBox:
|
||
"""How much disk the saved vocal splits (both engines) may take,
|
||
and how much they take now."""
|
||
from lintunes.dj import stems
|
||
group = QGroupBox("Saved vocal splits")
|
||
form = QFormLayout(group)
|
||
form.addRow(self._note(
|
||
"Each song split into vocals and instrumental is saved on this "
|
||
"computer, so the vocals slider works at once the next time it's "
|
||
"on a deck. Past the limit, the songs used longest ago are "
|
||
"deleted; they're split again if you load them later."))
|
||
cache = QLineEdit(f"{stems.cache_limit_gb():g}")
|
||
cache.setValidator(QDoubleValidator(0.0, 10000.0, 2, cache))
|
||
cache.setMaximumWidth(80)
|
||
cache.editingFinished.connect(self._save_stem_cache_limit)
|
||
cache_row = QHBoxLayout()
|
||
cache_row.addWidget(cache)
|
||
cache_row.addWidget(QLabel("GB"))
|
||
cache_row.addStretch(1)
|
||
form.addRow("Keep up to:", cache_row)
|
||
self._dj_cache_edit = cache
|
||
self._dj_cache_used = QLabel("Measuring…")
|
||
form.addRow("Using now:", self._dj_cache_used)
|
||
self._stem_cache_measured.connect(self._show_stem_cache_used)
|
||
self._measure_stem_cache()
|
||
return group
|
||
|
||
def _measure_stem_cache(self, prune_to: float | None = None):
|
||
"""Walk the cache off the GUI thread (pruning first, when given a
|
||
new limit) and report its size back through a signal."""
|
||
from lintunes.dj import stems
|
||
|
||
def work():
|
||
if prune_to is not None:
|
||
stems.prune(prune_to)
|
||
try:
|
||
self._stem_cache_measured.emit(stems.cache_size())
|
||
except RuntimeError:
|
||
pass # the dialog was closed meanwhile
|
||
|
||
threading.Thread(target=work, daemon=True,
|
||
name="lintunes-stems-measure").start()
|
||
|
||
def _show_stem_cache_used(self, size: int):
|
||
gb = size / 1024 ** 3
|
||
text = f"{gb:.2f} GB" if gb >= 0.1 else f"{size / 1024 ** 2:.0f} MB"
|
||
self._dj_cache_used.setText(text)
|
||
|
||
def _save_stem_cache_limit(self):
|
||
"""config.json, not preferences: how much disk to give the splits
|
||
is this machine's business. A lower limit applies at once."""
|
||
from lintunes.dj import stems
|
||
try:
|
||
value = float(self._dj_cache_edit.text().replace(",", "."))
|
||
except ValueError:
|
||
self._dj_cache_edit.setText(f"{stems.cache_limit_gb():g}")
|
||
return
|
||
config = load_config()
|
||
if config.get(stems.CACHE_LIMIT_KEY) == value:
|
||
return
|
||
config[stems.CACHE_LIMIT_KEY] = value
|
||
save_config(config)
|
||
self._measure_stem_cache(prune_to=value)
|
||
|
||
# ---- Wrapped ----
|
||
|
||
def _build_wrapped_group(self) -> QGroupBox:
|
||
group = QGroupBox("Yearly Wrapped")
|
||
column = QVBoxLayout(group)
|
||
wrapped = self._prefs.wrapped
|
||
self._history_check = QCheckBox(
|
||
"Keep a play history for my yearly Wrapped")
|
||
self._history_check.setChecked(bool(wrapped.get("track_history")))
|
||
column.addWidget(self._history_check)
|
||
column.addWidget(self._note(
|
||
"Every song you listen to, here and on the Rabbit: when, for how "
|
||
"long, and whether you finished it. Kept in the library folder; "
|
||
"nothing leaves your machines."))
|
||
self._share_history_check = QCheckBox(
|
||
"Share this year's play history with friends")
|
||
self._share_history_check.setChecked(
|
||
bool(wrapped.get("share_with_friends")))
|
||
column.addWidget(self._share_history_check)
|
||
column.addWidget(self._note(
|
||
"Goes in your cassette folder for each friend: what you played, "
|
||
"when and for how long — no playlists or devices. Refreshed "
|
||
"monthly, and daily in November and December."))
|
||
self._share_history_check.setEnabled(self._history_check.isChecked())
|
||
self._history_check.toggled.connect(self._on_history_toggled)
|
||
self._share_history_check.toggled.connect(
|
||
lambda on: self._prefs.update_wrapped(share_with_friends=on))
|
||
return group
|
||
|
||
@staticmethod
|
||
def _note(text: str) -> QLabel:
|
||
label = QLabel(text)
|
||
label.setWordWrap(True)
|
||
label.setEnabled(False) # the dimmed sub-label look
|
||
label.setContentsMargins(24, 0, 0, 6)
|
||
return label
|
||
|
||
def _on_history_toggled(self, on: bool):
|
||
self._share_history_check.setEnabled(on)
|
||
self._prefs.update_wrapped(track_history=on)
|
||
|
||
# ---- Appearance ----
|
||
|
||
def _build_general_group(self) -> QGroupBox:
|
||
group = QGroupBox("Interface")
|
||
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)
|
||
|
||
self._dark_check = QCheckBox("Dark mode")
|
||
self._dark_check.setToolTip("Dark mode has its own colors and tint "
|
||
"(Colors, below); the highlight is shared")
|
||
self._dark_check.setChecked(theme.mode(self._prefs) == "dark")
|
||
self._dark_check.toggled.connect(self._on_dark_toggled)
|
||
form.addRow("Mode:", self._dark_check)
|
||
# The toolbar's light/dark button flips the same pref while this is open.
|
||
self._prefs.changed.connect(self._sync_dark_check)
|
||
|
||
self._menu_bar_check = QCheckBox("Hide the menu bar until Alt is pressed")
|
||
self._menu_bar_check.setToolTip(
|
||
"Tap Alt to show it, or press Alt and a menu's letter (Alt+F for "
|
||
"File); shortcuts like Ctrl+N work either way")
|
||
self._menu_bar_check.setChecked(self._prefs.get("menu_bar", "always") == "alt")
|
||
self._menu_bar_check.toggled.connect(
|
||
lambda on: self._prefs.set("menu_bar", "alt" if on else "always"))
|
||
form.addRow("Menu bar:", self._menu_bar_check)
|
||
|
||
# Highlight color: a radio per slot, and beside it the slot's swatch,
|
||
# which opens a full color picker; the color picked replaces that
|
||
# slot's (right-click the swatch to put the original back).
|
||
color_row = QHBoxLayout()
|
||
self._color_group = QButtonGroup(self)
|
||
self._color_radios, self._swatches = {}, {}
|
||
for name in HIGHLIGHT_COLORS:
|
||
swatch = QToolButton()
|
||
swatch.setAutoRaise(True)
|
||
swatch.clicked.connect(lambda _=False, n=name: self._choose_color(n))
|
||
swatch.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
||
swatch.customContextMenuRequested.connect(
|
||
lambda point, n=name: self._swatch_menu(n, point))
|
||
radio = QRadioButton()
|
||
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)
|
||
self._color_radios[name], self._swatches[name] = radio, swatch
|
||
color_row.addWidget(swatch)
|
||
color_row.addWidget(radio)
|
||
color_row.addSpacing(6)
|
||
self._show_palette()
|
||
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 _show_palette(self):
|
||
palette = theme.highlight_palette(self._prefs)
|
||
saved = self._prefs.get("highlight_palette") or {}
|
||
for name, swatch in self._swatches.items():
|
||
custom = name in saved
|
||
swatch.setIcon(theme.swatch_icon(palette[name]))
|
||
swatch.setToolTip(
|
||
f"{palette[name]} — click to pick a color"
|
||
+ (f"; right-click to restore {name}" if custom else ""))
|
||
self._color_radios[name].setText("custom" if custom else name)
|
||
|
||
def _pick_color(self, initial: QColor) -> QColor:
|
||
return QColorDialog.getColor(initial, self, "Highlight Color")
|
||
|
||
def _choose_color(self, name: str):
|
||
initial = QColor(theme.highlight_palette(self._prefs)[name])
|
||
picked = self._pick_color(initial)
|
||
if not picked.isValid():
|
||
return # cancelled
|
||
self._set_slot(name, picked.name())
|
||
self._color_radios[name].setChecked(True) # use what was just picked
|
||
|
||
def _set_slot(self, name: str, value):
|
||
saved = dict(self._prefs.get("highlight_palette") or {})
|
||
if value is None or QColor(value) == QColor(HIGHLIGHT_COLORS[name]):
|
||
saved.pop(name, None)
|
||
else:
|
||
saved[name] = value
|
||
self._prefs.set("highlight_palette", saved)
|
||
self._show_palette()
|
||
|
||
def _swatch_menu(self, name: str, point):
|
||
if name not in (self._prefs.get("highlight_palette") or {}):
|
||
return
|
||
menu = QMenu(self)
|
||
menu.addAction(f"Restore {name.capitalize()}",
|
||
lambda: self._set_slot(name, None))
|
||
menu.exec(self._swatches[name].mapToGlobal(point))
|
||
|
||
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 ----
|
||
|
||
# ---- Visualizer ----
|
||
|
||
def _build_visualizer_group(self) -> QGroupBox:
|
||
group = QGroupBox("Visualizer")
|
||
column = QVBoxLayout(group)
|
||
config = visualizer_styles.settings(self._prefs)
|
||
|
||
style_row = QHBoxLayout()
|
||
self._viz_style = QButtonGroup(self)
|
||
self._viz_radios = {}
|
||
current = self._prefs.get("visualizer_style", "bars")
|
||
if current not in _VISUALIZER_STYLES:
|
||
current = "bars"
|
||
for key, label in _VISUALIZER_STYLES.items():
|
||
radio = QRadioButton(label)
|
||
radio.setChecked(key == current) # before connect
|
||
radio.toggled.connect(
|
||
lambda on, k=key: on and self._on_viz_style(k))
|
||
self._viz_style.addButton(radio)
|
||
self._viz_radios[key] = radio
|
||
style_row.addWidget(radio)
|
||
style_row.addStretch()
|
||
style_form = QFormLayout()
|
||
style_form.addRow("Style:", style_row)
|
||
column.addLayout(style_form)
|
||
|
||
# Only the chosen style's settings are shown.
|
||
self._viz_pages = QStackedWidget()
|
||
self._viz_setters = {} # key → puts a value into its control
|
||
self._sync_sliders = {} # style → its sync delay slider
|
||
self._sync_save_timer = QTimer(self)
|
||
self._sync_save_timer.setSingleShot(True)
|
||
self._sync_save_timer.setInterval(300)
|
||
self._sync_save_timer.timeout.connect(self._save_sync_delay)
|
||
self._preset_combos = {} # style → its preset drop-down
|
||
fade_tip = ("How long what's left behind takes to fade into the "
|
||
"background — 0 is no trail")
|
||
|
||
bars = QWidget()
|
||
form = self._viz_form(bars)
|
||
self._preset_row(form, "bars")
|
||
self._sync_delay_slider(form, "bars")
|
||
self._bars_count_box = self._viz_spinbox(
|
||
form, "Bars:", "visualizer_bars_count", config, step=1, decimals=0,
|
||
suffix="", tip="How many bars, 1 to 1024. Past the drawing's width "
|
||
"it's one bar per pixel, SoundJam style")
|
||
self._bars_fade_slider, _ = self._viz_slider(
|
||
form, "Fade:", "visualizer_bars_fade", config, scale=20,
|
||
fmt=_fade_text, tip=fade_tip)
|
||
self._viz_pages.addWidget(bars)
|
||
|
||
radial = QWidget()
|
||
form = self._viz_form(radial)
|
||
self._preset_row(form, "radial")
|
||
self._sync_delay_slider(form, "radial")
|
||
self._fade_slider, _ = self._viz_slider(
|
||
form, "Fade:", "visualizer_ghost_fade", config, scale=20,
|
||
fmt=_fade_text, tip=fade_tip)
|
||
self._spokes_slider, _ = self._viz_slider(
|
||
form, "Frequency bands:", "visualizer_radial_spokes", config,
|
||
tip="How many slices of the spectrum go around the circle")
|
||
self._levels_slider, _ = self._viz_slider(
|
||
form, "Volume steps:", "visualizer_radial_levels", config,
|
||
tip="How many positions each dot can take, center to rim")
|
||
self._radial_dot_slider, _ = self._viz_slider(
|
||
form, "Dot size:", "visualizer_radial_dot", config, scale=100,
|
||
fmt=_dot_text,
|
||
tip="How much of the space between neighbouring dots each dot "
|
||
"fills: at 100% they touch, past it they overlap. A share "
|
||
"of the spacing rather than pixels, because the spacing "
|
||
"changes with the drawing's size (the panel or the big "
|
||
"window) and with the bands and steps above")
|
||
self._normalize = self._viz_check(
|
||
form, "Even out bass and treble", "visualizer_radial_normalize",
|
||
config, tip="Music is loudest in the bass. This learns the "
|
||
"song's overall balance and takes it out, so the "
|
||
"dots sit on a circle and move with the music")
|
||
self._viz_pages.addWidget(radial)
|
||
|
||
laser = QWidget()
|
||
form = self._viz_form(laser)
|
||
self._preset_row(form, "laser")
|
||
self._sync_delay_slider(form, "laser")
|
||
self._laser_fade_box = self._viz_spinbox(
|
||
form, "Afterimage:", "visualizer_laser_afterimage", config,
|
||
step=0.05, decimals=2, suffix=" s", off_text="Off",
|
||
tip="How long past sweeps of the beam take to fade — 0 is none")
|
||
self._speaker = self._speaker_range(form, config)
|
||
# The look controls on the left, a still drawing of a scope beside.
|
||
looks = self._viz_form(None)
|
||
self._width_box = self._viz_spinbox(
|
||
looks, "Line width:", "visualizer_laser_width", config,
|
||
step=0.5, decimals=1, suffix=" px")
|
||
self._glow = self._viz_check(
|
||
looks, "Glow", "visualizer_laser_glow", config,
|
||
tip="The haze around the beam")
|
||
self._grid = self._viz_check(
|
||
looks, "Graticule", "visualizer_laser_grid", config,
|
||
tip="The grid of gray dots on an oscilloscope's screen, painted "
|
||
"under the beam")
|
||
self._head = self._viz_check(
|
||
looks, "Dot at the tip of the beam", "visualizer_laser_head",
|
||
config, tip="When the music is silent the beam rests as a dot "
|
||
"in the middle either way")
|
||
beside = QHBoxLayout()
|
||
beside.addLayout(looks)
|
||
beside.addSpacing(12)
|
||
beside.addStretch()
|
||
beside.addWidget(ScopeDrawing())
|
||
form.addRow(beside)
|
||
self._dot_slider, _ = self._viz_slider(
|
||
form, "Tip dot size:", "visualizer_laser_dot", config, scale=2,
|
||
fmt=lambda v: f"{v:g} px",
|
||
tip="The dot at the beam's tip, and the resting dot in silence")
|
||
self._grid_dot_slider, _ = self._viz_slider(
|
||
form, "Graticule dot size:", "visualizer_laser_grid_dot", config,
|
||
scale=100, fmt=lambda v: f"{round(v * 100)}%",
|
||
tip="100% is the size that suits the screen's size")
|
||
self._viz_pages.addWidget(laser)
|
||
|
||
kaleido = QWidget()
|
||
form = self._viz_form(kaleido)
|
||
self._sync_delay_slider(form, "kaleidostrobe")
|
||
about = QLabel(
|
||
"The 2002 iTunes visualizer by Shehryar Lasi, rebuilt from its "
|
||
"original code. It has no settings: the Color and Flash boxes "
|
||
"it once showed were never connected to anything.")
|
||
about.setWordWrap(True)
|
||
about.setEnabled(False)
|
||
form.addRow(about)
|
||
self._viz_pages.addWidget(kaleido)
|
||
|
||
lint = QWidget()
|
||
form = self._viz_form(lint)
|
||
self._sync_delay_slider(form, "lint")
|
||
about = QLabel(
|
||
"Three balls of lint in headphones: they bob to the bass, dance "
|
||
"when the music is fast and full, and fall asleep when it goes "
|
||
"quiet. No settings yet.")
|
||
about.setWordWrap(True)
|
||
about.setEnabled(False)
|
||
form.addRow(about)
|
||
self._viz_pages.addWidget(lint)
|
||
|
||
self._viz_pages.setCurrentIndex(list(_VISUALIZER_STYLES).index(current))
|
||
self._fit_viz_pages()
|
||
column.addWidget(self._viz_pages)
|
||
|
||
note = QLabel("Click the visualizer to see it big.")
|
||
note.setEnabled(False)
|
||
column.addWidget(note)
|
||
return group
|
||
|
||
@staticmethod
|
||
def _viz_form(page) -> QFormLayout:
|
||
form = QFormLayout(page) if page is not None else QFormLayout()
|
||
form.setContentsMargins(0, 0, 0, 0)
|
||
# Sliders run the full width of the window.
|
||
form.setFieldGrowthPolicy(
|
||
QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
|
||
return form
|
||
|
||
def _viz_spinbox(self, form, label, key, config, *, step, decimals,
|
||
suffix, off_text="", tip="") -> QDoubleSpinBox:
|
||
"""A setting as a number: type it, or step it with the arrows
|
||
(buttons or ↑/↓). ``off_text`` is shown in place of the minimum."""
|
||
lo, hi = visualizer_styles.LIMITS[key]
|
||
box = QDoubleSpinBox()
|
||
box.setRange(lo, hi)
|
||
box.setSingleStep(step)
|
||
box.setDecimals(decimals)
|
||
box.setSuffix(suffix)
|
||
box.setToolTip(tip)
|
||
if off_text:
|
||
box.setSpecialValueText(off_text)
|
||
box.setValue(config[key]) # before connect
|
||
|
||
def changed(value):
|
||
self._prefs.set_live(key, value)
|
||
self._color_save_timer.start()
|
||
|
||
box.valueChanged.connect(changed)
|
||
row = QHBoxLayout()
|
||
row.addWidget(box)
|
||
row.addStretch()
|
||
form.addRow(label, row)
|
||
self._viz_setters[key] = box.setValue
|
||
return box
|
||
|
||
# ---- Visualizer presets ----
|
||
|
||
def _preset_row(self, form, style: str):
|
||
combo = QComboBox()
|
||
combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToContents)
|
||
combo.activated.connect(
|
||
lambda index, s=style: self._on_preset_chosen(s, index))
|
||
save = QPushButton("Save as Preset…")
|
||
save.clicked.connect(lambda _=False, s=style: self._save_preset(s))
|
||
row = QHBoxLayout()
|
||
row.addWidget(combo, stretch=1)
|
||
row.addWidget(save)
|
||
form.addRow("Preset:", row)
|
||
self._preset_combos[style] = combo
|
||
self._sync_preset_combo(style)
|
||
if len(self._preset_combos) == 1:
|
||
# Any change — a slider, a preset applied, an edit on the other
|
||
# machine — may make the settings match a preset, or stop.
|
||
self._prefs.changed.connect(self._sync_preset_combos)
|
||
|
||
def _sync_preset_combos(self):
|
||
for style in self._preset_combos:
|
||
self._sync_preset_combo(style)
|
||
|
||
def _sync_preset_combo(self, style: str):
|
||
"""List the presets, showing the one the settings match — or
|
||
"Custom" when they match none (unsaved changes)."""
|
||
combo = self._preset_combos[style]
|
||
match = presets.matching(self._prefs, style)
|
||
combo.blockSignals(True)
|
||
combo.clear()
|
||
if match is None:
|
||
combo.addItem("Custom", None)
|
||
for name in presets.names(self._prefs, style):
|
||
combo.addItem(name, name)
|
||
combo.insertSeparator(combo.count())
|
||
combo.addItem("Edit Presets…", _EDIT_PRESETS)
|
||
combo.setCurrentIndex(0 if match is None else combo.findData(match))
|
||
combo.blockSignals(False)
|
||
|
||
def _on_preset_chosen(self, style: str, index: int):
|
||
choice = self._preset_combos[style].itemData(index)
|
||
if choice == _EDIT_PRESETS:
|
||
self._edit_presets(style)
|
||
elif choice is not None:
|
||
self._apply_preset(style, choice)
|
||
self._sync_preset_combo(style)
|
||
|
||
def _apply_preset(self, style: str, name: str):
|
||
"""Move the controls to the preset; they save it as if dragged."""
|
||
values = presets.values_of(self._prefs, style, name)
|
||
for key, value in values.items():
|
||
if key not in _SPEAKER_KEYS:
|
||
self._viz_setters[key](value)
|
||
if style == "laser":
|
||
self._speaker.setValues(
|
||
_hz_to_step(values["visualizer_laser_low_hz"]),
|
||
_hz_to_step(values["visualizer_laser_high_hz"]))
|
||
|
||
def _save_preset(self, style: str):
|
||
suggestion = presets.matching(self._prefs, style) or ""
|
||
if suggestion == presets.DEFAULT_NAME:
|
||
suggestion = ""
|
||
name = (self._ask_preset_name(suggestion) or "").strip()
|
||
if not name:
|
||
return
|
||
if name == presets.DEFAULT_NAME:
|
||
self._preset_warning(
|
||
f"“{name}” is the built-in preset. Pick another name.")
|
||
return
|
||
if name in presets.presets(self._prefs, style) and not \
|
||
self._confirm_overwrite(name):
|
||
return
|
||
presets.save(self._prefs, style, name)
|
||
self._sync_preset_combo(style)
|
||
|
||
def _edit_presets(self, style: str):
|
||
presets.PresetEditor(self._prefs, style, _VISUALIZER_STYLES[style],
|
||
self).exec()
|
||
|
||
# Overridable, so tests needn't type into dialogs.
|
||
def _ask_preset_name(self, suggestion: str) -> str:
|
||
name, ok = QInputDialog.getText(self, "Save as Preset", "Name:",
|
||
text=suggestion)
|
||
return name if ok else ""
|
||
|
||
def _confirm_overwrite(self, name: str) -> bool:
|
||
return QMessageBox.question(
|
||
self, "Save as Preset",
|
||
f"Replace the preset “{name}” with these settings?") == \
|
||
QMessageBox.StandardButton.Yes
|
||
|
||
def _preset_warning(self, text: str):
|
||
QMessageBox.warning(self, "Save as Preset", text)
|
||
|
||
def _speaker_range(self, form, config) -> RangeSlider:
|
||
"""Which frequencies drive the trace (the "speaker" in
|
||
visualizer_styles), on a log scale (each slider step is the same musical interval)."""
|
||
slider = RangeSlider(0, SPEAKER_STEPS, gap=_speaker_gap())
|
||
slider.setToolTip(
|
||
"Which frequencies drive the trace. Bass makes the big "
|
||
"loops; treble is a fine shiver on them. Slide the low end up to "
|
||
"watch the treble on its own.")
|
||
slider.setValues(_hz_to_step(config["visualizer_laser_low_hz"]),
|
||
_hz_to_step(config["visualizer_laser_high_hz"]))
|
||
text = QLabel()
|
||
text.setMinimumWidth(QLabel("2.5 kHz – 20 kHz").sizeHint().width())
|
||
|
||
def changed(low, high, save=True):
|
||
text.setText(f"{_hz_text(_step_to_hz(low))} – "
|
||
f"{_hz_text(_step_to_hz(high))}")
|
||
if save:
|
||
self._prefs.set_live("visualizer_laser_low_hz", _step_to_hz(low))
|
||
self._prefs.set_live("visualizer_laser_high_hz", _step_to_hz(high))
|
||
self._color_save_timer.start()
|
||
|
||
changed(*slider.values(), save=False)
|
||
slider.rangeChanged.connect(changed)
|
||
row = QHBoxLayout()
|
||
row.addWidget(slider, stretch=1)
|
||
row.addSpacing(8)
|
||
row.addWidget(text)
|
||
form.addRow("Frequency range:", row)
|
||
return slider
|
||
|
||
def _sync_delay_slider(self, form, style: str) -> QSlider:
|
||
"""This style's sync delay — this machine's speakers' latency plus
|
||
the style's own lag, so one per style, in config.json."""
|
||
lo, hi = visualizer_styles.SYNC_DELAY_LIMITS
|
||
slider = _viz_slider_widget()
|
||
slider.setRange(lo, hi)
|
||
slider.setSingleStep(5)
|
||
slider.setPageStep(25)
|
||
slider.setToolTip(
|
||
"If the visualizer runs ahead of what you hear — Bluetooth "
|
||
"headphones especially — hold it back this much. Below zero it "
|
||
"reacts sooner, by up to as much audio as the player has decoded "
|
||
"ahead (usually a few tens of ms). Set per computer and per "
|
||
"style, since each style lags in its own way.")
|
||
slider.setValue(visualizer_styles.sync_delay_ms(load_config(), style))
|
||
text = QLabel(_sync_text(slider.value()))
|
||
text.setMinimumWidth(max(_VALUE_WIDTH, text.fontMetrics().horizontalAdvance(
|
||
_sync_text(visualizer_styles.SYNC_DELAY_LIMITS[0])) + 4))
|
||
|
||
def changed(value):
|
||
text.setText(_sync_text(value))
|
||
self._sync_save_timer.start()
|
||
|
||
slider.valueChanged.connect(changed)
|
||
self._sync_sliders[style] = slider
|
||
row = QHBoxLayout()
|
||
row.addWidget(slider, stretch=1)
|
||
row.addSpacing(8)
|
||
row.addWidget(text)
|
||
form.addRow("Sync delay:", row)
|
||
return slider
|
||
|
||
def _save_sync_delay(self):
|
||
config = load_config()
|
||
config[visualizer_styles.SYNC_DELAYS_KEY] = {
|
||
style: slider.value() for style, slider in self._sync_sliders.items()}
|
||
save_config(config)
|
||
# config.json has no signal of its own; the visualizer re-reads it
|
||
# whenever preferences change.
|
||
self._prefs.changed.emit()
|
||
|
||
def _viz_check(self, form, label, key, config, tip=""):
|
||
box = QCheckBox(label)
|
||
box.setChecked(config[key]) # before connect
|
||
box.setToolTip(tip)
|
||
box.toggled.connect(lambda on: self._prefs.set(key, on))
|
||
form.addRow(box)
|
||
self._viz_setters[key] = lambda value: box.setChecked(bool(value))
|
||
return box
|
||
|
||
def _viz_slider(self, form, label, key, config, *, scale=1, fmt=str,
|
||
tip=""):
|
||
"""A slider over ``visualizer_styles.LIMITS[key]`` that previews live
|
||
and saves once the drag settles, with its value beside it."""
|
||
lo, hi = visualizer_styles.LIMITS[key]
|
||
slider = _viz_slider_widget()
|
||
slider.setRange(round(lo * scale), round(hi * scale))
|
||
slider.setToolTip(tip)
|
||
slider.setValue(round(config[key] * scale)) # before connect
|
||
text = QLabel(fmt(config[key]))
|
||
text.setMinimumWidth(_VALUE_WIDTH)
|
||
|
||
def changed(position):
|
||
value = position / scale if scale != 1 else position
|
||
text.setText(fmt(value))
|
||
self._prefs.set_live(key, value)
|
||
self._color_save_timer.start() # persist once the drag settles
|
||
|
||
slider.valueChanged.connect(changed)
|
||
row = QHBoxLayout()
|
||
row.addWidget(slider, stretch=1)
|
||
row.addSpacing(8)
|
||
row.addWidget(text)
|
||
form.addRow(label, row)
|
||
self._viz_setters[key] = lambda value: slider.setValue(round(value * scale))
|
||
return slider, text
|
||
|
||
def _on_viz_style(self, key: str):
|
||
self._viz_pages.setCurrentIndex(list(_VISUALIZER_STYLES).index(key))
|
||
self._fit_viz_pages()
|
||
self._prefs.set("visualizer_style", key)
|
||
|
||
def _fit_viz_pages(self):
|
||
"""A stack is as tall as its tallest page (the oscilloscope's), which left
|
||
the other styles over a block of empty space; only the shown page
|
||
counts toward its size."""
|
||
stack = self._viz_pages
|
||
for i in range(stack.count()):
|
||
page = stack.widget(i)
|
||
policy = (QSizePolicy.Policy.Preferred if i == stack.currentIndex()
|
||
else QSizePolicy.Policy.Ignored)
|
||
page.setSizePolicy(policy, policy)
|
||
stack.currentWidget().adjustSize()
|
||
stack.updateGeometry()
|
||
|
||
def _build_colors_group(self) -> QGroupBox:
|
||
"""Light and dark each have a tint and a full set of grays; the
|
||
Light | Dark tabs pick which set the controls show and edit, and
|
||
every control moves to that set's saved values."""
|
||
group = QGroupBox("Colors")
|
||
form = QFormLayout(group)
|
||
note = QLabel("Each gray runs black → white and updates instantly. "
|
||
"The tint colors every gray but text, by the tint level.")
|
||
note.setWordWrap(True)
|
||
form.addRow(note)
|
||
|
||
# Which set the controls below show: folder tabs, since picking one
|
||
# changes the page under it (shared design #tabs).
|
||
strip = TabStrip()
|
||
self._color_mode_group = QButtonGroup(self)
|
||
self._color_mode_buttons = {}
|
||
for which in theme.MODES:
|
||
tab = MacTab(which.capitalize())
|
||
self._color_mode_group.addButton(tab)
|
||
self._color_mode_buttons[which] = tab
|
||
strip.add(tab)
|
||
tab.toggled.connect(
|
||
lambda on, w=which: on and self._edit_colors_of(w))
|
||
form.addRow(strip)
|
||
|
||
self._editing = theme.mode(self._prefs)
|
||
tint_row = QHBoxLayout()
|
||
self._tint_swatch = QToolButton()
|
||
self._tint_swatch.setAutoRaise(True)
|
||
self._tint_swatch.setToolTip("Choose the tint color")
|
||
self._tint_swatch.clicked.connect(self._choose_tint)
|
||
self._tint_slider = QSlider(Qt.Orientation.Horizontal)
|
||
self._tint_slider.setRange(0, 100)
|
||
self._tint_label = QLabel("")
|
||
self._tint_label.setMinimumWidth(36)
|
||
self._tint_slider.valueChanged.connect(self._on_tint_level)
|
||
tint_row.addWidget(self._tint_swatch)
|
||
tint_row.addWidget(self._tint_slider, stretch=1)
|
||
tint_row.addWidget(self._tint_label)
|
||
form.addRow("Tint:", tint_row)
|
||
|
||
self._color_sliders = {}
|
||
for key, label in _COLOR_ROWS:
|
||
slider = QSlider(Qt.Orientation.Horizontal)
|
||
slider.setRange(0, 255)
|
||
slider.valueChanged.connect(
|
||
lambda value, k=key: self._on_color_changed(k, value))
|
||
self._color_sliders[key] = slider
|
||
form.addRow(label, slider)
|
||
self._color_mode_buttons[self._editing].setChecked(True)
|
||
strip.finish()
|
||
self._show_color_values()
|
||
return group
|
||
|
||
def _edit_colors_of(self, which: str):
|
||
if which != self._editing:
|
||
self._editing = which
|
||
self._show_color_values()
|
||
|
||
def _show_color_values(self):
|
||
"""Move every control to the edited mode's saved values, without
|
||
writing anything."""
|
||
which = self._editing
|
||
for key, slider in self._color_sliders.items():
|
||
slider.blockSignals(True)
|
||
slider.setValue(theme.gray_value(self._prefs, key, which))
|
||
slider.blockSignals(False)
|
||
color, level = theme.tint(self._prefs, which)
|
||
self._tint_swatch.setIcon(theme.swatch_icon(color.name()))
|
||
self._tint_slider.blockSignals(True)
|
||
self._tint_slider.setValue(round(level * 100))
|
||
self._tint_slider.blockSignals(False)
|
||
self._tint_label.setText(f"{round(level * 100)} %")
|
||
|
||
def _on_color_changed(self, key: str, value: int):
|
||
self._prefs.set_live(theme.mode_key(key, self._editing), value)
|
||
self._color_save_timer.start() # persist once the drag settles
|
||
|
||
def _on_tint_level(self, value: int):
|
||
self._tint_label.setText(f"{value} %")
|
||
self._prefs.set_live(theme.mode_key("tint_level", self._editing), value)
|
||
self._color_save_timer.start()
|
||
|
||
def _choose_tint(self):
|
||
which = self._editing
|
||
current, _level = theme.tint(self._prefs, which)
|
||
color = QColorDialog.getColor(current, self, "Tint color")
|
||
if not color.isValid():
|
||
return
|
||
self._prefs.set(theme.mode_key("tint_color", which), color.name())
|
||
if self._tint_slider.value() == 0:
|
||
self._tint_slider.setValue(20) # a tint at 0 % would show nothing
|
||
self._show_color_values()
|
||
|
||
def _on_dark_toggled(self, on: bool):
|
||
self._prefs.set("dark_mode", on)
|
||
self._color_mode_buttons["dark" if on else "light"].setChecked(True)
|
||
|
||
def _sync_dark_check(self):
|
||
on = theme.mode(self._prefs) == "dark"
|
||
if self._dark_check.isChecked() != on:
|
||
self._dark_check.blockSignals(True)
|
||
self._dark_check.setChecked(on)
|
||
self._dark_check.blockSignals(False)
|
||
self._color_mode_buttons["dark" if on else "light"].setChecked(True)
|
||
|
||
# ---- 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 _build_web_server_group(self) -> QGroupBox:
|
||
"""Where Export Web Mix uploads to. config.json, not preferences: the
|
||
host is usually an ssh alias on *this* machine, and nothing about the
|
||
server should reach the synced share."""
|
||
group = QGroupBox("Web Server")
|
||
form = QFormLayout(group)
|
||
hint = QLabel(
|
||
"Export Web Mix can upload a mix straight to a web server over "
|
||
"ssh (rsync). Pick a folder on the server that's used only for "
|
||
"LinTunes mixes: each mix goes into its own folder inside it, and "
|
||
"uploading a mix again makes that folder match the export "
|
||
"exactly, deleting anything else in it. Needs ssh key login; a "
|
||
"password prompt can't be answered from here. Saved on this "
|
||
"computer only.")
|
||
hint.setWordWrap(True)
|
||
form.addRow(hint)
|
||
config = load_config()
|
||
self._web_host = QLineEdit(config.get(upload.HOST_KEY, ""))
|
||
self._web_host.setPlaceholderText("myserver")
|
||
self._web_host.setToolTip(
|
||
"An ssh host — a Host alias from ~/.ssh/config works, "
|
||
"as does user@example.com")
|
||
self._web_host.editingFinished.connect(self._save_web_server)
|
||
form.addRow("Host:", self._web_host)
|
||
self._web_path = QLineEdit(config.get(upload.PATH_KEY, ""))
|
||
self._web_path.setPlaceholderText("/var/www/html/mixes")
|
||
self._web_path.setToolTip(
|
||
"The full path of the mixes folder on the server. It must "
|
||
"already exist.")
|
||
self._web_path.editingFinished.connect(self._save_web_server)
|
||
form.addRow("Folder:", self._web_path)
|
||
return group
|
||
|
||
def _save_web_server(self):
|
||
config = load_config()
|
||
values = {upload.HOST_KEY: self._web_host.text().strip(),
|
||
upload.PATH_KEY: self._web_path.text().strip()}
|
||
if all(config.get(k, "") == v for k, v in values.items()):
|
||
return
|
||
config.update(values)
|
||
save_config(config)
|
||
|
||
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)
|