Repository navigation
Expand file tree
/
Copy pathoverlay_ui.py
More file actions
1370 lines (1269 loc) · 63.7 KB
/
Copy pathoverlay_ui.py
File metadata and controls
1370 lines (1269 loc) · 63.7 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""OverlayMenu - the settings menu right inside the overlay layer, like ReShade.
It is drawn on the same pygame surface as the HUD and the alerts, so there is
still a single window: no fight over topmost and focus with the game.
Separation of duties: this module BUILDS THE LAYOUT and DRAWS it. It does not
touch pygame.display, does not read events and knows nothing about the worker.
The layout is a flat list of items with rectangles, and the same list serves as
the hit table for the mouse (hit()).
The layout is line-based: every control has its own label line and its own line
for the control itself. They used to share one line and the label ran into the
value and the arrows.
All sizes are given in 1440p base units and multiplied by scale - the same
factor the HUD uses (display.ui_scale_for).
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Any, Callable
import pygame
from i18n import STRINGS
# --- Themes. The accent is shared; background and text change ------------
THEMES = {
"light": {
"bg": "#F0EEE6", # warm cream panel background
"surface": "#E8E5DC", # slider tracks, fields
"border": "#DCD8CC",
"text": "#191919",
"muted": "#79776F",
"accent": "#D97757", # clay accent
"ok": "#5E8C61", # green of the support indicator
"danger": "#BC4C2E",
},
"dark": {
"bg": "#262624",
"surface": "#32312E",
"border": "#403E3A",
"text": "#F5F4EF",
"muted": "#A3A099",
"accent": "#D97757",
"ok": "#7FB07F",
"danger": "#E06C4F",
},
}
# What we show in the remapping page and in which order. On the left is the
# command the hotkey lives under in hotkeys.DEFAULT_BINDINGS and in
# config["hotkeys"].
HOTKEY_ROWS = (
("toggle", "hk_nr"),
("settings", "hk_menu"),
("screenshot_menu", "hk_shot"),
("record", "hk_record"),
("window_mode", "hk_window"),
("quit", "hk_quit"),
)
# pygame.key.name() gives "page up" while the parser in hotkeys.parse_binding
# expects "PGUP", and the numpad comes back as "[1]" where the parser wants
# "NUM1". These are the only ones that differ.
_KEY_ALIASES = {"page up": "PGUP", "page down": "PGDN",
"return": "ENTER", "escape": "ESC",
"[.]": "Numdot", "[+]": "Numplus", "[-]": "Numminus",
"[*]": "Nummul", "[/]": "Numdiv"}
# Mixed case on purpose: the parser upper-cases anyway, and "Num3" is what the
# default bindings print on the buttons.
_KEY_ALIASES.update({f"[{n}]": f"Num{n}" for n in range(10)})
def key_text(event) -> str | None:
"""Keyboard event -> a string like "Ctrl+Alt+Q" for parse_binding.
None when only a modifier is pressed: there is no such thing as a binding
made of a lone Ctrl.
"""
name = pygame.key.name(event.key)
if name in ("left ctrl", "right ctrl", "left alt", "right alt",
"left shift", "right shift", "left meta", "right meta"):
return None
base = _KEY_ALIASES.get(name, name.upper())
mods = pygame.key.get_mods()
parts = []
if mods & pygame.KMOD_CTRL:
parts.append("Ctrl")
if mods & pygame.KMOD_ALT:
parts.append("Alt")
if mods & pygame.KMOD_SHIFT:
parts.append("Shift")
parts.append(base)
return "+".join(parts)
def palette(theme: str) -> dict:
"""The theme palette. The alerts in display.py need it too - same look."""
return THEMES.get(theme, THEMES["light"])
# --- Base layout (1440p units) --------------------------------------------
PANEL_W = 540
PAD = 26
TITLE_H = 54
LABEL_H = 24
CTRL_H = 26
ROW_GAP = 20
SECTION_GAP = 14
SLIDER_H = 6
KNOB_R = 9
BTN_H = 42
BTN_PAD = 18
BTN_GAP = 10
ICON_W = 30 # header button: a rounded square, not a circle
ACTION_H = 46 # action button: title with the hotkey caption below it
EXIT_H = 64 # exit: plus an explanation on a third line
STAT_LINE_H = 24
STAT_PAD = 14
RADIUS = 10
FONT_SIZE = 17
TITLE_SIZE = 21
SMALL_SIZE = 14
PARAM_KEYS = ("intensity", "local_tone", "local_structure", "skin_structure")
PARAM_MIN, PARAM_MAX = 0.0, 2.5
SKIN_MIN = -1.0
def _rgb(color: str) -> tuple[int, int, int]:
c = color.lstrip("#")
return int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)
@dataclass
class Item:
"""A layout item: what it is, where it sits, what it belongs to."""
kind: str # "slider" | "button" | "toggle" | "choice"
key: str
rect: pygame.Rect # mouse hit area
lo: float = 0.0
hi: float = 1.0
value: float = 0.0
payload: Any = None
extra: dict = field(default_factory=dict)
class OverlayMenu:
"""The overlay menu: visibility, state, layout, drawing."""
def __init__(self, scale: float, font_loader: Callable[[int], Any]):
self.scale = scale
# Manual multiplier: needed before the fonts are created, they size
# themselves through _u
self.user_scale = 1.0
self._load_font = font_loader
self.visible = False
self.lang = "en"
self.state: dict = {
"nr": True,
"work_scale": 1.0,
# Where the work size hits the NGX cap. Sent by main because only it
# knows the screen size. The slider runs one step past it, and that
# last step means "the whole screen" - the reduced mode off.
"work_scale_cap": 1.0,
"nr_small": False,
"screen_size": "",
"profile": "",
"profiles": [],
"params": {},
"recording": False,
"work_size": "",
"theme": "light",
"rec_seconds": 0.0,
"open_on_start": True,
"split": 0.0,
# Which card this is and whether NR runs on it. gpu_ok:
# True/False/None (None - the worker has not answered yet).
"gpu_text": "",
"gpu_ok": None,
"monitor": "0",
"monitors": [],
"autostart": False,
# The header shows the version; the channel label lives in the
# settings page (user rule 2026-09-08).
"version": "",
"channel": "",
}
# Pipeline readings: the same ones the HUD shows. The menu is meant to
# be the single place where both the settings and what is going on are
# visible.
self.stats: dict = {}
self.items: list[Item] = []
self._font = font_loader(self._u(FONT_SIZE))
self._title_font = font_loader(self._u(TITLE_SIZE))
self._small_font = font_loader(self._u(SMALL_SIZE))
self.panel_rect = pygame.Rect(0, 0, 0, 0)
self._stats_rect = pygame.Rect(0, 0, 0, 0)
# The panel can be dragged by its title bar and stretched by its
# corner. The offset is stored relative to the screen centre, so it
# survives a resolution change without the window ending up off-screen.
self.offset = [0, 0]
self._grip = pygame.Rect(0, 0, 0, 0)
self._title_bar = pygame.Rect(0, 0, 0, 0)
self._move_from = None
self._resize_from = None
# Panel height: None means "fit the content". It is set by dragging the
# bottom edge; content taller than the height scrolls.
self.user_height: int | None = None
self.scroll = 0
self.content_height = 0
self._max_scroll = 0
self._resize_h_from = None
# The last mouse position: in pygame the wheel arrives without
# coordinates, and pygame.mouse.get_pos() in a click-through window is
# not to be trusted.
self._mouse = (0, 0)
self._edge = pygame.Rect(0, 0, 0, 0)
self._viewport = pygame.Rect(0, 0, 0, 0)
self._scroll_track = pygame.Rect(0, 0, 0, 0)
self._scroll_thumb = pygame.Rect(0, 0, 0, 0)
# Which list is currently expanded (profile / language / theme).
# Cycling with arrows is awkward once there are more than two options.
self.open_choice: str | None = None
# Menu page: the main window or the settings behind the gear.
self.page = "main"
# The command we are currently waiting for a keypress for (or None).
self.capturing: str | None = None
# Hotkey captions: command -> "Num1". They come from main together with
# the bindings, so a remap shows up on the buttons immediately.
self.hotkeys: dict = {}
self._sections: list = []
self._hint_rel = pygame.Rect(0, 0, 0, 0)
self._rule_rel = pygame.Rect(0, 0, 0, 0)
self._rule2_rel = pygame.Rect(0, 0, 0, 0)
# What is under the cursor: "title" (draggable) or "grip" (resizable).
# Without the highlight these zones are invisible and impossible to
# find.
self.hover: str | None = None
@property
def c(self) -> dict:
"""Colours of the current theme."""
return palette(self.state.get("theme", "light"))
# -- helpers -----------------------------------------------------------
def _u(self, base: float) -> int:
"""1440p base units -> screen pixels."""
return max(1, int(round(base * self.scale * self.user_scale)))
def set_user_scale(self, value: float) -> None:
"""Manual panel stretching. The fonts have to be recreated."""
value = min(2.0, max(0.6, round(value, 2)))
if abs(value - self.user_scale) < 0.01:
return
self.user_scale = value
self._font = self._load_font(self._u(FONT_SIZE))
self._title_font = self._load_font(self._u(TITLE_SIZE))
self._small_font = self._load_font(self._u(SMALL_SIZE))
def toggle(self) -> bool:
self.visible = not self.visible
if not self.visible:
self._drag_item = None
return self.visible
@property
def dragging(self) -> bool:
"""Whether a slider is being dragged right now - while dragging the
state must not be updated, otherwise the value jumps between what the
mouse shows and what main has already applied."""
return getattr(self, "_drag_item", None) is not None
def set_hotkeys(self, mapping: dict) -> None:
"""Hotkey captions: command -> "Num1". Sourced from the real bindings."""
self.hotkeys = dict(mapping or {})
def set_stats(self, hud: dict) -> None:
self.stats = dict(hud or {})
def set_state(self, payload: dict) -> None:
for k, v in payload.items():
if k == "lang":
self.lang = v
elif k == "params" and isinstance(v, dict):
self.state["params"] = dict(v)
elif k in self.state:
self.state[k] = v
def title_center(self) -> tuple[int, int]:
"""The centre of the title bar in screen coordinates.
The mouse lands here when the menu opens, so the user does not have
to hunt for the pointer (user request). Valid after layout().
"""
r = self._title_bar
return (r.x + r.w // 2, r.y + r.h // 2)
def place_bottom_right(self, screen_w: int, screen_h: int,
margin: int = 24) -> None:
"""Put the panel into the bottom-right corner of the screen.
The temporary answer to "the menu flies off the desktop in window
mode": the offset from the config was computed for the 4K desktop and
lands the panel outside a small captured window. On every menu open in
window mode the panel starts in the bottom-right corner; the user
drags it where they want and the offset is saved on close as usual.
"""
self.layout(screen_w, screen_h)
w, h = self.panel_rect.w, self.panel_rect.h
# The offset is relative to the screen centre: solve for the corner.
self.offset = [screen_w - w - margin - (screen_w - w) // 2,
screen_h - h - margin - (screen_h - h) // 2]
self.layout(screen_w, screen_h)
def _capture_mouse(self, on: bool) -> None:
"""Capture the mouse while dragging the panel by its title bar.
Without it the drag dies the moment the cursor leaves the window:
pygame stops delivering MOUSEMOTION outside the window, and the
release click outside is lost too - the panel "stops and has to be
grabbed again" (user report). SetCapture keeps the events coming
until the button is released.
"""
try:
import ctypes
hwnd = pygame.display.get_wm_info()["window"]
if on:
ctypes.windll.user32.SetCapture(hwnd)
else:
ctypes.windll.user32.ReleaseCapture()
except Exception:
pass
# -- layout ------------------------------------------------------------
def layout(self, screen_w: int, screen_h: int) -> None:
"""Recompute the rectangles.
We walk top to bottom in relative coordinates, learn the height at the
end and shift everything at once - that way the panel height cannot
drift apart from the content (it used to come from a formula and lag
behind).
"""
s = STRINGS.get(self.lang, STRINGS["en"])
w = self._u(PANEL_W)
pad = self._u(PAD)
label_h = self._u(LABEL_H)
ctrl_h = self._u(CTRL_H)
gap = self._u(ROW_GAP)
inner_w = w - pad * 2
items: list[Item] = []
# Header icons: help and settings. There is deliberately no close
# cross - it hid the menu while sitting next to "quit the program".
iw = self._u(ICON_W)
igap = self._u(8)
iy = self._u(TITLE_H) // 2 - iw // 2
order = ["help", "gear"] if self.page != "settings" else ["close"]
# Laid out right to left: the right edge is the last icon.
for idx, kind in enumerate(reversed(order)):
ix = pad + inner_w - iw - idx * (iw + igap)
items.append(Item("icon", kind,
pygame.Rect(ix, iy, iw, iw)))
cy = self._u(TITLE_H) + self._u(SECTION_GAP)
# The readings block
stat_h = self._u(STAT_LINE_H) * 2 + self._u(STAT_PAD) * 2
self._stats_rel = pygame.Rect(pad, cy, inner_w, stat_h)
cy += stat_h + self._u(6)
# The GPU line: a status dot and the card model. A separate line rather
# than a cell in the readings block - this is not a pipeline reading
# but the answer to "does this work on my card at all".
gpu_h = self._u(SMALL_SIZE) + self._u(8)
self._gpu_rel = pygame.Rect(pad, cy, inner_w, gpu_h)
cy += gpu_h + gap
# The content is split into titled blocks: eight identical rows in a
# row gave the eye nothing to hold on to. The titles are not
# interactive, so they live in their own list rather than in items.
self._sections: list[tuple[str, pygame.Rect]] = []
sec_h = self._u(SMALL_SIZE) + self._u(10)
def section(title: str) -> None:
nonlocal cy
cy += self._u(6)
self._sections.append((title, pygame.Rect(pad, cy, inner_w, sec_h)))
cy += sec_h
def slider(key: str, lo: float, hi: float, value: float,
label: str, hint: str = "", value_text: str = "") -> None:
nonlocal cy
items.append(Item("slider", key,
pygame.Rect(pad, cy, inner_w, label_h + ctrl_h),
lo=lo, hi=hi, value=value,
extra={"label": label, "hint": hint,
"value_text": value_text,
"label_h": label_h}))
cy += label_h + ctrl_h + (self._u(SMALL_SIZE) + 4 if hint else 0) + gap
def choice(key: str, label: str, current: str, options: list) -> None:
nonlocal cy
items.append(Item("choice", key,
pygame.Rect(pad, cy, inner_w, label_h + ctrl_h),
payload=list(options),
extra={"label": label, "current": current,
"label_h": label_h}))
cy += label_h + ctrl_h + gap
def segmented(key: str, label: str, current: str, options: list,
labels: list | None = None) -> None:
"""A two- or three-way switch instead of a drop-down list.
A list for the sake of two values is an extra click and extra
expand/collapse machinery; here both options are visible at once.
"""
nonlocal cy
seg_w = min(inner_w - self._u(150), self._u(60) * len(options) + self._u(60))
rect = pygame.Rect(pad + inner_w - seg_w, cy, seg_w, ctrl_h)
items.append(Item("segmented", key, rect, payload=list(options),
extra={"label": label, "current": current,
"labels": list(labels or options)}))
cy += ctrl_h + gap
def toggle(key: str, label: str, on: bool) -> None:
nonlocal cy
items.append(Item("toggle", key,
pygame.Rect(pad, cy, inner_w, ctrl_h),
value=1.0 if on else 0.0,
extra={"label": label}))
cy += ctrl_h + gap
if self.page == "settings":
section(s["sec_capture"])
monitors = self.state.get("monitors") or []
if monitors:
choice("monitor", s.get("monitor", "Monitor"),
str(self.state.get("monitor", "0")), monitors)
section(s["sec_behaviour"])
toggle("open_on_start", s["open_on_start"],
bool(self.state.get("open_on_start")))
toggle("autostart", s.get("autostart", "Autostart with Windows"),
bool(self.state.get("autostart")))
section(s["sec_hotkeys"])
# The remapping fields. The captions on the buttons come from these
# same values, so a key change is visible across the whole menu at
# once.
field_h = self._u(CTRL_H)
for cmd, label in HOTKEY_ROWS:
items.append(Item("hotkey", cmd,
pygame.Rect(pad, cy, inner_w, field_h),
extra={"label": s.get(label, label),
"key": self.hotkeys.get(cmd, "—"),
"capturing": self.capturing == cmd}))
cy += field_h + self._u(6)
cy += gap
self._hint_rel = pygame.Rect(pad, cy, inner_w,
self._u(SMALL_SIZE) + self._u(6))
cy += self._hint_rel.h + gap
# The channel label: the header shows the version, the channel
# lives here (user rule 2026-09-08). A button item - the only
# non-interactive kind the drawer supports - with the label as
# its caption.
channel = self.state.get("channel") or ""
if channel:
section(s["sec_about"])
act_h = self._u(ACTION_H)
items.append(Item("button", "channel",
pygame.Rect(pad, cy, inner_w, act_h),
extra={"label": channel, "filled": False}))
cy += act_h + pad
else:
section(s["sec_processing"])
nr_on = bool(self.state.get("nr"))
hk_nr = self.hotkeys.get("toggle", "")
toggle("nr", f"{s['nr_on'] if nr_on else s['nr_off']} {hk_nr}".rstrip(),
nr_on)
choice("profile", s["profile"], str(self.state.get("profile", "")),
list(self.state.get("profiles") or []))
params = self.state.get("params") or {}
for key in PARAM_KEYS:
lo = SKIN_MIN if key == "skin_structure" else PARAM_MIN
val = float(params.get(key, 0.0))
slider(key, lo, PARAM_MAX, val, s[key], value_text=f"{val:.2f}")
section(s["sec_speed"])
# One slider, not a toggle plus a slider. The two used to be
# separate, and with the toggle off the slider still moved, still
# showed a changing resolution and changed the picture by exactly
# nothing - measured, bit for bit. A control that answers and does
# nothing is worse than no control.
cap = float(self.state.get("work_scale_cap", 1.0))
full = not bool(self.state.get("nr_small"))
# The extra step past the cap is "the whole screen". Below the cap
# every position is a different resolution; above it they would all
# be the same one, so there is exactly one position up there.
pos = cap + 0.05 if full else float(self.state.get("work_scale", cap))
if full:
shown = str(self.state.get("screen_size")
or self.stats.get("resolution") or "")
value_text = f"{shown} · {s['nr_res_full']}" if shown else s["nr_res_full"]
else:
value_text = str(self.state.get("work_size") or f"{pos:.2f}")
# The lower bound follows WORK_SCALE_MIN (0.1), not a hardcoded
# 0.30: a config value below the slider range would put the knob
# at the bottom while the label shows a different resolution.
lo = float(self.state.get("work_scale_min", 0.1))
slider("nr_res", lo, cap + 0.05, pos, s["nr_res"],
hint=s["nr_res_hint"], value_text=value_text)
section(s["sec_compare"])
split_val = float(self.state.get("split", 0.0))
slider("split", 0.0, 1.0, split_val, s["split"], hint=s["split_hint"],
value_text=(s.get("off", "off") if split_val <= 0.0
else f"{split_val:.2f}"))
section(s["sec_view"])
segmented("lang", s["language"], self.lang, ["en", "ru"],
["EN", "RU"])
segmented("theme", s["theme"], self.state.get("theme", "light"),
["light", "dark"], [s["theme_light"], s["theme_dark"]])
windows = self.state.get("windows") or []
if windows:
choice("window", s.get("window", "Window"),
str(self.state.get("window_current", "")), windows)
# The footer: actions with the hotkey printed underneath. "Collapse"
# and "Exit" used to look equally harmless, even though one hides the
# menu and the other unloads the program.
cy += self._u(6)
self._rule_rel = pygame.Rect(pad, cy, inner_w, 1)
cy += self._u(14)
act_h = self._u(ACTION_H)
if self.page == "settings":
items.append(Item("action", "back",
pygame.Rect(pad, cy, inner_w, act_h),
extra={"label": s["back"],
"filled": False}))
cy += act_h + pad
else:
row = [("screenshot", s["screenshot"], self.hotkeys.get("screenshot_menu", ""), False),
("record", s["record_stop"] if self.state.get("recording")
else s["record"], self.hotkeys.get("record", ""), True),
("collapse", s["collapse"], self.hotkeys.get("settings", ""), False)]
bgap = self._u(BTN_GAP)
bw = (inner_w - bgap * (len(row) - 1)) // len(row)
for idx, (key, label, hk, filled) in enumerate(row):
items.append(Item("action", key,
pygame.Rect(pad + idx * (bw + bgap), cy, bw, act_h),
extra={"label": label, "hotkey": hk,
"filled": filled}))
cy += act_h + self._u(16)
self._rule2_rel = pygame.Rect(pad, cy, inner_w, 1)
cy += self._u(14)
exit_h = self._u(EXIT_H)
items.append(Item("action", "exit",
pygame.Rect(pad, cy, inner_w, exit_h),
extra={"label": s["exit_full"],
"hotkey": self.hotkeys.get("quit", ""),
"note": s["exit_note"], "danger": True}))
cy += exit_h + pad
# The content height is known. The panel may be shorter - then the
# content scrolls: at 1080p a full panel took up almost the whole
# screen and there was no way around it.
content_h = cy
title_h = self._u(TITLE_H)
min_h = title_h + self._u(140)
# We never stretch past the content: empty space at the bottom looks
# broken, not spacious.
h = content_h if self.user_height is None else int(self.user_height)
h = max(min(h, content_h, max(0, screen_h - self._u(40))), min(min_h, content_h))
self.content_height = content_h
self._max_scroll = max(0, content_h - h)
self.scroll = min(max(self.scroll, 0), self._max_scroll)
# Offset from the centre plus a clamp, so the panel cannot be dragged
# entirely off the edge of the screen.
x = (screen_w - w) // 2 + self.offset[0]
y = (screen_h - h) // 2 + self.offset[1]
x = min(max(x, -w + self._u(80)), screen_w - self._u(80))
y = min(max(y, 0), max(0, screen_h - self._u(60)))
self.panel_rect = pygame.Rect(x, y, w, h)
self._title_bar = pygame.Rect(x, y, w, title_h)
grip = self._u(26)
self._grip = pygame.Rect(x + w - grip, y + h - grip, grip, grip)
# The bottom edge drags the height while the corner stays in charge of
# the scale - which is why the edge zone stops short of the corner.
edge = self._u(7)
self._edge = pygame.Rect(x, y + h - edge, max(0, w - grip), edge)
self._viewport = pygame.Rect(x, y + title_h, w, max(0, h - title_h))
# All the content lives shifted by the scroll; the title bar does not.
sy = y - self.scroll
self._stats_rect = self._stats_rel.move(x, sy)
self._gpu_rect = self._gpu_rel.move(x, sy)
self._hint_rect = self._hint_rel.move(x, sy)
self._rule_rect = self._rule_rel.move(x, sy)
self._rule2_rect = self._rule2_rel.move(x, sy)
self._section_rects = [(t, r.move(x, sy)) for t, r in self._sections]
if self._max_scroll > 0:
bar_w = max(2, self._u(3))
view_h = self._viewport.h
track = pygame.Rect(x + w - self._u(7) - bar_w,
y + title_h + self._u(4),
bar_w, max(1, view_h - self._u(8)))
thumb_h = max(self._u(26), int(track.h * view_h / content_h))
travel = track.h - thumb_h
ty = track.y + int(travel * (self.scroll / self._max_scroll))
self._scroll_track = track
self._scroll_thumb = pygame.Rect(track.x, ty, bar_w, thumb_h)
else:
self._scroll_track = pygame.Rect(0, 0, 0, 0)
self._scroll_thumb = pygame.Rect(0, 0, 0, 0)
for it in items:
# The header icons are pinned to the panel, not to the content:
# they sit above the scroll area and used to travel with it under
# the title bar.
it.rect = it.rect.move(x, y if it.kind == "icon" else sy)
if it.kind == "choice":
# The select field is computed here rather than at draw time:
# the layout of an expanded list is built before the first
# draw.
it.extra["strip"] = pygame.Rect(
it.rect.x, it.rect.y + label_h, it.rect.w, it.rect.h - label_h)
self.items = items
# The entries of the expanded list. They lie on top of the rows below,
# so they are added last and checked first on a mouse hit.
self.options: list[Item] = []
if self.open_choice:
src = next((i for i in items if i.key == self.open_choice), None)
if src is not None:
strip = src.extra.get("strip")
if strip is not None:
oh = self._u(CTRL_H) + self._u(6)
for idx, opt in enumerate(src.payload or []):
self.options.append(Item(
"option", src.key,
pygame.Rect(strip.x, strip.bottom + self._u(4) + idx * oh,
strip.w, oh),
payload=opt,
extra={"label": str(opt),
"selected": str(opt) == str(src.extra.get("current"))}))
# -- input -------------------------------------------------------------
def handle_event(self, event) -> list[tuple]:
"""Handle a pygame event. Returns a list of actions for main.
Actions: ("nr",), ("param", key, value), ("profile", name),
("lang", code), ("theme", name), ("button", key), ("drag", dx, dy).
This module changes only its own display state - everything else is
decided by main, which holds the source of truth.
"""
if not self.visible:
return []
out: list[tuple] = []
if self.capturing is not None and event.type == pygame.KEYDOWN:
# While we wait for a key the keyboard belongs to the field. Esc
# cancels, otherwise the menu would close instead of cancelling the
# assignment.
if event.key == pygame.K_ESCAPE:
self.capturing = None
out.append(("capture", None))
return out
text = key_text(event)
if text is None:
return out
cmd, self.capturing = self.capturing, None
out.append(("hotkey", cmd, text))
out.append(("capture", None))
return out
if event.type == pygame.MOUSEMOTION:
self._mouse = event.pos
if self._grip.collidepoint(event.pos):
self.hover = "grip"
elif self._edge.collidepoint(event.pos):
self.hover = "edge"
elif self._title_bar.collidepoint(event.pos):
self.hover = "title"
for it in self.items:
if it.kind == "icon" and it.rect.collidepoint(event.pos):
self.hover = f"icon:{it.key}"
break
else:
self.hover = None
for it in self.items:
if it.kind in ("action", "hotkey", "button") and \
it.rect.collidepoint(event.pos):
self.hover = f"{it.kind}:{it.key}"
break
if event.type == pygame.MOUSEWHEEL:
# Scroll only while the cursor is over the panel: otherwise the
# wheel inside the game would end up scrolling the menu. The
# cached position is refreshed on MOUSEMOTION; when the menu was
# just opened by a hotkey the cache may still be (0,0) - fall
# back to the real cursor position once.
if self._mouse == (0, 0):
try:
self._mouse = pygame.mouse.get_pos()
except Exception:
pass
if self._max_scroll > 0 and self.panel_rect.collidepoint(self._mouse):
self.scroll = min(max(self.scroll - event.y * self._u(48), 0),
self._max_scroll)
return out
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# The icons sit in the header, and the header is the drag handle,
# which returns immediately. So the icons are checked first.
for it in self.items:
if it.kind == "icon" and it.rect.collidepoint(event.pos):
out.extend(self._icon_click(it.key))
return out
if self._grip.collidepoint(event.pos):
self._resize_from = (event.pos, self.user_scale)
return out
if self._edge.collidepoint(event.pos):
# Dragging the height. If the height has never been set, take
# the current one - otherwise the very first pixel of the drag
# would collapse the panel.
base = self.user_height if self.user_height is not None \
else self.panel_rect.h
self._resize_h_from = (event.pos[1], int(base))
return out
if self._title_bar.collidepoint(event.pos):
self._move_from = (event.pos, tuple(self.offset))
self._capture_mouse(True)
return out
item = self.hit(event.pos)
if item is None:
self._drag_item = None
self.open_choice = None
return out
if item.kind == "action":
out.extend(self._action_click(item.key))
elif item.kind == "hotkey":
self.capturing = item.key
out.append(("capture", item.key))
elif item.kind == "segmented":
cells = item.extra.get("cells") or []
for idx, cr in enumerate(cells):
if cr.collidepoint(event.pos) and idx < len(item.payload or []):
out.extend(self._pick(item.key, str(item.payload[idx])))
break
elif item.kind == "toggle":
out.append(("nr",) if item.key == "nr" else ("toggle", item.key))
elif item.kind == "button":
out.append(("button", item.key))
elif item.kind == "option":
out.extend(self._pick(item.key, str(item.payload)))
self.open_choice = None
elif item.kind == "choice":
self.open_choice = None if self.open_choice == item.key else item.key
elif item.kind == "slider":
self._drag_item = item
out.extend(self._slide(item, event.pos[0]))
elif event.type == pygame.MOUSEMOTION and self._resize_h_from is not None:
start_y, base = self._resize_h_from
self.user_height = max(1, base + event.pos[1] - start_y)
elif event.type == pygame.MOUSEMOTION and self._move_from is not None:
start, base = self._move_from
self.offset = [base[0] + event.pos[0] - start[0],
base[1] + event.pos[1] - start[1]]
elif event.type == pygame.MOUSEMOTION and self._resize_from is not None:
start, base = self._resize_from
# Dragging right and down grows the panel. The step is chosen so
# that a pass across the screen diagonal gives roughly double the
# size.
delta = ((event.pos[0] - start[0]) + (event.pos[1] - start[1])) / 900.0
self.set_user_scale(base + delta)
elif event.type == pygame.MOUSEMOTION and getattr(self, "_drag_item", None):
if event.buttons and event.buttons[0]:
out.extend(self._slide(self._drag_item, event.pos[0]))
else:
self._drag_item = None
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self._drag_item = None
self._move_from = None
self._resize_from = None
self._capture_mouse(False)
if self._resize_h_from is not None:
self._resize_h_from = None
# The layout clamps the height by the content and the screen -
# we take the clamped value so nothing raw leaks into the
# config.
self.user_height = (None if self._max_scroll == 0
else self.panel_rect.h)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
out.append(("button", "close"))
return out
def _icon_click(self, key: str) -> list[tuple]:
"""The header: help, entering settings, returning from them."""
if key == "help":
return [("button", "github")]
if key == "gear":
self.page = "settings"
self.scroll = 0
self.capturing = None
return [("capture", None)]
if key == "close":
self.page = "main"
self.scroll = 0
self.capturing = None
return [("capture", None)]
return []
def _action_click(self, key: str) -> list[tuple]:
"""The footer. "Collapse" hides the menu, "Exit" unloads the program -
which is why they are different actions with different captions rather
than a single cross."""
if key == "back":
self.page = "main"
self.scroll = 0
self.capturing = None
return [("capture", None)]
if key == "collapse":
return [("button", "close")]
if key == "screenshot":
return [("button", "screenshot")]
return [("button", key)]
def _pick(self, key: str, value: str) -> list[tuple]:
"""A list entry was picked."""
if key == "profile":
return [("profile", value)]
if key == "lang":
return [("lang", value)]
if key == "theme":
self.state["theme"] = value
return [("theme", value)]
if key == "monitor":
return [("monitor", value)]
if key == "window":
return [("window", value)]
return []
def _slide(self, item: Item, mouse_x: int) -> list[tuple]:
"""The slider value from the mouse position, rounded to a 0.05 step."""
track = item.extra.get("track")
if track is None or track.w <= 0:
return []
frac = min(1.0, max(0.0, (mouse_x - track.x) / track.w))
value = item.lo + frac * (item.hi - item.lo)
value = round(round(value / 0.05) * 0.05, 2)
if abs(value - item.value) < 1e-9:
return []
item.value = value
if item.key == "split":
self.state["split"] = value
return [("split", value)]
if item.key == "nr_res":
cap = float(self.state.get("work_scale_cap", 1.0))
# Reflect the choice straight away so the label does not lag a
# frame behind the knob; main confirms it on the way back.
self.state["nr_small"] = value <= cap + 1e-6
if self.state["nr_small"]:
self.state["work_scale"] = value
# The label shows the work resolution; recompute it here so it
# follows the knob while dragging (main confirms on the way
# back). The formula mirrors _work_size in main.py.
try:
sw, sh = (int(x) for x in
str(self.state.get("screen_size", "0x0")).split("x"))
w = max(64, int(round(sw * value / 2) * 2))
h = max(64, int(round(sh * value / 2) * 2))
if w > 2560 or h > 1440:
k = min(2560 / w, 1440 / h)
w = max(64, int(round(w * k / 2) * 2))
h = max(64, int(round(h * k / 2) * 2))
self.state["work_size"] = f"{w}x{h}"
except Exception:
pass
return [("nr_res", value)]
params = dict(self.state.get("params") or {})
params[item.key] = value
self.state["params"] = params
return [("param", item.key, value)]
@property
def desired_cursor(self):
"""The cursor for the current zone. display sets it - it owns pygame."""
if self.hover == "grip" or self._resize_from is not None:
return pygame.SYSTEM_CURSOR_SIZENWSE
if self.hover == "edge" or self._resize_h_from is not None:
return pygame.SYSTEM_CURSOR_SIZENS
if isinstance(self.hover, str) and self.hover.startswith(
("icon:", "action:", "hotkey:", "button:")):
return pygame.SYSTEM_CURSOR_HAND
if self.hover == "title" or self._move_from is not None:
return pygame.SYSTEM_CURSOR_SIZEALL
return pygame.SYSTEM_CURSOR_ARROW
def hit(self, pos: tuple[int, int]) -> Item | None:
# Scrolled content is drawn clipped to _viewport, so hits outside it
# must not count either: a row that has travelled under the title bar
# is invisible, yet its rectangle still exists.
for it in self.items:
if it.kind == "icon" and it.rect.collidepoint(pos):
return it
if self._viewport.h > 0 and not self._viewport.collidepoint(pos):
return None
for opt in getattr(self, "options", []):
if opt.rect.collidepoint(pos):
return opt
for item in self.items:
if item.rect.collidepoint(pos):
return item
return None
def inside(self, pos: tuple[int, int]) -> bool:
return self.panel_rect.collidepoint(pos)
# -- drawing -----------------------------------------------------------
def draw(self, surface: pygame.Surface) -> None:
if not self.visible:
return
self.layout(surface.get_width(), surface.get_height())
s = STRINGS.get(self.lang, STRINGS["en"])
pad = self._u(PAD)
r = self.panel_rect
pygame.draw.rect(surface, _rgb(self.c["bg"]), r, border_radius=self._u(RADIUS))
pygame.draw.rect(surface, _rgb(self.c["border"]), r, self._u(1),
border_radius=self._u(RADIUS))
if self.hover == "title" or self._move_from is not None:
# The title bar is the drag handle. We highlight it with a strip
# and an accent edge: there is otherwise no way to guess it exists.
tb = self._title_bar
pygame.draw.rect(surface, _rgb(self.c["surface"]), tb,
border_top_left_radius=self._u(RADIUS),
border_top_right_radius=self._u(RADIUS))
pygame.draw.line(surface, _rgb(self.c["accent"]),
(tb.x + self._u(RADIUS), tb.bottom - 1),
(tb.right - self._u(RADIUS), tb.bottom - 1),
max(2, self._u(2)))
head = (s.get("settings_title", "Settings") if self.page == "settings"
else s["title"])
title = self._title_font.render(head, True, _rgb(self.c["text"]))
surface.blit(title, (r.x + pad, r.y + self._u(16)))
# The version right after the title: the top right corner is taken by
# the icons. The channel label lives in the settings page (user rule
# 2026-09-08).
ver = self.state.get("version") or ""
if ver:
ver_text = self._small_font.render(f"v{ver}", True,
_rgb(self.c["muted"]))
surface.blit(ver_text, (r.x + pad + title.get_width() + self._u(10),
r.y + self._u(22)))
# The content is drawn clipped to the scroll area, otherwise scrolled
# rows would spill outside the panel.
prev_clip = surface.get_clip()
surface.set_clip(self._viewport)
self._draw_stats(surface, s)
self._draw_gpu(surface, s)
self._draw_sections(surface)
self._draw_rules(surface, s)
# The resize corner: three short strokes, as resize handles usually go
g = self._grip
active = self.hover == "grip" or self._resize_from is not None
if active:
# A backing under the corner: three strokes on their own get lost
# against the panel and the zone is invisible until you poke it.
# NOT SRCALPHA: a translucent backing blends with the magenta
# background (CHROMA_KEY) -> colour != key -> the colour key does
# not cut it out -> a pink slab. An opaque backing in the panel
# colour is cut out along with the background, and the accent
# border stays.
pad = pygame.Surface(g.size)
pygame.draw.rect(pad, _rgb(self.c["bg"]), pad.get_rect(),
border_bottom_right_radius=self._u(RADIUS))
pygame.draw.rect(pad, _rgb(self.c["accent"]), pad.get_rect(),
self._u(1),
border_bottom_right_radius=self._u(RADIUS))
surface.blit(pad, g.topleft)
color = self.c["accent"] if active else self.c["muted"]
width = max(2, self._u(3 if active else 2))
step = max(3, self._u(6))
for i in range(1, 4):
off = i * step
pygame.draw.line(surface, _rgb(color),
(g.right - off, g.bottom - self._u(3)),
(g.right - self._u(3), g.bottom - off), width)
for item in self.items:
{"toggle": self._draw_toggle, "slider": self._draw_slider,
"choice": self._draw_choice, "button": self._draw_button,
"segmented": self._draw_segmented,
"action": self._draw_action,