-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlay.py
More file actions
622 lines (565 loc) · 32.3 KB
/
Copy pathoverlay.py
File metadata and controls
622 lines (565 loc) · 32.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
"""Transparent PyQt6 overlay for spectrum rendering."""
from __future__ import annotations
import ctypes
from pathlib import Path
import numpy as np
from PyQt6.QtCore import QPoint, QPointF, QRectF, Qt, QTimer
from PyQt6.QtGui import QColor, QFont, QGuiApplication, QImage, QPainter, QPainterPath, QPen
from PyQt6.QtWidgets import QLabel, QWidget
from config import save_config
from signal_processing import Spectrum, frequency_position
class _DataLabel(QLabel):
def __init__(self, name: str, owner: "OverlayWidget") -> None:
super().__init__(owner)
self.name = name
self.owner = owner
self._drag_start: QPoint | None = None
self._resize_start: QPoint | None = None
self._initial_size_factor = 0.045
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
def mousePressEvent(self, event) -> None: # type: ignore[no-untyped-def]
if not self.owner.data_edit_mode:
event.ignore()
return
if event.position().x() >= self.width() - 18 and event.position().y() >= self.height() - 18:
self._resize_start = event.position().toPoint()
self._initial_size_factor = self.owner.config["data"]["text_layout"][self.name]["size_factor"]
else:
self._drag_start = event.globalPosition().toPoint()
self.grabMouse()
event.accept()
def mouseMoveEvent(self, event) -> None: # type: ignore[no-untyped-def]
if self._resize_start is not None:
delta = event.position().y() - self._resize_start.y()
factor = max(0.005, min(0.25, self._initial_size_factor + delta / max(1, self.owner.height())))
self.owner._set_text_size(self.name, factor)
elif self._drag_start is not None:
delta = event.globalPosition().toPoint() - self._drag_start
self.move(self.pos() + delta)
self._drag_start = event.globalPosition().toPoint()
self.owner._store_text_position(self.name, self.geometry().center())
event.accept()
def mouseReleaseEvent(self, event) -> None: # type: ignore[no-untyped-def]
self._drag_start = None
self._resize_start = None
if self.mouseGrabber() is self:
self.releaseMouse()
event.accept()
class OverlayWidget(QWidget):
"""A click-through widget that paints the current spectrum."""
def __init__(self, config: dict, parent: QWidget | None = None) -> None:
flags = Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool
if config["general"]["always_on_top"]:
flags |= Qt.WindowType.WindowStaysOnTopHint
super().__init__(parent, flags)
self.config = config
self.spectrum: Spectrum | None = None
self.input_spectrum: Spectrum | None = None
self._drag_offset: QPointF | None = None
self._resize_origin: QPointF | None = None
self._resize_center: QPointF | None = None
self._resize_size: tuple[int, int] | None = None
self._output_frequency: float | None = None
self._output_bpm: float | None = None
self._input_frequency: float | None = None
self._input_bpm: float | None = None
self._output_volume: float | None = None
self._input_volume: float | None = None
self.data_edit_mode = False
self._slider_positions = {"output": None, "input": None}
self._slider_time = None
self._data_labels = {name: _DataLabel(name, self) for name in ("output_frequency", "output_bpm", "output_volume", "input_frequency", "input_bpm", "input_volume")}
self._label_state: dict[str, tuple] = {}
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setMouseTracking(True)
self._background_image = QImage()
self.setGeometry(0, 0, 900, 420)
self._restore_geometry()
self._load_background_image()
self._timer = QTimer(self)
self._timer.timeout.connect(self.update)
self._timer.start(max(1, round(1000 / config["visual"]["frame_rate"])))
def showEvent(self, event) -> None: # type: ignore[no-untyped-def]
super().showEvent(event)
self._set_click_through(self.config["general"]["click_through"])
def set_spectrum(self, spectrum: Spectrum | None, input_spectrum: Spectrum | None = None) -> None:
self.spectrum = spectrum
self.input_spectrum = input_spectrum
def paintEvent(self, event) -> None: # type: ignore[no-untyped-def]
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
self._paint_background(painter)
mode = self.config["visual"]["mode"]
if self.config["visual"]["orientation"] == "circle":
if mode == "line":
self._paint_circle_line(painter)
else:
self._paint_circle_bars(painter)
elif mode == "line":
self._paint_line(painter)
else:
self._paint_bars(painter)
if not self.config["general"]["click_through"]:
self._paint_resize_grip(painter)
self._paint_data_overlay(painter)
painter.end()
self._update_data_labels()
def _paint_bars(self, painter: QPainter) -> None:
left, right = self._values(self.spectrum)
input_left, input_right = self._values(self.input_spectrum)
visual = self.config["visual"]
margin = visual["margin"]
width = max(1.0, (self.width() - 2 * margin) / len(left))
painter.setPen(Qt.PenStyle.NoPen)
baseline = self.height() - margin
available_height = self.height() - 2 * margin
slot_width = (self.width() - 2 * margin) / max(1, len(left))
bar_width = int(slot_width * float(visual["bar_width"]))
if bar_width <= 0:
return
output_layers = ((self.spectrum, left, "output", "left_color", False),) if self.config["output"]["channels"] == "mono" else ((self.spectrum, left, "output", "left_color", False), (self.spectrum, right, "output", "right_color", False))
layers = output_layers + ((self.input_spectrum, input_left, "input", "color", True), (self.input_spectrum, input_right, "input", "color", True))
for spectrum, values, section, color_name, mirrored in layers:
if spectrum is None:
continue
painter.setBrush(self._stream_color(section, color_name))
for index, value in enumerate(values):
height = max(1.0, float(value) * available_height)
painter.drawRoundedRect(
int(margin + index * width),
int(margin if mirrored else baseline - height),
bar_width,
int(height),
2,
2,
)
def _paint_circle_bars(self, painter: QPainter) -> None:
self._paint_circle_layers(painter, False)
def _paint_circle_line(self, painter: QPainter) -> None:
self._paint_circle_layers(painter, True)
def _paint_line(self, painter: QPainter) -> None:
margin = self.config["visual"]["margin"]
visual = self.config["visual"]
for spectrum, values, section, color_name, mirrored in self._layers():
if spectrum is None:
continue
points = [QPointF(margin + index * (self.width() - 2 * margin) / max(1, len(values) - 1), margin + float(value) * (self.height() - 2 * margin) if mirrored else self.height() - margin - float(value) * (self.height() - 2 * margin)) for index, value in enumerate(values)]
painter.setPen(QPen(self._stream_color(section, color_name), 2.0))
if visual["line_style"] == "trace":
painter.drawPolyline(points)
else:
painter.drawPath(self._smooth_path(points))
def _layers(self):
left, right = self._values(self.spectrum)
input_left, input_right = self._values(self.input_spectrum)
output_layers = ((self.spectrum, left, "output", "left_color", False),) if self.config["output"]["channels"] == "mono" else ((self.spectrum, left, "output", "left_color", False), (self.spectrum, right, "output", "right_color", False))
return output_layers + ((self.input_spectrum, input_left, "input", "color", True), (self.input_spectrum, input_right, "input", "color", True))
def _paint_circle_layers(self, painter: QPainter, as_line: bool) -> None:
visual = self.config["visual"]
center = QPointF(self.width() / 2, self.height() / 2)
dimension = min(self.width(), self.height())
radius = max(1.0, min(dimension * visual["radius_ratio"], dimension / 2 - visual["margin"]))
for spectrum, values, section, color_name, mirrored in self._layers():
if spectrum is None:
continue
direction = -1 if mirrored else 1
points = []
for index, value in enumerate(values):
angle = 2 * np.pi * index / len(values) - np.pi / 2
distance = radius + direction * float(value) * radius
points.append(QPointF(center.x() + distance * np.cos(angle), center.y() + distance * np.sin(angle)))
if as_line:
points.append(points[0])
painter.setPen(QPen(self._stream_color(section, color_name), 2.0))
if visual["line_style"] == "trace":
painter.drawPolyline(points)
else:
painter.drawPath(self._smooth_path(points))
else:
if float(visual["bar_width"]) <= 0:
continue
arc_length = 2 * np.pi * radius
slot_width = arc_length / max(1, len(values))
painter.setPen(QPen(self._stream_color(section, color_name), max(1.0, slot_width * float(visual["bar_width"]))))
for index, point in enumerate(points):
angle = 2 * np.pi * index / len(values) - np.pi / 2
end = QPointF(center.x() + radius * np.cos(angle), center.y() + radius * np.sin(angle))
painter.drawLine(end, point)
@staticmethod
def _smooth_path(points: list[QPointF]) -> QPainterPath:
path = QPainterPath()
if not points:
return path
path.moveTo(points[0])
for index in range(1, len(points)):
previous = points[index - 1]
current = points[index]
midpoint = QPointF((previous.x() + current.x()) / 2, (previous.y() + current.y()) / 2)
path.quadTo(previous, midpoint)
path.quadTo(points[-1], points[-1])
return path
def _values(self, spectrum: Spectrum | None) -> tuple[np.ndarray, np.ndarray]:
if spectrum is None:
empty = np.zeros(1, dtype=np.float32)
return empty, empty
return spectrum.left_magnitudes, spectrum.right_magnitudes
def _paint_resize_grip(self, painter: QPainter) -> None:
painter.setPen(QPen(QColor("#FFFFFF"), 2))
corner = QPointF(self.width() - 18, self.height() - 18)
painter.drawLine(corner, QPointF(self.width() - 4, self.height() - 4))
painter.drawLine(QPointF(self.width() - 12, self.height() - 4), QPointF(self.width() - 4, self.height() - 12))
def mousePressEvent(self, event) -> None: # type: ignore[no-untyped-def]
if self.config["general"]["click_through"]:
event.ignore()
return
position = event.position()
if position.x() >= self.width() - 48 and position.y() >= self.height() - 48:
self._resize_origin = event.globalPosition()
self._resize_center = QPointF(self.geometry().center())
self._resize_size = (self.width(), self.height())
self.grabMouse()
else:
self._drag_offset = position
self.grabMouse()
event.accept()
def mouseMoveEvent(self, event) -> None: # type: ignore[no-untyped-def]
if self._resize_origin is not None and self._resize_size is not None:
delta = event.globalPosition() - self._resize_origin
width = max(180, int(self._resize_size[0] + 2 * delta.x()))
height = max(100, int(self._resize_size[1] + 2 * delta.y()))
center = self._resize_center
if center is not None:
self.setGeometry(
int(center.x() - width / 2), int(center.y() - height / 2), width, height
)
elif self._drag_offset is not None:
self.move((event.globalPosition() - self._drag_offset).toPoint())
event.accept()
def mouseReleaseEvent(self, event) -> None: # type: ignore[no-untyped-def]
self._drag_offset = None
self._resize_origin = None
self._resize_center = None
self._resize_size = None
if self.mouseGrabber() is self:
self.releaseMouse()
event.accept()
def _set_click_through(self, enabled: bool) -> None:
if not hasattr(self, "winId"):
return
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, enabled)
hwnd = int(self.winId())
user32 = ctypes.windll.user32
get_window_long = getattr(user32, "GetWindowLongPtrW", user32.GetWindowLongW)
set_window_long = getattr(user32, "SetWindowLongPtrW", user32.SetWindowLongW)
ex_style = get_window_long(hwnd, -20)
if enabled:
ex_style |= 0x00000020 | 0x00080000
else:
ex_style &= ~0x00000020
set_window_long(hwnd, -20, ex_style)
user32.SetWindowPos(hwnd, 0, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0020 | 0x0040)
def set_click_through(self, enabled: bool) -> None:
self.config["general"]["click_through"] = enabled
self._set_click_through(enabled)
for label in self._data_labels.values():
label.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, enabled or not self.data_edit_mode)
if enabled:
self.setCursor(Qt.CursorShape.ArrowCursor)
else:
self.setCursor(Qt.CursorShape.SizeAllCursor)
self.update()
def set_data(self, output_frequency: float | None, output_bpm: float | None, input_frequency: float | None, input_bpm: float | None, output_volume: float | None = None, input_volume: float | None = None) -> None:
self._output_frequency = output_frequency
self._output_bpm = output_bpm
self._input_frequency = input_frequency
self._input_bpm = input_bpm
if output_volume is not None:
self._output_volume = output_volume
if input_volume is not None:
self._input_volume = input_volume
self._update_data_labels()
self.update()
def set_data_edit_mode(self, enabled: bool) -> None:
self.data_edit_mode = enabled
if enabled:
self.set_click_through(False)
for label in self._data_labels.values():
label.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, not enabled)
label.setStyleSheet("border: 1px dashed rgba(255,255,255,180);" if enabled else "border: none;")
self.update()
def _set_text_size(self, name: str, factor: float) -> None:
self.config["data"]["text_layout"][name]["size_factor"] = factor
self._update_data_labels()
save_config(self.config)
def reset_data_layout(self) -> None:
defaults = {
"output_frequency": {"x": 0.5, "y": 0.35, "size_factor": 0.045},
"output_bpm": {"x": 0.5, "y": 0.45, "size_factor": 0.045},
"output_volume": {"x": 0.5, "y": 0.55, "size_factor": 0.045},
"input_frequency": {"x": 0.5, "y": 0.65, "size_factor": 0.045},
"input_bpm": {"x": 0.5, "y": 0.75, "size_factor": 0.045},
"input_volume": {"x": 0.5, "y": 0.85, "size_factor": 0.045},
}
self.config["data"]["text_layout"] = defaults
self.config["data"]["data_font"] = "Segoe UI"
self._update_data_labels()
save_config(self.config)
def _store_text_position(self, name: str, center: QPoint) -> None:
layout = self.config["data"]["text_layout"][name]
layout["x"] = max(0.0, min(1.0, center.x() / max(1, self.width())))
layout["y"] = max(0.0, min(1.0, center.y() / max(1, self.height())))
save_config(self.config)
def _update_data_labels(self) -> None:
mode = self.config["data"]["data_frequency_mode"]
values = {
"output_frequency": self._format_data_frequency(self._output_frequency, mode),
"output_bpm": f"{self._output_bpm:.0f} BPM" if self._output_bpm is not None else "",
"output_volume": self._format_volume(self._output_volume),
"input_frequency": self._format_data_frequency(self._input_frequency, mode),
"input_bpm": f"{self._input_bpm:.0f} BPM" if self._input_bpm is not None else "",
"input_volume": self._format_volume(self._input_volume),
}
data = self.config["data"]
visible = {"output_frequency": data["show_output_frequency"], "output_bpm": data["show_output_bpm"], "output_volume": data["show_output_volume"], "input_frequency": data["show_input_frequency"], "input_bpm": data["show_input_bpm"], "input_volume": data["show_input_volume"]}
for name, label in self._data_labels.items():
layout = data["text_layout"][name]
font_size = max(6.0, min(self.width(), self.height()) * float(layout["size_factor"]))
style_key = (str(data["data_font"]), round(font_size, 3), str(data["data_color"]), round(float(data["data_opacity"]), 4), self.data_edit_mode)
if self._label_state.get(name, (None,))[0] != style_key:
font = QFont(str(data["data_font"]))
font.setPointSizeF(font_size)
label.setFont(font)
data_color = QColor(data["data_color"])
data_color.setAlphaF(float(data["data_opacity"]))
red, green, blue, alpha = data_color.getRgb()
border = "border: 1px dashed rgba(255,255,255,180);" if self.data_edit_mode else "border: none;"
label.setStyleSheet(f"{border} color: rgba({red}, {green}, {blue}, {alpha});")
if label.text() != values[name]:
label.setText(values[name])
label.adjustSize()
if name.endswith("_volume"):
stable_width = label.fontMetrics().boundingRect("0.000 Vol").width()
label.setMinimumWidth(stable_width)
label.setFixedWidth(stable_width)
label.setVisible(bool(visible[name]) or self.data_edit_mode)
if label._drag_start is None and label._resize_start is None:
center = QPoint(int(layout["x"] * self.width()), int(layout["y"] * self.height()))
if label.pos() != center - label.rect().center():
label.move(center - label.rect().center())
self._label_state[name] = (style_key, values[name], label.size(), label.pos(), bool(label.isVisible()))
def _stream_color(self, section: str, key: str) -> QColor:
if section == "output" and self.config[section]["channels"] == "mono":
key = "color"
color = QColor(self.config[section][key])
color.setAlphaF(color.alphaF() * float(self.config[section]["opacity"]))
return color
def _paint_background(self, painter: QPainter) -> None:
if not self._background_image.isNull():
painter.drawImage(self.rect(), self._background_image)
color = QColor(self.config["visual"]["background_color"])
opacity = float(self.config["visual"]["background_opacity"])
color.setAlpha(max(1, round(opacity * 255)))
painter.fillRect(self.rect(), color)
def _load_background_image(self) -> None:
image_path = self.config["visual"]["background_image"].strip()
self._background_image = QImage(image_path) if image_path and Path(image_path).is_file() else QImage()
def _paint_data_overlay(self, painter: QPainter) -> None:
data = self.config["data"]
visual = self.config["visual"]
marker_color = QColor(data["marker_color"])
marker_color.setAlpha(round(float(data["marker_opacity"]) * 255))
painter.setPen(QPen(marker_color, 1))
if data["show_frequency_markers"]:
values = [self._parse_marker(item.strip()) for item in data["marker_values"].split(",") if item.strip()]
values = [value for value in values if value > 0]
minimum = max(1.0, self._active_frequency_min())
maximum = max(minimum + 1.0, self._active_frequency_max())
for frequency in values:
if not minimum <= frequency <= maximum:
continue
position = self._frequency_position(frequency, minimum, maximum)
output_proximity = self._marker_proximity(frequency, self._output_frequency, minimum, maximum)
input_proximity = self._marker_proximity(frequency, self._input_frequency, minimum, maximum)
proximity = max(output_proximity, input_proximity)
slider_color = data["output_slider_color"] if output_proximity >= input_proximity else data["input_slider_color"]
marker_color = self._blend_color(data["marker_color"], slider_color, proximity)
marker_color.setAlpha(round(float(data["marker_opacity"]) * 255))
painter.setPen(QPen(marker_color, 1))
label = self._format_note(frequency) if data["marker_mode"] == "notes" else self._format_frequency(frequency)
label_position = float(data["marker_label_position"])
if visual["orientation"] == "circle":
angle = 2 * np.pi * position - np.pi / 2
center = QPointF(self.width() / 2, self.height() / 2)
radius = min(self.width(), self.height()) * visual["radius_ratio"]
start = radius * self._interpolated_marker_size("start", proximity)
end = radius * self._interpolated_marker_size("end", proximity)
start_point = QPointF(center.x() + start * np.cos(angle), center.y() + start * np.sin(angle))
end_point = QPointF(center.x() + end * np.cos(angle), center.y() + end * np.sin(angle))
painter.drawLine(start_point, end_point)
label_center = QPointF(center.x() + radius * label_position * np.cos(angle), center.y() + radius * label_position * np.sin(angle))
label_rect = painter.fontMetrics().boundingRect(label)
painter.drawText(QRectF(label_center.x() - label_rect.width() / 2, label_center.y() - label_rect.height() / 2, label_rect.width(), label_rect.height()), Qt.AlignmentFlag.AlignCenter, label)
else:
x = visual["margin"] + position * (self.width() - 2 * visual["margin"])
start = self.height() * (1.0 - self._interpolated_marker_size("start", proximity))
end = self.height() * (1.0 - self._interpolated_marker_size("end", proximity))
painter.drawLine(QPointF(x, start), QPointF(x, end))
label_center = QPointF(x, self.height() * label_position)
label_rect = painter.fontMetrics().boundingRect(label)
painter.drawText(QRectF(label_center.x() - label_rect.width() / 2, label_center.y() - label_rect.height() / 2, label_rect.width(), label_rect.height()), Qt.AlignmentFlag.AlignCenter, label)
self._paint_sliders(painter)
def _active_frequency_min(self) -> float:
return float(self.config["general"]["frequency_min"])
def _active_frequency_max(self) -> float:
return float(self.config["general"]["frequency_max"])
def _frequency_position(self, frequency: float, minimum: float | None = None, maximum: float | None = None) -> float:
general = self.config["general"]
return frequency_position(
frequency,
self._active_frequency_min() if minimum is None else minimum,
self._active_frequency_max() if maximum is None else maximum,
general["binning_method"],
0.0,
0.0,
self.config["visual"]["bar_count"],
general.get("non_empty_bins"),
)
def _format_data_frequency(self, frequency: float | None, mode: str) -> str:
if frequency is None:
return ""
return self._format_note(frequency) if mode == "notes" and frequency > 0 else self._format_frequency(frequency)
def _parse_marker(self, value: str) -> float:
try:
return float(value)
except ValueError:
return self._note_frequency(value)
@staticmethod
def _note_frequency(note: str) -> float:
names = {"C": 0, "C#": 1, "Db": 1, "D": 2, "D#": 3, "Eb": 3, "E": 4, "F": 5, "F#": 6, "Gb": 6, "G": 7, "G#": 8, "Ab": 8, "A": 9, "A#": 10, "Bb": 10, "B": 11}
try:
name = note[:-1]
octave = int(note[-1])
return 440.0 * 2 ** ((12 * (octave - 4) + names[name] - 9) / 12)
except (KeyError, ValueError, IndexError):
return 0.0
@staticmethod
def _format_frequency(frequency: float) -> str:
return f"{frequency:.0f} Hz"
@staticmethod
def _format_volume(volume: float | None) -> str:
return f"{max(0.0, min(1.0, volume)):.3f} Vol" if volume is not None else ""
def _marker_proximity(self, marker: float, frequency: float | None, minimum: float, maximum: float) -> float:
if frequency is None or frequency <= 0:
return 0.0
marker_position = self._frequency_position(marker, minimum, maximum)
frequency_position = self._frequency_position(max(minimum, min(maximum, frequency)), minimum, maximum)
distance = abs(marker_position - frequency_position)
if self.config["visual"]["orientation"] == "circle":
distance = min(distance, 1.0 - distance)
limit = float(self.config["data"]["marker_interpolation_distance"])
if limit <= 0.0:
return 1.0 if distance <= 1e-9 else 0.0
return max(0.0, min(1.0, 1.0 - distance / limit))
@staticmethod
def _blend_color(first: str, second: str, amount: float) -> QColor:
left, right = QColor(first), QColor(second)
amount = max(0.0, min(1.0, amount))
color = QColor(
round(left.red() + (right.red() - left.red()) * amount),
round(left.green() + (right.green() - left.green()) * amount),
round(left.blue() + (right.blue() - left.blue()) * amount),
round(left.alpha() + (right.alpha() - left.alpha()) * amount),
)
return color
def _interpolated_marker_size(self, endpoint: str, proximity: float) -> float:
data = self.config["data"]
normal = float(data[f"marker_size_{endpoint}"])
accent = float(data[f"accent_marker_size_{endpoint}"])
return normal + (accent - normal) * proximity
@staticmethod
def _format_note(frequency: float) -> str:
names = ("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
midi = round(69 + 12 * np.log2(frequency / 440.0))
return f"{names[midi % 12]}{midi // 12 - 1}"
def _paint_sliders(self, painter: QPainter) -> None:
for stream, frequency in (("output", self._output_frequency), ("input", self._input_frequency)):
data = self.config["data"]
if not data[f"{stream}_slider_enabled"]:
self._slider_positions[stream] = None
continue
minimum = max(1.0, self._active_frequency_min())
maximum = max(minimum + 1.0, self._active_frequency_max())
size_start = float(data[f"{stream}_slider_size_start"])
size_end = float(data[f"{stream}_slider_size_end"])
target = 0.0 if frequency is None or frequency <= 0 else self._frequency_position(frequency, minimum, maximum)
current = self._slider_positions[stream]
if current is None:
current = 0.0
step = float(data["slider_velocity"])
current += max(-step, min(step, target - current))
self._slider_positions[stream] = current
color = QColor(data[f"{stream}_slider_color"])
color.setAlpha(round(float(data["marker_opacity"]) * 255))
painter.setPen(QPen(color, 2))
if current <= 0.001:
continue
if self.config["visual"]["orientation"] == "circle":
angle = 2 * np.pi * current - np.pi / 2
center = QPointF(self.width() / 2, self.height() / 2)
radius = max(1.0, min(self.width(), self.height()) * self.config["visual"]["radius_ratio"] - self.config["visual"]["margin"])
painter.drawLine(QPointF(center.x() + radius * size_start * np.cos(angle), center.y() + radius * size_start * np.sin(angle)), QPointF(center.x() + radius * size_end * np.cos(angle), center.y() + radius * size_end * np.sin(angle)))
else:
x = self.config["visual"]["margin"] + current * (self.width() - 2 * self.config["visual"]["margin"])
painter.drawLine(QPointF(x, self.height() * (1.0 - size_start)), QPointF(x, self.height() * (1.0 - size_end)))
def apply_config(self, config: dict) -> None:
self.config = config
general = config["general"]
self.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, general["always_on_top"])
self._load_background_image()
self.set_click_through(general["click_through"])
self._update_data_labels()
self.show()
self.update()
def closeEvent(self, event) -> None: # type: ignore[no-untyped-def]
self.save_state()
super().closeEvent(event)
def save_state(self) -> None:
general = self.config["general"]
position = self.geometry().topLeft()
general["window_position"] = {"x": position.x(), "y": position.y()}
general["window_size"] = {"width": self.width(), "height": self.height()}
screen = self.screen()
general["window_monitor"] = screen.name() if screen is not None else ""
save_config(self.config)
def _restore_geometry(self) -> None:
general = self.config["general"]
saved_screen = str(general.get("window_monitor", ""))
screen = next((candidate for candidate in QGuiApplication.screens() if candidate.name() == saved_screen), None)
screen = screen or QGuiApplication.primaryScreen()
position = general.get("window_position", {})
size = general.get("window_size", {})
width = max(180, int(size.get("width", 500)))
height = max(100, int(size.get("height", 500)))
if screen is None:
self.setGeometry(int(position.get("x", 0)), int(position.get("y", 0)), width, height)
return
available = screen.availableGeometry()
x = int(position.get("x", available.left() + (available.width() - width) // 2))
y = int(position.get("y", available.top() + (available.height() - height) // 2))
if not available.contains(QPoint(x, y)):
x = available.left() + (available.width() - width) // 2
y = available.top() + (available.height() - height) // 2
self.setGeometry(x, y, width, height)
def recenter(self) -> None:
width = height = 500
screen = QGuiApplication.primaryScreen()
if screen is not None:
available = screen.availableGeometry()
size = int(min(available.width(), available.height()) * 0.5)
width = height = max(180, size)
x = available.left() + (available.width() - width) // 2
y = available.top() + (available.height() - height) // 2
else:
x, y = 0, 0
self.setGeometry(x, y, width, height)