v0.77.0: the laser visualizer is the Oscilloscope — screen sliders and rig diagram gone, a graticule dot size, and a sync delay per style

This commit is contained in:
2026-10-23 00:21:32 -07:00
parent 5413263587
commit 5f41460cb6
13 changed files with 357 additions and 478 deletions
+21 -13
View File
@@ -268,21 +268,28 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
drew as a flat arc. "Even out bass and treble" removes a *straight*, drew as a flat arc. "Even out bass and treble" removes a *straight*,
loudness-weighted dB-vs-log-f tilt, clipped to ±24 dB, and never lifts a loudness-weighted dB-vs-log-f tilt, clipped to ±24 dB, and never lifts a
band that isn't sounding (a curve fitted to a lone tone lit up silent band that isn't sounding (a curve fitted to a lone tone lit up silent
treble). **Laser** simulates a mirror on a speaker membrane: the treble). **Oscilloscope** (`laser` in code and prefs — Round 108 renamed
only what the user sees) is an **X-Y scope of the bass**: nine resonators
(≈50–160 Hz) each push the trace along a fixed direction, and the sum is
X and Y. *Where* they sit and *which way* they push comes from modelling a
laser off a mirror on a speaker membrane (Tame Impala's rig): the
circular-membrane modes run as complex one-pole resonators, vectorized in circular-membrane modes run as complex one-pole resonators, vectorized in
`CHUNK`s. Loops come from the split degenerate pairs, between whose `CHUNK`s. Loops come from the split degenerate pairs, between whose
resonances x and y answer up to 90° apart, hence the slack 50 Hz membrane resonances x and y answer up to 90° apart, hence the slack 50 Hz membrane
with a wide split. The beam ray is intersected with a screen at with a wide split. Round 78's screen distance/pitch/yaw/roll sliders and
`distance`, turned by pitch/yaw/roll; the auto-gain holds the beam the live rig diagram are gone (Round 108): they only resized, stretched or
*angle*, so distance is real, and `scale()` shrinks the drawing only when a spun the same tangle, so trav found they "don't really do anything". The
steep screen would push the loudest swing out of view. The path is drawn screen is fixed square at `SCREEN_DISTANCE`; a still `gui/scope_drawing.py`
sits beside the look controls. The graticule's dots have a size
(`visualizer_laser_grid_dot`, × the automatic size). The path is drawn
brighter where it moves slower (dwell). The afterimage is a **phosphor** brighter where it moves slower (dwell). The afterimage is a **phosphor**
(`_Phosphor`, one per painted size, half resolution past 400 px wide): (`_Phosphor`, one per painted size, half resolution past 400 px wide):
each sweep is burned in once and the buffer is dimmed per frame, so cost each sweep is burned in once and the buffer is dimmed per frame, so cost
doesn't grow with the fade time. The dimming is a numpy LUT that rounds doesn't grow with the fade time. The dimming is a numpy LUT that rounds
*down*, because Qt's own fade rounds to nearest and stalls faint pixels *down*, because Qt's own fade rounds to nearest and stalls faint pixels
forever. The numpy array must be a **view of the QImage's `bits()`**, since forever. The numpy array must be a **view of the QImage's `bits()`**, since
building a QImage *from* an array copies it. A **speaker range** (low/high building a QImage *from* an array copies it. A **frequency range** (the
"speaker" in code, low/high
Hz, `gui/range_slider.py`) filters what drives the membrane, with Hz, `gui/range_slider.py`) filters what drives the membrane, with
`one_pole` stages done exactly via the cumsum trick, 36 dB/octave. That is `one_pole` stages done exactly via the cumsum trick, 36 dB/octave. That is
steeper than a real speaker on purpose: the membrane answers bass ~80 dB steeper than a real speaker on purpose: the membrane answers bass ~80 dB
@@ -297,10 +304,14 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
buffers arrive in a burst. So the widget keeps 1.5 s of *timestamped* buffers arrive in a burst. So the widget keeps 1.5 s of *timestamped*
history (`QAudioBuffer.startTime()`) and each frame draws the stretch history (`QAudioBuffer.startTime()`) and each frame draws the stretch
ending at `Player.position_ms()`, carried forward by the clock between ending at `Player.position_ms()`, carried forward by the clock between
Qt's buffer-sized steps, minus `visualizer_sync_delay_ms`. That delay is Qt's buffer-sized steps, minus the sync delay. That delay is output
output latency Qt can't see (Bluetooth), this machine's hardware, so it latency Qt can't see (Bluetooth), this machine's hardware, so it lives in
lives in **`config.json`**; the dialog emits `prefs.changed` after writing **`config.json`** — and since Round 108 **one per style**
it so the widget re-reads. The laser takes every heard sample exactly once (`visualizer_sync_delays: {style: ms}`, the slider right under each page's
preset), because each style adds its own lag (radial's FFT window, the
bars' fall, Kaleidostrobe's 25 fps, the scope's ringing). A style not yet
set starts from the old shared `visualizer_sync_delay_ms`. The dialog emits
`prefs.changed` after writing it so the widget re-reads. The laser takes every heard sample exactly once
(`_drawn` index), never the newest-decoded ones. (`_drawn` index), never the newest-decoded ones.
**Presets** (`gui/visualizer_presets.py`): per style, `STYLE_KEYS` under a **Presets** (`gui/visualizer_presets.py`): per style, `STYLE_KEYS` under a
name, in `visualizer_presets` (synced; never the sync delay). `Default` is name, in `visualizer_presets` (synced; never the sync delay). `Default` is
@@ -310,9 +321,6 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal
"Custom" whenever the settings match no preset. A setting added later "Custom" whenever the settings match no preset. A setting added later
must join `STYLE_KEYS` and register a setter, or presets silently skip it must join `STYLE_KEYS` and register a setter, or presets silently skip it
(`test_every_style_key_has_a_control` pins that). (`test_every_style_key_has_a_control` pins that).
The laser page draws the rig (`gui/laser_diagram.py`, textbook line art
through the renderer's own `_rotation`); it labels distance, angles and
dot size, so those sliders show no number.
**Dark mode** (Round 101, Preferences › Appearance): `theme.mode(prefs)` **Dark mode** (Round 101, Preferences › Appearance): `theme.mode(prefs)`
picks a whole palette (`_dark_palette`, every role) in dark, or the picks a whole palette (`_dark_palette`, every role) in dark, or the
base palette plus overrides in light. Each mode has its own gray sliders base palette plus overrides in light. Each mode has its own gray sliders
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux.""" """LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.76.0" __version__ = "0.77.0"
-222
View File
@@ -1,222 +0,0 @@
"""A small line drawing of the laser rig as the settings describe it — the
speaker with its mirror, the laser, the beam, and the screen at its distance
and angles — in the manner of an old electronics textbook: thin dark-gray
lines, a dimension line with arrowheads, small italic serif labels.
Schematic, not to scale: the distance moves the screen along the beam and
the angles turn it (through the same rotation the visualizer projects
with), but sizes are chosen to read, not measured.
"""
import math
import numpy as np
from PyQt6.QtWidgets import QWidget, QSizePolicy
from PyQt6.QtCore import Qt, QPointF, QRectF, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QFont, QPolygonF, QFontMetricsF
from lintunes.gui import visualizer_styles
# Oblique projection: the screen's width (across the beam) recedes up and to
# the right at this share of its true length — a cabinet drawing.
DEPTH = 0.5
DEPTH_ANGLE = math.radians(35)
INK = 0.72 # how far the line color is from the background to the text
class LaserDiagram(QWidget):
def __init__(self, config=None, parent=None):
super().__init__(parent)
self._config = config or visualizer_styles.settings(None)
self.setSizePolicy(QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
self.setMinimumSize(300, 150)
self.setToolTip("The rig your settings describe (not to scale)")
def sizeHint(self):
return QSize(420, 160)
def set_config(self, config: dict):
self._config = config
self.update()
# ---- drawing helpers ----
def _ink(self) -> QColor:
text = self.palette().windowText().color()
back = self.palette().window().color()
return QColor(*(round(b + (t - b) * INK) for t, b in (
(text.red(), back.red()), (text.green(), back.green()),
(text.blue(), back.blue()))))
def _label_font(self, caps=False) -> QFont:
font = QFont(self.font())
font.setFamilies(["Times New Roman", "Liberation Serif", "DejaVu Serif"])
font.setStyleHint(QFont.StyleHint.Serif)
font.setItalic(not caps)
font.setPointSizeF(max(7.0, font.pointSizeF() - (1.5 if caps else 0.5)))
if caps:
font.setLetterSpacing(QFont.SpacingType.PercentageSpacing, 112)
return font
@staticmethod
def _arrowhead(painter, tip: QPointF, toward: QPointF, size=6.0):
angle = math.atan2(tip.y() - toward.y(), tip.x() - toward.x())
wing = math.radians(18)
painter.drawPolygon(QPolygonF([
tip,
QPointF(tip.x() - size * math.cos(angle - wing),
tip.y() - size * math.sin(angle - wing)),
QPointF(tip.x() - size * math.cos(angle + wing),
tip.y() - size * math.sin(angle + wing))]))
def screen_corners(self, center: QPointF, half_height: float,
pitch=None, yaw=None, roll=None) -> list:
"""The screen's outline, projected: its own right/up axes turned by
the angles, then the across-the-beam axis drawn receding."""
c = self._config
rot = visualizer_styles._rotation(
c["visualizer_laser_pitch"] if pitch is None else pitch,
c["visualizer_laser_yaw"] if yaw is None else yaw,
c["visualizer_laser_roll"] if roll is None else roll)
half_width = half_height * 1.6
corners = []
for u, v in ((-1, -1), (1, -1), (1, 1), (-1, 1)):
x, y, z = rot @ np.array([u * half_width, v * half_height, 0.0])
corners.append(QPointF(
center.x() + z + x * DEPTH * math.cos(DEPTH_ANGLE),
center.y() - y - x * DEPTH * math.sin(DEPTH_ANGLE)))
return corners
# ---- the drawing ----
def paintEvent(self, event):
c = self._config
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
ink = self._ink()
thin = QPen(ink, 1.0)
thin.setCapStyle(Qt.PenCapStyle.RoundCap)
thin.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
dashed = QPen(ink, 0.8, Qt.PenStyle.DashLine)
italic, caps = self._label_font(), self._label_font(caps=True)
w, h = self.width(), self.height()
axis_y = h * 0.42
mirror = QPointF(62, axis_y)
half = min(h * 0.24, 34) # the screen's half-height
angle_labels_w = QFontMetricsF(italic).horizontalAdvance("pitch −60°") + 14
near_x = mirror.x() + 105
far_x = max(near_x + 40, w - angle_labels_w - half * 1.0)
lo, hi = visualizer_styles.LIMITS["visualizer_laser_distance"]
distance = c["visualizer_laser_distance"]
screen = QPointF(near_x + (distance - lo) / (hi - lo) * (far_x - near_x),
axis_y)
# The laser, below and ahead of the speaker, aimed up at the mirror.
laser_at = QPointF(mirror.x() + 62, axis_y + 30)
incoming = math.atan2(laser_at.y() - mirror.y(), laser_at.x() - mirror.x())
painter.save()
painter.translate(laser_at)
painter.rotate(math.degrees(incoming))
painter.setPen(thin)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRect(QRectF(0, -5, 34, 10))
painter.drawLine(QPointF(34, -3), QPointF(38, -3)) # a cable stub
painter.restore()
painter.setFont(caps)
painter.drawText(QPointF(laser_at.x() + 2, laser_at.y() + 26), "LASER")
# The speaker: its axis halfway between the laser and the screen, so
# the mirror on its membrane sends the beam straight along the axis.
normal = incoming / 2
painter.save()
painter.translate(mirror)
painter.rotate(math.degrees(normal))
painter.setPen(thin)
cone = QPolygonF([QPointF(0, -26), QPointF(-22, -9), QPointF(-22, 9),
QPointF(0, 26)])
painter.drawPolyline(cone)
painter.drawLine(QPointF(0, -26), QPointF(0, 26)) # the membrane
painter.drawRect(QRectF(-34, -10, 12, 20)) # the magnet
painter.drawLine(QPointF(-3, -27), QPointF(-3, 27)) # the frame lip
mirror_pen = QPen(ink, 3.0)
painter.setPen(mirror_pen)
painter.drawLine(QPointF(1.5, -6), QPointF(1.5, 6)) # the mirror
painter.restore()
painter.setPen(thin)
painter.setFont(caps)
painter.drawText(QPointF(mirror.x() - 52, axis_y + 46), "SPEAKER")
# The beam: in from the laser, out to the screen.
painter.drawLine(laser_at, mirror)
painter.setBrush(ink)
self._arrowhead(painter, QPointF((laser_at.x() + mirror.x()) / 2,
(laser_at.y() + mirror.y()) / 2), laser_at)
corners = self.screen_corners(screen, half)
painter.drawLine(mirror, screen)
mid = QPointF((mirror.x() + screen.x()) / 2, axis_y)
self._arrowhead(painter, mid, mirror)
painter.setBrush(Qt.BrushStyle.NoBrush)
# Where a screen facing the beam squarely would be, if this one isn't.
turned = any(c[k] for k in ("visualizer_laser_pitch",
"visualizer_laser_yaw", "visualizer_laser_roll"))
if turned:
painter.setPen(dashed)
painter.drawPolygon(QPolygonF(self.screen_corners(screen, half, 0, 0, 0)))
painter.setPen(thin)
painter.drawPolygon(QPolygonF(corners))
painter.setFont(caps)
top = min(p.y() for p in corners)
painter.drawText(QPointF(screen.x() - 22, max(10.0, top - 6)), "SCREEN")
# The dot, where the beam lands, at its size.
radius = max(1.0, min(9.0, c["visualizer_laser_dot"] / 2))
painter.setBrush(ink)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawEllipse(screen, radius, radius)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.setPen(thin)
right = max(p.x() for p in corners)
lead_from = QPointF(screen.x() + radius + 1, screen.y() + radius + 1)
lead_to = QPointF(right + 10, axis_y + half * 0.9)
painter.drawLine(lead_from, lead_to)
painter.setFont(italic)
dot = c["visualizer_laser_dot"]
dot_text = f"dot {dot:g} px" + ("" if c["visualizer_laser_head"] else
" (at rest)")
painter.drawText(QPointF(lead_to.x() + 3, lead_to.y() + 4), dot_text)
# The angles, beside the screen.
lines = [f"pitch {_deg(c['visualizer_laser_pitch'])}",
f"yaw {_deg(c['visualizer_laser_yaw'])}",
f"roll {_deg(c['visualizer_laser_roll'])}"]
metrics = QFontMetricsF(italic)
y = axis_y - half - 2
for line in lines:
painter.drawText(QPointF(right + 10, y), line)
y += metrics.height()
# The distance: a dimension line under it all, mirror to screen.
dim_y = h - 12
painter.setPen(thin)
for x in (mirror.x(), screen.x()):
painter.drawLine(QPointF(x, dim_y - 6), QPointF(x, dim_y + 4))
left, right_end = QPointF(mirror.x(), dim_y), QPointF(screen.x(), dim_y)
text = f"D = {distance:.1f} m"
text_w = metrics.horizontalAdvance(text) + 10
centre = (left.x() + right_end.x()) / 2
painter.drawLine(left, QPointF(centre - text_w / 2, dim_y))
painter.drawLine(QPointF(centre + text_w / 2, dim_y), right_end)
painter.setBrush(ink)
self._arrowhead(painter, left, right_end, 5)
self._arrowhead(painter, right_end, left, 5)
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawText(QPointF(centre - text_w / 2 + 5, dim_y + 4), text)
painter.end()
def _deg(value) -> str:
value = round(value)
return f"{value:+d}°".replace("-", "−") if value else "0°"
+42 -59
View File
@@ -17,7 +17,7 @@ from lintunes.config import load_config, save_config
from lintunes.export import upload from lintunes.export import upload
from lintunes.gui import visualizer_styles from lintunes.gui import visualizer_styles
from lintunes.gui.range_slider import RangeSlider from lintunes.gui.range_slider import RangeSlider
from lintunes.gui.laser_diagram import LaserDiagram from lintunes.gui.scope_drawing import ScopeDrawing
from lintunes.gui import visualizer_presets as presets from lintunes.gui import visualizer_presets as presets
from lintunes.gui import sounds from lintunes.gui import sounds
from lintunes.theme import HIGHLIGHT_COLORS from lintunes.theme import HIGHLIGHT_COLORS
@@ -37,7 +37,7 @@ _COLOR_ROWS = [
] ]
# Room for the widest value a visualizer slider shows ("−180°", "400 ms"). # Room for the widest value a visualizer slider shows ("400 ms").
_VALUE_WIDTH = 56 _VALUE_WIDTH = 56
@@ -45,7 +45,7 @@ HEADING_EXTRA_PX = 2 # section headings: this much over the text
_EDIT_PRESETS = "\0edit" # the preset drop-down's last item _EDIT_PRESETS = "\0edit" # the preset drop-down's last item
_SPEAKER_KEYS = ("visualizer_laser_low_hz", "visualizer_laser_high_hz") _SPEAKER_KEYS = ("visualizer_laser_low_hz", "visualizer_laser_high_hz")
# The laser's speaker range: 20 Hz – 20 kHz in log steps of 1/30 octave. # The oscilloscope's frequency range: 20 Hz – 20 kHz in log steps of 1/30 octave.
SPEAKER_STEPS = 300 SPEAKER_STEPS = 300
@@ -625,6 +625,11 @@ class PreferencesDialog(QDialog):
# Only the chosen style's settings are shown. # Only the chosen style's settings are shown.
self._viz_pages = QStackedWidget() self._viz_pages = QStackedWidget()
self._viz_setters = {} # key → puts a value into its control 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 self._preset_combos = {} # style → its preset drop-down
fade_tip = ("How long what's left behind takes to fade into the " fade_tip = ("How long what's left behind takes to fade into the "
"background — 0 is no trail") "background — 0 is no trail")
@@ -632,6 +637,7 @@ class PreferencesDialog(QDialog):
bars = QWidget() bars = QWidget()
form = self._viz_form(bars) form = self._viz_form(bars)
self._preset_row(form, "bars") self._preset_row(form, "bars")
self._sync_delay_slider(form, "bars")
self._bars_count_box = self._viz_spinbox( self._bars_count_box = self._viz_spinbox(
form, "Bars:", "visualizer_bars_count", config, step=1, decimals=0, form, "Bars:", "visualizer_bars_count", config, step=1, decimals=0,
suffix="", tip="How many bars, 1 to 1024. Past the drawing's width " suffix="", tip="How many bars, 1 to 1024. Past the drawing's width "
@@ -644,6 +650,7 @@ class PreferencesDialog(QDialog):
radial = QWidget() radial = QWidget()
form = self._viz_form(radial) form = self._viz_form(radial)
self._preset_row(form, "radial") self._preset_row(form, "radial")
self._sync_delay_slider(form, "radial")
self._fade_slider, _ = self._viz_slider( self._fade_slider, _ = self._viz_slider(
form, "Fade:", "visualizer_ghost_fade", config, scale=20, form, "Fade:", "visualizer_ghost_fade", config, scale=20,
fmt=_fade_text, tip=fade_tip) fmt=_fade_text, tip=fade_tip)
@@ -667,14 +674,13 @@ class PreferencesDialog(QDialog):
laser = QWidget() laser = QWidget()
form = self._viz_form(laser) form = self._viz_form(laser)
self._preset_row(form, "laser") self._preset_row(form, "laser")
self._sync_delay_slider(form, "laser")
self._laser_fade_box = self._viz_spinbox( self._laser_fade_box = self._viz_spinbox(
form, "Afterimage:", "visualizer_laser_afterimage", config, form, "Afterimage:", "visualizer_laser_afterimage", config,
step=0.05, decimals=2, suffix=" s", off_text="Off", step=0.05, decimals=2, suffix=" s", off_text="Off",
tip="How long past sweeps of the beam take to fade — 0 is none") tip="How long past sweeps of the beam take to fade — 0 is none")
self._speaker = self._speaker_range(form, config) self._speaker = self._speaker_range(form, config)
# The look controls on the left, and beside them a drawing of the # The look controls on the left, a still drawing of a scope beside.
# rig the settings describe — it labels the distance, the angles
# and the dot, so those sliders carry no number of their own.
looks = self._viz_form(None) looks = self._viz_form(None)
self._width_box = self._viz_spinbox( self._width_box = self._viz_spinbox(
looks, "Line width:", "visualizer_laser_width", config, looks, "Line width:", "visualizer_laser_width", config,
@@ -683,49 +689,32 @@ class PreferencesDialog(QDialog):
looks, "Glow", "visualizer_laser_glow", config, looks, "Glow", "visualizer_laser_glow", config,
tip="The haze around the beam") tip="The haze around the beam")
self._grid = self._viz_check( self._grid = self._viz_check(
looks, "Oscilloscope grid", "visualizer_laser_grid", config, looks, "Graticule", "visualizer_laser_grid", config,
tip="A graticule of gray dots painted under the beam") tip="The grid of gray dots on an oscilloscope's screen, painted "
"under the beam")
self._head = self._viz_check( self._head = self._viz_check(
looks, "Dot at the tip of the beam", "visualizer_laser_head", looks, "Dot at the tip of the beam", "visualizer_laser_head",
config, tip="When the music is silent the beam rests as a dot " config, tip="When the music is silent the beam rests as a dot "
"in the middle either way") "in the middle either way")
self._diagram = LaserDiagram(config)
self._prefs.changed.connect(lambda: self._diagram.set_config(
visualizer_styles.settings(self._prefs)))
beside = QHBoxLayout() beside = QHBoxLayout()
beside.addLayout(looks) beside.addLayout(looks)
beside.addSpacing(12) beside.addSpacing(12)
beside.addWidget(self._diagram, stretch=1) beside.addStretch()
beside.addWidget(ScopeDrawing())
form.addRow(beside) form.addRow(beside)
self._dot_slider, _ = self._viz_slider( self._dot_slider, _ = self._viz_slider(
form, "Dot size:", "visualizer_laser_dot", config, scale=2, form, "Tip dot size:", "visualizer_laser_dot", config, scale=2,
show_value=False) fmt=lambda v: f"{v:g} px",
self._distance_slider, _ = self._viz_slider( tip="The dot at the beam's tip, and the resting dot in silence")
form, "Screen distance:", "visualizer_laser_distance", config, self._grid_dot_slider, _ = self._viz_slider(
scale=10, show_value=False, form, "Graticule dot size:", "visualizer_laser_grid_dot", config,
tip="From the mirror to the middle of the screen") scale=100, fmt=lambda v: f"{round(v * 100)}%",
degrees = lambda v: f"{v:+.0f}°" if v else "0°" tip="100% is the size that suits the screen's size")
self._angle_sliders = {}
for key, label, tip in (
("visualizer_laser_pitch", "Screen pitch:",
"Tip the screen's top toward or away from the speaker — "
"stretches the figure up and down"),
("visualizer_laser_yaw", "Screen yaw:",
"Turn the screen left or right — stretches the figure "
"sideways"),
("visualizer_laser_roll", "Screen roll:",
"Spin the screen in its own plane — turns the figure")):
self._angle_sliders[key], _ = self._viz_slider(
form, label, key, config, fmt=degrees, tip=tip,
show_value=False)
square = QPushButton("Face Screen Square")
square.clicked.connect(
lambda: [s.setValue(0) for s in self._angle_sliders.values()])
form.addRow("", square)
self._viz_pages.addWidget(laser) self._viz_pages.addWidget(laser)
kaleido = QWidget() kaleido = QWidget()
form = self._viz_form(kaleido) form = self._viz_form(kaleido)
self._sync_delay_slider(form, "kaleidostrobe")
about = QLabel( about = QLabel(
"The 2002 iTunes visualizer by Shehryar Lasi, rebuilt from its " "The 2002 iTunes visualizer by Shehryar Lasi, rebuilt from its "
"original code. It has no settings: the Color and Flash boxes " "original code. It has no settings: the Color and Flash boxes "
@@ -739,10 +728,6 @@ class PreferencesDialog(QDialog):
self._fit_viz_pages() self._fit_viz_pages()
column.addWidget(self._viz_pages) column.addWidget(self._viz_pages)
# For every style: this machine's speakers' latency (config.json).
form = QFormLayout()
self._sync_slider = self._sync_delay_slider(form)
column.addLayout(form)
note = QLabel("Click the visualizer to see it big.") note = QLabel("Click the visualizer to see it big.")
note.setEnabled(False) note.setEnabled(False)
column.addWidget(note) column.addWidget(note)
@@ -880,11 +865,11 @@ class PreferencesDialog(QDialog):
QMessageBox.warning(self, "Save as Preset", text) QMessageBox.warning(self, "Save as Preset", text)
def _speaker_range(self, form, config) -> RangeSlider: def _speaker_range(self, form, config) -> RangeSlider:
"""The speaker under the mirror: which frequencies it plays, on a """Which frequencies drive the trace (the "speaker" in
log scale (each slider step is the same musical interval).""" visualizer_styles), on a log scale (each slider step is the same musical interval)."""
slider = RangeSlider(0, SPEAKER_STEPS, gap=_speaker_gap()) slider = RangeSlider(0, SPEAKER_STEPS, gap=_speaker_gap())
slider.setToolTip( slider.setToolTip(
"What the speaker under the mirror plays. Bass makes the big " "Which frequencies drive the trace. Bass makes the big "
"loops; treble is a fine shiver on them. Slide the low end up to " "loops; treble is a fine shiver on them. Slide the low end up to "
"watch the treble on its own.") "watch the treble on its own.")
slider.setValues(_hz_to_step(config["visualizer_laser_low_hz"]), slider.setValues(_hz_to_step(config["visualizer_laser_low_hz"]),
@@ -906,10 +891,12 @@ class PreferencesDialog(QDialog):
row.addWidget(slider, stretch=1) row.addWidget(slider, stretch=1)
row.addSpacing(8) row.addSpacing(8)
row.addWidget(text) row.addWidget(text)
form.addRow("Speaker range:", row) form.addRow("Frequency range:", row)
return slider return slider
def _sync_delay_slider(self, form) -> QSlider: 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 lo, hi = visualizer_styles.SYNC_DELAY_LIMITS
slider = QSlider(Qt.Orientation.Horizontal) slider = QSlider(Qt.Orientation.Horizontal)
slider.setRange(lo, hi) slider.setRange(lo, hi)
@@ -919,8 +906,9 @@ class PreferencesDialog(QDialog):
"If the visualizer runs ahead of what you hear — Bluetooth " "If the visualizer runs ahead of what you hear — Bluetooth "
"headphones especially — hold it back this much. Below zero it " "headphones especially — hold it back this much. Below zero it "
"reacts sooner, by up to as much audio as the player has decoded " "reacts sooner, by up to as much audio as the player has decoded "
"ahead (usually a few tens of ms). Set per computer.") "ahead (usually a few tens of ms). Set per computer and per "
slider.setValue(visualizer_styles.sync_delay_ms(load_config())) "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 = QLabel(_sync_text(slider.value()))
text.setMinimumWidth(max(_VALUE_WIDTH, text.fontMetrics().horizontalAdvance( text.setMinimumWidth(max(_VALUE_WIDTH, text.fontMetrics().horizontalAdvance(
_sync_text(visualizer_styles.SYNC_DELAY_LIMITS[0])) + 4)) _sync_text(visualizer_styles.SYNC_DELAY_LIMITS[0])) + 4))
@@ -930,10 +918,7 @@ class PreferencesDialog(QDialog):
self._sync_save_timer.start() self._sync_save_timer.start()
slider.valueChanged.connect(changed) slider.valueChanged.connect(changed)
self._sync_save_timer = QTimer(self) self._sync_sliders[style] = slider
self._sync_save_timer.setSingleShot(True)
self._sync_save_timer.setInterval(300)
self._sync_save_timer.timeout.connect(self._save_sync_delay)
row = QHBoxLayout() row = QHBoxLayout()
row.addWidget(slider, stretch=1) row.addWidget(slider, stretch=1)
row.addSpacing(8) row.addSpacing(8)
@@ -943,7 +928,8 @@ class PreferencesDialog(QDialog):
def _save_sync_delay(self): def _save_sync_delay(self):
config = load_config() config = load_config()
config[visualizer_styles.SYNC_DELAY_KEY] = self._sync_slider.value() config[visualizer_styles.SYNC_DELAYS_KEY] = {
style: slider.value() for style, slider in self._sync_sliders.items()}
save_config(config) save_config(config)
# config.json has no signal of its own; the visualizer re-reads it # config.json has no signal of its own; the visualizer re-reads it
# whenever preferences change. # whenever preferences change.
@@ -959,7 +945,7 @@ class PreferencesDialog(QDialog):
return box return box
def _viz_slider(self, form, label, key, config, *, scale=1, fmt=str, def _viz_slider(self, form, label, key, config, *, scale=1, fmt=str,
tip="", show_value=True): tip=""):
"""A slider over ``visualizer_styles.LIMITS[key]`` that previews live """A slider over ``visualizer_styles.LIMITS[key]`` that previews live
and saves once the drag settles, with its value beside it.""" and saves once the drag settles, with its value beside it."""
lo, hi = visualizer_styles.LIMITS[key] lo, hi = visualizer_styles.LIMITS[key]
@@ -979,11 +965,8 @@ class PreferencesDialog(QDialog):
slider.valueChanged.connect(changed) slider.valueChanged.connect(changed)
row = QHBoxLayout() row = QHBoxLayout()
row.addWidget(slider, stretch=1) row.addWidget(slider, stretch=1)
if show_value: row.addSpacing(8)
row.addSpacing(8) row.addWidget(text)
row.addWidget(text)
else:
text.hide() # shown elsewhere (the laser diagram)
form.addRow(label, row) form.addRow(label, row)
self._viz_setters[key] = lambda value: slider.setValue(round(value * scale)) self._viz_setters[key] = lambda value: slider.setValue(round(value * scale))
return slider, text return slider, text
@@ -994,7 +977,7 @@ class PreferencesDialog(QDialog):
self._prefs.set("visualizer_style", key) self._prefs.set("visualizer_style", key)
def _fit_viz_pages(self): def _fit_viz_pages(self):
"""A stack is as tall as its tallest page (the laser's), which left """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 the other styles over a block of empty space; only the shown page
counts toward its size.""" counts toward its size."""
stack = self._viz_pages stack = self._viz_pages
+87
View File
@@ -0,0 +1,87 @@
"""A small, still line drawing of an oscilloscope beside the Oscilloscope
style's settings, in the manner of an old electronics textbook: thin
dark-gray lines, the screen's dot graticule, a Lissajous loop on it and two
knobs underneath. It shows what the style is; it doesn't follow the settings.
"""
import math
from PyQt6.QtWidgets import QWidget, QSizePolicy
from PyQt6.QtCore import Qt, QPointF, QRectF, QSize
from PyQt6.QtGui import QPainter, QPen, QColor, QPolygonF
INK = 0.72 # how far the line color is from the background to the text
class ScopeDrawing(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setSizePolicy(QSizePolicy.Policy.Preferred,
QSizePolicy.Policy.Preferred)
self.setMinimumSize(150, 116)
def sizeHint(self):
return QSize(170, 128)
def _ink(self) -> QColor:
text = self.palette().windowText().color()
back = self.palette().window().color()
return QColor(*(round(b + (t - b) * INK) for t, b in (
(text.red(), back.red()), (text.green(), back.green()),
(text.blue(), back.blue()))))
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
ink = self._ink()
pen = QPen(ink, 1.0)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(pen)
painter.setBrush(Qt.BrushStyle.NoBrush)
# The case, 4:3, centered.
w, h = self.width() - 2, self.height() - 2
case_w = min(w, h * 4 / 3)
case = QRectF((self.width() - case_w) / 2, (self.height() - case_w * 3 / 4) / 2,
case_w, case_w * 3 / 4)
painter.drawRoundedRect(case, 6, 6)
# The screen: the left three quarters, with the knobs to its right.
pad = case.height() * 0.1
screen = QRectF(case.left() + pad, case.top() + pad,
case.width() * 0.68, case.height() - 2 * pad)
painter.drawRoundedRect(screen, 4, 4)
# The graticule: a dot at every division, 8 × 6.
dots = QPen(ink, 2.2)
dots.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(dots)
inner = screen.adjusted(4, 4, -4, -4)
painter.drawPoints([QPointF(inner.left() + i * inner.width() / 8,
inner.top() + j * inner.height() / 6)
for i in range(1, 8) for j in range(1, 6)])
# A 3:2 Lissajous figure.
cx, cy = inner.center().x(), inner.center().y()
rx, ry = inner.width() * 0.38, inner.height() * 0.38
trace = QPen(ink, 1.3)
trace.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
painter.setPen(trace)
steps = 240
painter.drawPolyline(QPolygonF([
QPointF(cx + rx * math.sin(3 * t + math.pi / 2),
cy + ry * math.sin(2 * t + math.pi / 4))
for t in (2 * math.pi * k / steps for k in range(steps + 1))]))
# Two knobs, each with a pointer.
painter.setPen(pen)
knob_x = (screen.right() + case.right()) / 2
radius = min(case.right() - screen.right(), case.height()) * 0.2
for share, turn in ((0.32, -40), (0.68, 70)):
center = QPointF(knob_x, case.top() + case.height() * share)
painter.drawEllipse(center, radius, radius)
angle = math.radians(turn - 90)
painter.drawLine(center, QPointF(
center.x() + radius * 0.8 * math.cos(angle),
center.y() + radius * 0.8 * math.sin(angle)))
painter.end()
+3 -3
View File
@@ -87,7 +87,7 @@ class VisualizerWidget(QWidget):
self._total = 0 # samples ever appended: the history's end index self._total = 0 # samples ever appended: the history's end index
self._drawn = None # index the laser has consumed up to self._drawn = None # index the laser has consumed up to
self._anchor = None # (position ms, monotonic s) of the last update self._anchor = None # (position ms, monotonic s) of the last update
self._sync_delay = styles.sync_delay_ms(load_config()) self._sync_delay = styles.sync_delay_ms(load_config(), _style(prefs))
self._big = None # VisualizerWindow, made on first double-click self._big = None # VisualizerWindow, made on first double-click
# True while audio is coming out of something other than this machine # True while audio is coming out of something other than this machine
# (a Chromecast), so there is no decoded PCM to draw. # (a Chromecast), so there is no decoded PCM to draw.
@@ -130,8 +130,8 @@ class VisualizerWidget(QWidget):
return self._renderer.levels return self._renderer.levels
def _on_prefs_changed(self): def _on_prefs_changed(self):
self._sync_delay = styles.sync_delay_ms(load_config())
style = _style(self._prefs) style = _style(self._prefs)
self._sync_delay = styles.sync_delay_ms(load_config(), style)
config = styles.settings(self._prefs) config = styles.settings(self._prefs)
if style != self._renderer.name: if style != self._renderer.name:
self._renderer = make_renderer(style, config) self._renderer = make_renderer(style, config)
@@ -474,7 +474,7 @@ class VisualizerWidget(QWidget):
return QColor(self.palette().highlight().color()) return QColor(self.palette().highlight().color())
def _grid_gray(self): def _grid_gray(self):
"""The laser's graticule: the gray, faded so the beam reads over it """The oscilloscope's graticule: the gray, faded so the beam reads over it
even when the beam is gray too.""" even when the beam is gray too."""
gray = self._gray().darker(115) gray = self._gray().darker(115)
gray.setAlphaF(0.75) gray.setAlphaF(0.75)
+1 -2
View File
@@ -32,8 +32,7 @@ STYLE_KEYS = {
"visualizer_laser_high_hz", "visualizer_laser_width", "visualizer_laser_high_hz", "visualizer_laser_width",
"visualizer_laser_glow", "visualizer_laser_grid", "visualizer_laser_glow", "visualizer_laser_grid",
"visualizer_laser_head", "visualizer_laser_dot", "visualizer_laser_head", "visualizer_laser_dot",
"visualizer_laser_distance", "visualizer_laser_pitch", "visualizer_laser_grid_dot"),
"visualizer_laser_yaw", "visualizer_laser_roll"),
} }
+55 -73
View File
@@ -8,8 +8,9 @@ audio intake, the timer, on/dim/off, the color. Pure numpy + QPainter.
- ``BarsRenderer`` — the original 20-band graphic EQ. - ``BarsRenderer`` — the original 20-band graphic EQ.
- ``RadialRenderer`` — that EQ wrapped into a circle as dots: angle is - ``RadialRenderer`` — that EQ wrapped into a circle as dots: angle is
frequency, radius is volume, and a dot that moves leaves fading ghosts. frequency, radius is volume, and a dot that moves leaves fading ghosts.
- ``LaserRenderer`` — a laser bounced off a mirror glued to a membrane - ``LaserRenderer`` — the Oscilloscope: an X-Y trace of the bass, as a
stretched over a speaker, projected onto a screen (Tame Impala's rig). laser off a mirror on a speaker membrane would draw it (Tame Impala's
rig). Named "laser" in code and prefs, which is what it started as.
- ``KaleidostrobeRenderer`` (``visualizer_kaleido``) — the 2002 iTunes - ``KaleidostrobeRenderer`` (``visualizer_kaleido``) — the 2002 iTunes
plugin, ported from its PowerPC binary. plugin, ported from its PowerPC binary.
@@ -36,7 +37,7 @@ STYLES = (STYLE_BARS, STYLE_RADIAL, STYLE_LASER, STYLE_KALEIDOSTROBE)
STYLE_NAMES = { STYLE_NAMES = {
STYLE_BARS: "Bars", STYLE_BARS: "Bars",
STYLE_RADIAL: "Radial dots", STYLE_RADIAL: "Radial dots",
STYLE_LASER: "Laser", STYLE_LASER: "Oscilloscope",
STYLE_KALEIDOSTROBE: "Kaleidostrobe", STYLE_KALEIDOSTROBE: "Kaleidostrobe",
} }
@@ -62,16 +63,13 @@ LIMITS = {
"visualizer_laser_afterimage": (0.0, 3.0), "visualizer_laser_afterimage": (0.0, 3.0),
"visualizer_laser_width": (1.0, 8.0), # pixels "visualizer_laser_width": (1.0, 8.0), # pixels
"visualizer_laser_dot": (1.0, 16.0), # pixels across "visualizer_laser_dot": (1.0, 16.0), # pixels across
"visualizer_laser_grid_dot": (0.25, 3.0), # × the graticule's own size
# What the speaker under the mirror plays. At the ends, no filter. # What the speaker under the mirror plays. At the ends, no filter.
"visualizer_laser_low_hz": (20, 20000), "visualizer_laser_low_hz": (20, 20000),
"visualizer_laser_high_hz": (20, 20000), "visualizer_laser_high_hz": (20, 20000),
"visualizer_radial_spokes": (12, 360), "visualizer_radial_spokes": (12, 360),
"visualizer_radial_levels": (4, 40), "visualizer_radial_levels": (4, 40),
"visualizer_radial_dot": (0.2, 2.5), # × the automatic size "visualizer_radial_dot": (0.2, 2.5), # × the automatic size
"visualizer_laser_distance": (1.0, 4.0), # metres, mirror → screen
"visualizer_laser_pitch": (-60, 60), # degrees
"visualizer_laser_yaw": (-60, 60),
"visualizer_laser_roll": (-180, 180),
} }
_FLAGS = ("visualizer_radial_normalize", "visualizer_laser_head", _FLAGS = ("visualizer_radial_normalize", "visualizer_laser_head",
"visualizer_laser_glow", "visualizer_laser_grid") "visualizer_laser_glow", "visualizer_laser_grid")
@@ -82,7 +80,12 @@ SPEAKER_MIN_RATIO = 2 ** (1 / 3) # the narrowest speaker: a third-octave
# How much later than Qt's playback position the speakers really are — # How much later than Qt's playback position the speakers really are —
# PipeWire's buffer, and far more over Bluetooth. That's this machine's # PipeWire's buffer, and far more over Bluetooth. That's this machine's
# audio hardware, so it lives in config.json, never the synced prefs. # audio hardware, so it lives in config.json, never the synced prefs. One
# per style, {style: ms}: each adds its own lag on top (radial's 93 ms FFT
# window, the bars' fall, Kaleidostrobe's 25 fps, the scope's ringing).
SYNC_DELAYS_KEY = "visualizer_sync_delays"
# The single value every style shared before; a style not yet set starts
# from it.
SYNC_DELAY_KEY = "visualizer_sync_delay_ms" SYNC_DELAY_KEY = "visualizer_sync_delay_ms"
# Negative = sooner: the frame is taken from audio decoded but not yet # Negative = sooner: the frame is taken from audio decoded but not yet
# heard. The player decodes only a few tens of ms ahead (measured 0–30 ms), # heard. The player decodes only a few tens of ms ahead (measured 0–30 ms),
@@ -90,9 +93,12 @@ SYNC_DELAY_KEY = "visualizer_sync_delay_ms"
SYNC_DELAY_LIMITS = (-50, 400) SYNC_DELAY_LIMITS = (-50, 400)
def sync_delay_ms(config: dict) -> int: def sync_delay_ms(config: dict, style: str) -> int:
delays = config.get(SYNC_DELAYS_KEY)
if not isinstance(delays, dict) or style not in delays:
delays = {style: config.get(SYNC_DELAY_KEY, 0)}
try: try:
value = int(config.get(SYNC_DELAY_KEY, 0)) value = int(delays[style])
except (TypeError, ValueError): except (TypeError, ValueError):
return 0 return 0
return min(SYNC_DELAY_LIMITS[1], max(SYNC_DELAY_LIMITS[0], value)) return min(SYNC_DELAY_LIMITS[1], max(SYNC_DELAY_LIMITS[0], value))
@@ -520,14 +526,19 @@ class RadialRenderer:
# Laser # Laser
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# #
# The rig: a small mirror glued to a rubber membrane stretched over a # What this really is: an oscilloscope in X-Y mode. The audio, through the
# speaker; a laser hits the mirror and the reflection lands on a big # "speaker" (a band-pass), drives nine resonators, and each one pushes the
# screen. What moves the beam is the *tilt* of the mirror, and a membrane # trace along its own fixed direction; their sum is X and Y. Where those
# doesn't just pump in and out — it vibrates in modes, each with its own # resonators sit and which way they push comes from modelling the rig it
# resonance and its own shape. The mirror's tilt is the membrane's slope # was first built as — a small mirror glued to a rubber membrane stretched
# where the mirror sits, so every mode pushes the beam along one fixed # over a speaker, a laser off the mirror onto a screen — because that model
# direction on the screen, at a strength set by how near the music is to # is what draws loops rather than strokes:
# that mode's resonance. #
# What moves the beam is the *tilt* of the mirror, and a membrane doesn't
# just pump in and out — it vibrates in modes, each with its own resonance
# and its own shape. The mirror's tilt is the membrane's slope where the
# mirror sits, so every mode pushes the beam along one fixed direction, at
# a strength set by how near the music is to that mode's resonance.
# #
# The modes of a circular membrane are J_m(j_mn·r)·cos(mθ), resonating at # The modes of a circular membrane are J_m(j_mn·r)·cos(mθ), resonating at
# j_mn/j_01 times the fundamental. The m > 0 modes come in pairs at right # j_mn/j_01 times the fundamental. The m > 0 modes come in pairs at right
@@ -536,19 +547,16 @@ class RadialRenderer:
# same note up to 90° apart — the beam swings along one axis a quarter # same note up to 90° apart — the beam swings along one axis a quarter
# cycle behind the other, which is a circle. A mirror near the middle sits # cycle behind the other, which is a circle. A mirror near the middle sits
# where that rocking pair dominates (the (0,1) "breathing" mode has no # where that rocking pair dominates (the (0,1) "breathing" mode has no
# slope at the center, so it only draws lines), which is why the rig's # slope at the center, so it only draws lines), which is why the figures
# figures are loops rather than strokes. A perfectly even push wouldn't # are loops. A perfectly even push wouldn't excite the m > 0 modes at all;
# excite the m > 0 modes at all; the mirror's own mass, off-center, is # the mirror's own mass, off-center, is what couples them.
# what couples them.
# #
# Reflection doubles the angle: tilt θ turns the beam 2θ, and the spot is # Reflection doubles the angle: tilt θ turns the beam 2θ, and the spot is
# where that ray meets the screen. A screen square to the beam puts it at # D·tan(2θ) on a screen square to it. (Round 78 let the screen be moved and
# D·tan(2θ); a screen turned away (pitch, yaw) stretches the figure along # turned; that only stretched, keystoned or spun a tangle of loops, and
# the turn and spreads its far side wider (keystone); roll spins it. The # Round 108 took it out.) The spot moves far faster than an eye follows, so
# spot moves far faster than an eye or a camera follows, so what anyone # what anyone sees is the whole path traced in one glance, brightest where
# sees is the whole path traced in one glance, brightest where the beam # the beam moves slowest (it dwells there), with a bloom around it.
# moves slowest (it dwells there), with the haze and the screen's scatter
# blooming around it.
MODE_ZEROS = ( # (m, j_mn) — Bessel zeros MODE_ZEROS = ( # (m, j_mn) — Bessel zeros
(0, 2.40483), (1, 3.83171), (2, 5.13562), (0, 5.52008), (3, 6.38016), (0, 2.40483), (1, 3.83171), (2, 5.13562), (0, 5.52008), (3, 6.38016),
@@ -564,11 +572,10 @@ SPLIT = (0.0, 0.30, 0.24, 0.0, 0.18)
MIRROR_AT = (0.15, 0.6) # the mirror's spot: radius (of 1), angle (rad) MIRROR_AT = (0.15, 0.6) # the mirror's spot: radius (of 1), angle (rad)
SIM_RATE = 11025.0 # the membrane barely answers above a few hundred Hz SIM_RATE = 11025.0 # the membrane barely answers above a few hundred Hz
SCREEN_HALF = 1.0 # the screen's half-height, metres SCREEN_HALF = 1.0 # the screen's half-height, metres
FILL = 0.85 # at the farthest distance, the loudest swings fill this SCREEN_DISTANCE = 3.5 # metres, mirror → screen
# The auto-gain holds the beam's loudest swing at this angle, so distance FILL = 0.75 # the share of the screen the loudest swings fill
# is real: the figure grows as the screen moves back, filling it at the # The auto-gain holds the beam's loudest swing at this angle.
# slider's far end. BEAM_TARGET = math.atan(FILL * SCREEN_HALF / SCREEN_DISTANCE)
BEAM_TARGET = math.atan(FILL * SCREEN_HALF / LIMITS["visualizer_laser_distance"][1])
GAIN_RELEASE_S = 0.3 # how slowly the auto-gain turns back up after a peak GAIN_RELEASE_S = 0.3 # how slowly the auto-gain turns back up after a peak
# Silence must stay a still dot, not amplified hiss: the auto-gain never # Silence must stay a still dot, not amplified hiss: the auto-gain never
# turns up past what -60 dB hiss would swing, 22 dB over. Measured through # turns up past what -60 dB hiss would swing, 22 dB over. Measured through
@@ -637,18 +644,6 @@ def _membrane_modes():
MODES = _membrane_modes() MODES = _membrane_modes()
def _rotation(pitch, yaw, roll) -> np.ndarray:
"""The screen's orientation: columns are its right, up and normal."""
p, y, r = (math.radians(a) for a in (pitch, yaw, roll))
rx = np.array([[1, 0, 0], [0, math.cos(p), -math.sin(p)],
[0, math.sin(p), math.cos(p)]])
ry = np.array([[math.cos(y), 0, math.sin(y)], [0, 1, 0],
[-math.sin(y), 0, math.cos(y)]])
rz = np.array([[math.cos(r), -math.sin(r), 0],
[math.sin(r), math.cos(r), 0], [0, 0, 1]])
return ry @ rx @ rz
class LaserRenderer: class LaserRenderer:
name = STYLE_LASER name = STYLE_LASER
@@ -676,6 +671,7 @@ class LaserRenderer:
self.head = config["visualizer_laser_head"] self.head = config["visualizer_laser_head"]
self.glow = config["visualizer_laser_glow"] self.glow = config["visualizer_laser_glow"]
self.grid = config["visualizer_laser_grid"] self.grid = config["visualizer_laser_grid"]
self.grid_dot = config["visualizer_laser_grid_dot"]
band = (config["visualizer_laser_low_hz"], band = (config["visualizer_laser_low_hz"],
config["visualizer_laser_high_hz"]) config["visualizer_laser_high_hz"])
if band != getattr(self, "band", None): if band != getattr(self, "band", None):
@@ -683,18 +679,9 @@ class LaserRenderer:
if self._rate: if self._rate:
self._setup(self._rate) self._setup(self._rate)
self._prune() self._prune()
self.distance = config["visualizer_laser_distance"] # How far the loudest possible swing reaches on the screen.
rot = _rotation(config["visualizer_laser_pitch"], reach = SCREEN_DISTANCE * math.tan(BEAM_TARGET)
config["visualizer_laser_yaw"], self.extent = (reach, reach)
config["visualizer_laser_roll"])
self._right, self._up, self._normal = rot[:, 0], rot[:, 1], rot[:, 2]
# How far the loudest possible swing reaches on this screen, each
# way: what painting scales by so it always stays in view.
ring = np.linspace(0, 2 * math.pi, 96, endpoint=False)
edge = np.column_stack([np.cos(ring), np.sin(ring)]) * BEAM_TARGET
spots = self.on_screen(edge)
self.extent = (max(np.abs(spots[:, 0]).max(), 1e-6),
max(np.abs(spots[:, 1]).max(), 1e-6))
def clear(self): def clear(self):
self._state = np.zeros(len(MODES), dtype=np.complex128) self._state = np.zeros(len(MODES), dtype=np.complex128)
@@ -796,17 +783,11 @@ class LaserRenderer:
# ---- the screen ---- # ---- the screen ----
def on_screen(self, beam: np.ndarray) -> np.ndarray: @staticmethod
def on_screen(beam: np.ndarray) -> np.ndarray:
"""Beam angles (n, 2) from the rest direction → where the ray meets """Beam angles (n, 2) from the rest direction → where the ray meets
the screen, metres from its center along its own right and up.""" the screen, metres from its center."""
ray = np.column_stack([np.tan(beam[:, 0]), np.tan(beam[:, 1]), return SCREEN_DISTANCE * np.tan(beam)
np.ones(len(beam))])
center = np.array([0.0, 0.0, self.distance])
# ray·t meets the plane through `center` with this normal at
# t = (n·c)/(n·ray). The angle limits keep n·ray well above 0.
t = (self._normal @ center) / np.maximum(ray @ self._normal, 1e-3)
offset = ray * t[:, None] - center
return np.column_stack([offset @ self._right, offset @ self._up])
def project(self, tilt: np.ndarray, dt: float) -> np.ndarray: def project(self, tilt: np.ndarray, dt: float) -> np.ndarray:
"""Mirror tilt → spot on the screen (metres, y up).""" """Mirror tilt → spot on the screen (metres, y up)."""
@@ -847,8 +828,8 @@ class LaserRenderer:
def scale(self, rect) -> float: def scale(self, rect) -> float:
"""Pixels per metre: the screen's half-height fills the rect's, and """Pixels per metre: the screen's half-height fills the rect's, and
shrinks only if the loudest swing would leave the rect (a steeply shrinks only if the loudest swing would leave the rect — so the
turned screen) — so the figure is always on screen.""" figure is always on screen."""
half_w = rect.width() / 2 - INSET half_w = rect.width() / 2 - INSET
half_h = rect.height() / 2 - INSET half_h = rect.height() / 2 - INSET
unit = min(half_w, half_h) / SCREEN_HALF unit = min(half_w, half_h) / SCREEN_HALF
@@ -896,7 +877,8 @@ class LaserRenderer:
def paint_grid(self, painter, rect, gray: QColor): def paint_grid(self, painter, rect, gray: QColor):
"""An oscilloscope's graticule: dots at every division crossing, and """An oscilloscope's graticule: dots at every division crossing, and
finer ticks along the two center lines. Painted *on the glass*, so finer ticks along the two center lines. Painted *on the glass*, so
it stays put in the window whatever the screen's angle or distance.""" it stays put in the window whatever the trace does. ``grid_dot``
scales the dots from their automatic size."""
cx, cy = rect.center().x(), rect.center().y() cx, cy = rect.center().x(), rect.center().y()
division = (min(rect.width(), rect.height()) / 2 - INSET) / GRID_HALF division = (min(rect.width(), rect.height()) / 2 - INSET) / GRID_HALF
if division < 4: if division < 4:
@@ -914,10 +896,10 @@ class LaserRenderer:
if k % GRID_TICKS] if k % GRID_TICKS]
pen = QPen(gray) pen = QPen(gray)
pen.setCapStyle(Qt.PenCapStyle.RoundCap) pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setWidthF(max(1.5, division / 12)) pen.setWidthF(max(1.5, division / 12) * self.grid_dot)
painter.setPen(pen) painter.setPen(pen)
painter.drawPoints(major) painter.drawPoints(major)
pen.setWidthF(max(1.0, division / 20)) pen.setWidthF(max(1.0, division / 20) * self.grid_dot)
painter.setPen(pen) painter.setPen(pen)
painter.drawPoints(ticks) painter.drawPoints(ticks)
+1 -4
View File
@@ -27,6 +27,7 @@ DEFAULTS = {
"visualizer_laser_head": True, # a dot at the moving beam's tip "visualizer_laser_head": True, # a dot at the moving beam's tip
"visualizer_laser_glow": True, # the haze/scatter bloom "visualizer_laser_glow": True, # the haze/scatter bloom
"visualizer_laser_grid": False, # an oscilloscope's dot graticule "visualizer_laser_grid": False, # an oscilloscope's dot graticule
"visualizer_laser_grid_dot": 1.0, # its dots, × their automatic size
"visualizer_presets": {}, # {style: {name: settings}} "visualizer_presets": {}, # {style: {name: settings}}
"visualizer_laser_low_hz": 20, # the speaker under the mirror: "visualizer_laser_low_hz": 20, # the speaker under the mirror:
"visualizer_laser_high_hz": 20000, # what it plays (ends = no filter) "visualizer_laser_high_hz": 20000, # what it plays (ends = no filter)
@@ -34,10 +35,6 @@ DEFAULTS = {
"visualizer_radial_levels": 20, # volume steps along each spoke "visualizer_radial_levels": 20, # volume steps along each spoke
"visualizer_radial_dot": 1.0, # dot size, × the automatic size "visualizer_radial_dot": 1.0, # dot size, × the automatic size
"visualizer_radial_normalize": True, # even out bass vs treble "visualizer_radial_normalize": True, # even out bass vs treble
"visualizer_laser_distance": 3.5, # metres, mirror → screen center
"visualizer_laser_pitch": 0, # degrees the screen is turned
"visualizer_laser_yaw": 0,
"visualizer_laser_roll": 0,
# Per-area grayscale overrides (0=black .. 255=white). None = inherit the # Per-area grayscale overrides (0=black .. 255=white). None = inherit the
# current/default look for that surface, so nothing changes until the user # current/default look for that surface, so nothing changes until the user
# drags a slider in Preferences. # drags a slider in Preferences.
+123
View File
@@ -0,0 +1,123 @@
"""Round 108: the laser style is called what it is — an Oscilloscope.
The screen's distance/pitch/yaw/roll only stretched or spun the same
tangle of loops, so they and the live rig diagram are gone (a still scope
drawing stands in); the graticule's dots get a size; and the sync delay is
one per style, since each style lags in its own way.
"""
import numpy as np
from PyQt6.QtCore import QRectF
from PyQt6.QtGui import QColor, QImage, QPainter
from lintunes.gui import visualizer_styles as vs
from lintunes.gui import visualizer_presets as presets
from lintunes.preferences import Preferences, DEFAULTS
from test_round78 import RATE, _PositionedPlayer, _marked, _config
from test_round84 import _LastFm
def _dialog(prefs):
from lintunes.gui.preferences_dialog import PreferencesDialog
return PreferencesDialog(prefs, _LastFm())
class TestNaming:
def test_the_style_reads_oscilloscope(self):
assert vs.STYLE_NAMES[vs.STYLE_LASER] == "Oscilloscope"
def test_the_screen_settings_are_gone(self):
for key in ("distance", "pitch", "yaw", "roll"):
assert f"visualizer_laser_{key}" not in vs.LIMITS
assert f"visualizer_laser_{key}" not in DEFAULTS
assert f"visualizer_laser_{key}" not in presets.STYLE_KEYS["laser"]
def test_the_dialog_has_a_still_drawing_and_no_screen_sliders(
self, qapp, tmp_path):
from lintunes.gui.scope_drawing import ScopeDrawing
dialog = _dialog(Preferences(tmp_path))
page = dialog._viz_pages.widget(list(vs.STYLES).index("laser"))
assert len(page.findChildren(ScopeDrawing)) == 1
assert not hasattr(dialog, "_angle_sliders")
assert not hasattr(dialog, "_distance_slider")
def test_the_drawing_paints(self, qapp):
from lintunes.gui.scope_drawing import ScopeDrawing
drawing = ScopeDrawing()
drawing.resize(170, 128)
assert not drawing.grab().isNull()
class TestGraticuleDots:
def _ink(self, grid_dot):
r = vs.LaserRenderer(_config(laser_grid=True, laser_grid_dot=grid_dot))
image = QImage(400, 300, QImage.Format.Format_ARGB32)
image.fill(QColor("black"))
painter = QPainter(image)
r.paint_grid(painter, QRectF(0, 0, 400, 300), QColor("white"))
painter.end()
bits = image.constBits()
bits.setsize(image.sizeInBytes())
return np.frombuffer(bits, np.uint8).reshape(300, 400, 4)[..., 0].sum()
def test_the_size_scales_the_dots(self, qapp):
assert self._ink(2.0) > 2 * self._ink(1.0) > 2 * self._ink(0.5) > 0
def test_the_slider_writes_a_share(self, qapp, tmp_path):
prefs = Preferences(tmp_path)
dialog = _dialog(prefs)
dialog._grid_dot_slider.setValue(150)
assert prefs.get("visualizer_laser_grid_dot") == 1.5
assert "visualizer_laser_grid_dot" in presets.STYLE_KEYS["laser"]
class TestSyncPerStyle:
def test_each_style_has_its_own(self):
config = {"visualizer_sync_delays": {"bars": 40, "laser": 120}}
assert vs.sync_delay_ms(config, "bars") == 40
assert vs.sync_delay_ms(config, "laser") == 120
def test_an_unset_style_starts_from_the_old_shared_value(self):
config = {"visualizer_sync_delay_ms": 90,
"visualizer_sync_delays": {"bars": 40}}
assert vs.sync_delay_ms(config, "radial") == 90
assert vs.sync_delay_ms({}, "radial") == 0
assert vs.sync_delay_ms({"visualizer_sync_delays": {"bars": 9999}},
"bars") == vs.SYNC_DELAY_LIMITS[1]
def test_every_page_has_one_right_under_the_preset(self, qapp, tmp_path):
from PyQt6.QtWidgets import QFormLayout
dialog = _dialog(Preferences(tmp_path))
assert set(dialog._sync_sliders) == set(vs.STYLES)
for i, style in enumerate(vs.STYLES):
form = dialog._viz_pages.widget(i).layout()
row = 1 if style in dialog._preset_combos else 0
item = form.itemAt(row, QFormLayout.ItemRole.FieldRole)
sliders = [item.layout().itemAt(j).widget()
for j in range(item.layout().count())]
assert dialog._sync_sliders[style] in sliders
def test_saving_keeps_them_apart(self, qapp, tmp_path, monkeypatch):
from lintunes.config import load_config
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg"))
dialog = _dialog(Preferences(tmp_path))
dialog._sync_sliders["bars"].setValue(30)
dialog._sync_sliders["kaleidostrobe"].setValue(-20)
dialog._save_sync_delay()
saved = load_config()["visualizer_sync_delays"]
assert saved["bars"] == 30 and saved["kaleidostrobe"] == -20
assert saved["radial"] == 0
def test_the_widget_uses_the_shown_styles(self, qapp, tmp_path,
monkeypatch):
from lintunes.config import save_config
from lintunes.gui.visualizer import VisualizerWidget
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg"))
save_config({"visualizer_sync_delays": {"bars": 0, "radial": 200}})
prefs = Preferences(tmp_path)
player = _PositionedPlayer()
vis = VisualizerWidget(player, prefs)
vis._feed(_marked(1000), RATE, start_ms=0)
player.position = 600
assert abs(vis._frame(0.016).samples[-1] - 600) < 2
prefs.set("visualizer_style", "radial")
assert abs(vis._frame(0.016).samples[-1] - 400) < 2
+19 -49
View File
@@ -104,10 +104,10 @@ class TestStylePreference:
def test_settings_are_clamped(self, qapp, tmp_path): def test_settings_are_clamped(self, qapp, tmp_path):
prefs = Preferences(tmp_path) prefs = Preferences(tmp_path)
prefs.set("visualizer_radial_spokes", 100000) # hand-edited prefs.set("visualizer_radial_spokes", 100000) # hand-edited
prefs.set("visualizer_laser_pitch", "sideways") prefs.set("visualizer_laser_width", "wide")
config = vs.settings(prefs) config = vs.settings(prefs)
assert config["visualizer_radial_spokes"] == 360 assert config["visualizer_radial_spokes"] == 360
assert config["visualizer_laser_pitch"] == 0 assert config["visualizer_laser_width"] == 1.5
def test_every_style_paints_without_error(self, qapp): def test_every_style_paints_without_error(self, qapp):
for style in vs.STYLES: for style in vs.STYLES:
@@ -301,39 +301,11 @@ class TestLaser:
s = np.linalg.svd(tilt, compute_uv=False) s = np.linalg.svd(tilt, compute_uv=False)
assert s[1] / s[0] > 0.4 assert s[1] / s[0] > 0.4
def test_farther_screen_bigger_figure(self): def test_the_figure_stays_on_screen_and_visible(self):
audio = _sine(vs.MODES[1][0], 1.0)
near = _run(vs.LaserRenderer(_config(laser_distance=1.0)), audio)
far = _run(vs.LaserRenderer(_config(laser_distance=4.0)), audio)
ratio = np.abs(far.paths[0][0]).max() / np.abs(near.paths[0][0]).max()
assert 3.5 < ratio < 4.5
def test_pitch_stretches_vertically_and_roll_spins(self):
audio = _sine((vs.MODES[1][0] + vs.MODES[2][0]) / 2, 1.0)
def spread(**angles):
path = _run(vs.LaserRenderer(_config(**angles)), audio).paths[0][0]
return np.ptp(path[:, 0]), np.ptp(path[:, 1])
square_x, square_y = spread()
tipped_x, tipped_y = spread(laser_pitch=50)
assert tipped_y / square_y > 1.3 * tipped_x / square_x
turned_x, turned_y = spread(laser_yaw=50)
assert turned_x / square_x > 1.3 * turned_y / square_y
spun = _run(vs.LaserRenderer(_config(laser_roll=90)), audio).paths[0][0]
flat = _run(vs.LaserRenderer(_config()), audio).paths[0][0]
# A quarter turn: x becomes y (up to sign).
assert np.allclose(np.abs(spun[:, 0]), np.abs(flat[:, 1]), atol=1e-9)
@pytest.mark.parametrize("angles", [
{}, {"laser_pitch": 60, "laser_yaw": -60},
{"laser_pitch": -60, "laser_yaw": 60, "laser_roll": 45},
{"laser_distance": 1.0, "laser_pitch": 60}])
def test_every_setting_stays_on_screen_and_visible(self, angles):
rng = np.random.default_rng(0) rng = np.random.default_rng(0)
audio = _sine(90, 2, 0.9) * (1 + rng.standard_normal(2 * RATE) * 0.3) audio = _sine(90, 2, 0.9) * (1 + rng.standard_normal(2 * RATE) * 0.3)
audio = audio + _sine(150, 2, 0.5) audio = audio + _sine(150, 2, 0.5)
r = vs.LaserRenderer(_config(**angles)) r = vs.LaserRenderer(_config())
rect = QRectF(0, 0, 140, 62) rect = QRectF(0, 0, 140, 62)
half_w, half_h = 70 - vs.INSET, 31 - vs.INSET half_w, half_h = 70 - vs.INSET, 31 - vs.INSET
biggest = 0.0 biggest = 0.0
@@ -632,17 +604,12 @@ class TestPreferencesPage:
dialog._head.setChecked(False) dialog._head.setChecked(False)
dialog._width_box.setValue(dialog._width_box.minimum()) dialog._width_box.setValue(dialog._width_box.minimum())
dialog._dot_slider.setValue(12) dialog._dot_slider.setValue(12)
dialog._distance_slider.setValue(15) dialog._grid_dot_slider.setValue(200)
dialog._angle_sliders["visualizer_laser_pitch"].setValue(30)
assert prefs.get("visualizer_laser_glow") is False assert prefs.get("visualizer_laser_glow") is False
assert prefs.get("visualizer_laser_head") is False assert prefs.get("visualizer_laser_head") is False
assert prefs.get("visualizer_laser_width") == 1 # one pixel assert prefs.get("visualizer_laser_width") == 1 # one pixel
assert prefs.get("visualizer_laser_dot") == 6 assert prefs.get("visualizer_laser_dot") == 6
assert prefs.get("visualizer_laser_distance") == 1.5 assert prefs.get("visualizer_laser_grid_dot") == 2
assert prefs.get("visualizer_laser_pitch") == 30
lo, hi = vs.LIMITS["visualizer_laser_roll"]
slider = dialog._angle_sliders["visualizer_laser_roll"]
assert (slider.minimum(), slider.maximum()) == (lo, hi)
def test_sync_delay_saves_to_config_not_prefs(self, qapp, tmp_path, def test_sync_delay_saves_to_config_not_prefs(self, qapp, tmp_path,
monkeypatch): monkeypatch):
@@ -650,10 +617,10 @@ class TestPreferencesPage:
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg")) monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg"))
prefs = Preferences(tmp_path) prefs = Preferences(tmp_path)
dialog = self._dialog(prefs) dialog = self._dialog(prefs)
dialog._sync_slider.setValue(150) dialog._sync_sliders["laser"].setValue(150)
dialog._save_sync_delay() dialog._save_sync_delay()
assert load_config()["visualizer_sync_delay_ms"] == 150 assert load_config()["visualizer_sync_delays"]["laser"] == 150
assert prefs.get("visualizer_sync_delay_ms") is None assert prefs.get("visualizer_sync_delays") is None
def test_a_swatch_repaints_its_slot(self, qapp, tmp_path): def test_a_swatch_repaints_its_slot(self, qapp, tmp_path):
from lintunes import theme from lintunes import theme
@@ -792,7 +759,7 @@ class TestPhosphor:
def test_a_setting_change_starts_it_afresh(self, qapp): def test_a_setting_change_starts_it_afresh(self, qapp):
r = _run(vs.LaserRenderer(_config(laser_afterimage=0.5)), _sine(150, 0.2)) r = _run(vs.LaserRenderer(_config(laser_afterimage=0.5)), _sine(150, 0.2))
_paint(r, 300, 200) _paint(r, 300, 200)
r.configure(_config(laser_afterimage=0.5, laser_pitch=30)) r.configure(_config(laser_afterimage=0.5, laser_width=3))
assert r._phosphor == {} assert r._phosphor == {}
@@ -902,7 +869,7 @@ class TestPresets:
def test_save_and_apply(self, qapp, tmp_path): def test_save_and_apply(self, qapp, tmp_path):
prefs = Preferences(tmp_path) prefs = Preferences(tmp_path)
dialog = self._dialog(prefs) dialog = self._dialog(prefs)
dialog._angle_sliders["visualizer_laser_pitch"].setValue(40) dialog._grid_dot_slider.setValue(40)
dialog._grid.setChecked(True) dialog._grid.setChecked(True)
dialog._speaker.setValues(150, 300) dialog._speaker.setValues(150, 300)
dialog._width_box.setValue(3.5) dialog._width_box.setValue(3.5)
@@ -913,17 +880,17 @@ class TestPresets:
# Back to Default: every control (and setting) follows. # Back to Default: every control (and setting) follows.
dialog._on_preset_chosen("laser", combo.findData("Default")) dialog._on_preset_chosen("laser", combo.findData("Default"))
assert prefs.get("visualizer_laser_pitch") == 0 assert prefs.get("visualizer_laser_grid_dot") == 1
assert prefs.get("visualizer_laser_grid") is False assert prefs.get("visualizer_laser_grid") is False
assert prefs.get("visualizer_laser_width") == 1.5 assert prefs.get("visualizer_laser_width") == 1.5
assert dialog._speaker.values() == (0, 300) assert dialog._speaker.values() == (0, 300)
assert combo.currentText() == "Default" assert combo.currentText() == "Default"
dialog._on_preset_chosen("laser", combo.findData("Big Tilt")) dialog._on_preset_chosen("laser", combo.findData("Big Tilt"))
assert prefs.get("visualizer_laser_pitch") == 40 assert prefs.get("visualizer_laser_grid_dot") == 0.4
assert prefs.get("visualizer_laser_grid") is True assert prefs.get("visualizer_laser_grid") is True
assert prefs.get("visualizer_laser_width") == 3.5 assert prefs.get("visualizer_laser_width") == 3.5
assert dialog._angle_sliders["visualizer_laser_pitch"].value() == 40 assert dialog._grid_dot_slider.value() == 40
assert dialog._speaker.values() == (150, 300) assert dialog._speaker.values() == (150, 300)
assert combo.currentText() == "Big Tilt" assert combo.currentText() == "Big Tilt"
@@ -966,13 +933,16 @@ class TestPresets:
assert set(presets.presets(prefs, "bars")["x"]) == {"visualizer_bars_fade", assert set(presets.presets(prefs, "bars")["x"]) == {"visualizer_bars_fade",
"visualizer_bars_count"} "visualizer_bars_count"}
assert "visualizer_sync_delay_ms" not in presets.STYLE_KEYS["laser"] assert "visualizer_sync_delay_ms" not in presets.STYLE_KEYS["laser"]
assert "visualizer_sync_delays" not in presets.STYLE_KEYS["laser"]
def test_an_old_preset_takes_new_settings_defaults(self, qapp, tmp_path): def test_an_old_preset_takes_new_settings_defaults(self, qapp, tmp_path):
prefs = Preferences(tmp_path) prefs = Preferences(tmp_path)
prefs.set(presets.PRESETS_KEY, prefs.set(presets.PRESETS_KEY,
{"laser": {"Old": {"visualizer_laser_pitch": 20}}}) {"laser": {"Old": {"visualizer_laser_width": 4,
"visualizer_laser_pitch": 20}}})
values = presets.values_of(prefs, "laser", "Old") values = presets.values_of(prefs, "laser", "Old")
assert values["visualizer_laser_pitch"] == 20 assert values["visualizer_laser_width"] == 4
assert "visualizer_laser_pitch" not in values # retired
assert values["visualizer_laser_glow"] is True # default assert values["visualizer_laser_glow"] is True # default
def test_every_style_key_has_a_control(self, qapp, tmp_path): def test_every_style_key_has_a_control(self, qapp, tmp_path):
-49
View File
@@ -180,55 +180,6 @@ class TestHeadings:
assert not dialog._glow.font().bold() assert not dialog._glow.font().bold()
class TestLaserDiagram:
def test_the_dialog_has_one_and_it_follows_the_settings(self, qapp, tmp_path):
prefs = Preferences(tmp_path)
dialog = _prefs_dialog(prefs)
dialog._angle_sliders["visualizer_laser_pitch"].setValue(-25)
dialog._distance_slider.setValue(16)
config = dialog._diagram._config
assert config["visualizer_laser_pitch"] == -25
assert config["visualizer_laser_distance"] == 1.6
def test_labelled_sliders_lost_their_numbers(self, qapp, tmp_path):
dialog = _prefs_dialog(Preferences(tmp_path))
page = dialog._viz_pages.widget(2)
dialog._viz_pages.setCurrentIndex(2)
dialog.show()
visible = {label.text() for label in page.findChildren(QLabel)
if label.isVisible()}
assert "3.5 m" not in visible and "0°" not in visible
assert "3 px" not in visible
dialog.close()
def test_paints_at_any_setting(self, qapp):
from lintunes.gui import visualizer_styles as vs
from lintunes.gui.laser_diagram import LaserDiagram
for overrides in ({}, {"visualizer_laser_pitch": 60,
"visualizer_laser_yaw": -60,
"visualizer_laser_roll": 180,
"visualizer_laser_distance": 1.0,
"visualizer_laser_dot": 16}):
config = vs.settings(None)
config.update(overrides)
diagram = LaserDiagram(config)
diagram.resize(420, 160)
assert not diagram.grab().isNull()
def test_the_screen_turns_with_the_angles(self, qapp):
from PyQt6.QtCore import QPointF
from lintunes.gui import visualizer_styles as vs
from lintunes.gui.laser_diagram import LaserDiagram
diagram = LaserDiagram(vs.settings(None))
square = diagram.screen_corners(QPointF(0, 0), 30)
pitched = diagram.screen_corners(QPointF(0, 0), 30, pitch=40,
yaw=0, roll=0)
# Tipping the top away moves the top edge along the beam.
assert pitched[2].x() != pytest.approx(square[2].x())
# A square screen's vertical edges are vertical.
assert square[1].x() == pytest.approx(square[2].x())
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
# 5. Copying songs gives other apps a song list # 5. Copying songs gives other apps a song list
# -------------------------------------------------------------------------- # --------------------------------------------------------------------------
+4 -3
View File
@@ -54,14 +54,15 @@ class TestBetweenFrames:
class TestSyncSooner: class TestSyncSooner:
def test_negative_delay_is_kept(self): def test_negative_delay_is_kept(self):
assert vs.sync_delay_ms({"visualizer_sync_delay_ms": -30}) == -30 assert vs.sync_delay_ms({"visualizer_sync_delay_ms": -30}, "bars") == -30
assert vs.sync_delay_ms({"visualizer_sync_delay_ms": -999}) == vs.SYNC_DELAY_LIMITS[0] assert vs.sync_delay_ms({"visualizer_sync_delay_ms": -999},
"bars") == vs.SYNC_DELAY_LIMITS[0]
def test_slider_reads_sooner_and_later(self, qapp, tmp_path, monkeypatch): def test_slider_reads_sooner_and_later(self, qapp, tmp_path, monkeypatch):
from lintunes.gui import preferences_dialog as pd from lintunes.gui import preferences_dialog as pd
monkeypatch.setattr(pd, "load_config", lambda: {}) monkeypatch.setattr(pd, "load_config", lambda: {})
dialog = pd.PreferencesDialog(Preferences(tmp_path), _LastFm()) dialog = pd.PreferencesDialog(Preferences(tmp_path), _LastFm())
assert dialog._sync_slider.minimum() < 0 assert dialog._sync_sliders["kaleidostrobe"].minimum() < 0
assert pd._sync_text(-20) == "20 ms sooner" assert pd._sync_text(-20) == "20 ms sooner"
assert pd._sync_text(40) == "40 ms later" assert pd._sync_text(40) == "40 ms later"