-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyboard_test.py
More file actions
808 lines (710 loc) · 31.4 KB
/
Copy pathkeyboard_test.py
File metadata and controls
808 lines (710 loc) · 31.4 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
#!/usr/bin/env python3
"""
keyboard_test.py - Professional keyboard diagnostic mode for Keybr.py.
An in-terminal keyboard tester similar to commercial keyboard testing software:
- Full QWERTY + function row + nav cluster + numpad layout
- Key states: pressed (green), held (yellow), released (smooth fade back to gray)
- Modifier glow: Ctrl=red, Alt=blue, Shift=purple, Super=cyan (combined naturally)
- Currently-held keys panel with combination display
- Scrolling event history (last 50 events, with timestamps)
- Keyboard coverage tracker with "Keyboard Successfully Tested" completion
- Guided test mode (highlights the next key to press)
- Gaming mode (WASD / QER / 1-5 / modifiers / arrows, anti-ghosting focus)
- NKRO / anti-ghosting counters, repeat-rate and press-duration timing
- Scan-code info, layout detection, optional sound feedback
Terminal limitations (curses) - stated clearly so users are never misled:
- Key RELEASE events are not reported by a terminal; a key is treated as
released after a short silence (HOLD_TIMEOUT).
- CapsLock / Alt / Win / Menu / NumLock / PrtSc / ScrLk / Pause / media keys
produce no dependable terminal event, so they are excluded from the
coverage total (Alt and Caps shown in the layout as a visual reference).
- Shift is inferred from uppercase / shifted-symbol characters, Ctrl from
control characters (Ctrl+C / Ctrl+Z stay owned by the terminal's signal
handling).
- Sound uses the terminal bell.
Architecture: UI (drawing) is kept separate from logic (state tracking), so
the app can be unit-tested without a live curses screen.
"""
from __future__ import annotations
import curses
import os
import time
from datetime import datetime
from typing import Dict, List, Optional, Set, Tuple
# ─── Timing constants ────────────────────────────────────────────────────────
POLL_MS = 30 # frame interval (smooth animation / live panels)
HOLD_TIMEOUT = 0.35 # seconds of silence before a key counts as released
FADE_DURATION = 0.6 # seconds for the release fade animation
PRESS_HIGHLIGHT = 0.18 # seconds a key stays bright green before "held"
HISTORY_LIMIT = 50 # max recent events kept
# ─── Color pair IDs (kept > 8 so they never clash with Keybr.py's pairs) ─────
CP = {
"gray": 100, "press": 101, "held": 102, "fade1": 103, "fade2": 104,
"ctrl": 105, "alt": 106, "shift": 107, "super": 108,
"panel": 109, "title": 110, "dim": 111, "guide": 112, "ok": 113, "err": 114,
"gaming": 115,
}
# Keys that a plain terminal can never report reliably. Shown in the layout
# but not counted toward coverage (so "Keyboard Successfully Tested" stays
# achievable). Caps/Alt produce no dependable terminal event; Win/Menu/NumLock/
# PrtSc/ScrLk/Pause/media keys are not detectable through a terminal at all.
UNDETECTABLE = {"Win", "Menu", "NumLock", "PrtSc", "ScrLk", "Pause", "Caps", "Alt"}
# Modifier names -> their glow color role
MOD_ROLES = {"Ctrl": "ctrl", "Alt": "alt", "Shift": "shift", "Win": "super"}
# Gaming mode emphasizes these keys
GAMING_KEYS = {"W", "A", "S", "D", "Q", "E", "R", "1", "2", "3", "4", "5",
"Shift", "Ctrl", "Space", "Left", "Right", "Up", "Down"}
# Shifted symbols -> the unshifted key that produces them
SHIFTED_MAP = {
"!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7",
"*": "8", "(": "9", ")": "0", "_": "-", "+": "=", "~": "`",
"{": "[", "}": "]", "|": "\\", ":": ";", '"': "'", "<": ",", ">": ".",
"?": "/",
}
# Numpad characters that also light the numpad cluster
NUMPAD_CHARS = set("0123456789./*-+")
class KeySpec:
"""A single key in the drawn layout."""
__slots__ = ("name", "units", "label", "role")
def __init__(self, name: str, units: float = 1.0, label: Optional[str] = None,
role: Optional[str] = None):
self.name = name
self.units = units
self.label = label or name
self.role = role # "shift" | "ctrl" | "alt" | "super" | None
class KeyState:
"""Runtime state for one physical key."""
__slots__ = ("name", "press_ts", "release_ts", "first_press_ts")
def __init__(self, name: str):
self.name = name
self.press_ts: Optional[float] = None # last keydown event
self.release_ts: Optional[float] = None # when we declared it released
self.first_press_ts: Optional[float] = None # start of current hold
def _k(name: str, units: float = 1.0, label: Optional[str] = None,
role: Optional[str] = None) -> KeySpec:
return KeySpec(name, units, label, role)
def build_layout() -> List[List[KeySpec]]:
"""Return the layout rows. Each row is a list of KeySpecs."""
fn_row = [_k("Esc", 1.2)] + [_k("F%d" % i) for i in range(1, 13)] + [
_k("PrtSc", 1.3), _k("ScrLk", 1.3), _k("Pause", 1.3)]
main_rows = [
# Number row
[_k("`", label="`"), _k("1"), _k("2"), _k("3"), _k("4"), _k("5"),
_k("6"), _k("7"), _k("8"), _k("9"), _k("0"), _k("-"), _k("="),
_k("Backspace", 2.6, "Bksp")],
# Top letter row
[_k("Tab", 1.6), _k("Q"), _k("W"), _k("E"), _k("R"), _k("T"), _k("Y"),
_k("U"), _k("I"), _k("O"), _k("P"), _k("["), _k("]"), _k("\\", 1.4)],
# Home row
[_k("Caps", 2.0), _k("A"), _k("S"), _k("D"), _k("F"), _k("G"),
_k("H"), _k("J"), _k("K"), _k("L"), _k(";"), _k("'"),
_k("Enter", 2.6)],
# Bottom letter row
[_k("Shift", 2.6, role="shift"), _k("Z"), _k("X"), _k("C"), _k("V"),
_k("B"), _k("N"), _k("M"), _k(","), _k("."), _k("/"),
_k("Shift", 2.6, role="shift")],
# Modifier row
[_k("Ctrl", 1.7, role="ctrl"), _k("Win", 1.5, role="super"),
_k("Alt", 1.5, role="alt"), _k("Space", 6.5),
_k("Alt", 1.5, role="alt"), _k("Menu", 1.5, role="menu"),
_k("Ctrl", 1.7, role="ctrl")],
]
nav_row = [_k("Ins", label="Ins"), _k("Del"), _k("Home"), _k("End"),
_k("PgUp"), _k("PgDn")]
arrow_row = [_k("Up", 1.2, "Up"), _k("Left", 1.2, "Left"),
_k("Down", 1.2, "Down"), _k("Right", 1.2, "Right")]
numpad_rows = [
[_k("NumLock", 1.6), _k("/"), _k("*"), _k("-"), _k("+")],
[_k("7"), _k("8"), _k("9"), _k("4"), _k("5"), _k("6"),
_k("1"), _k("2"), _k("3"), _k("0"), _k(".")],
[_k("Enter", 2.0)],
]
return [fn_row] + main_rows + [nav_row, arrow_row] + numpad_rows
def all_specs() -> List[KeySpec]:
specs: List[KeySpec] = []
for row in build_layout():
specs.extend(row)
return specs
# Unique, coverage-counted key names (undetectable keys excluded).
def coverage_targets() -> Set[str]:
targets = set(s.name for s in all_specs()) - UNDETECTABLE
return targets
# Guided test order = layout order, skipping undetectable keys.
GUIDED_ORDER: List[str] = []
for row in build_layout():
for spec in row:
if spec.name not in UNDETECTABLE and spec.name not in GUIDED_ORDER:
GUIDED_ORDER.append(spec.name)
# ─── Curses keycode -> key name ───────────────────────────────────────────────
def code_to_key(code: int) -> Tuple[Optional[str], List[str]]:
"""Map a curses keycode to (key_name, active_modifiers).
Modifiers are *inferred* from the character actually received:
- Shift -> uppercase letters / shifted symbols (e.g. '!' from 1)
- Ctrl -> control characters (e.g. Ctrl+A produces 1)
Returns (None, []) for undetectable/unknown codes.
"""
if code == -1:
return None, []
# Printable characters (includes shift inference)
if 32 <= code <= 126:
ch = chr(code)
if ch in SHIFTED_MAP:
return SHIFTED_MAP[ch], ["Shift"] # shifted number/symbol
if ch == " ":
return "Space", [] # layout name for spacebar
if ch.isalpha():
return ch.upper(), (["Shift"] if ch.isupper() else [])
return ch, []
# Ctrl + letter (control characters). Ctrl+C/Z are handled by the
# terminal signal system and will not arrive here.
if 1 <= code <= 26 and code not in (8, 9, 10, 13, 27):
return chr(96 + code), ["Ctrl"]
# Control / special codes
if code == 9:
return "Tab", []
if code == getattr(curses, "KEY_BTAB", -2):
return "Tab", ["Shift"] # Shift+Tab
if code in (10, 13, getattr(curses, "KEY_ENTER", -2)):
return "Enter", []
if code == 27:
return "Esc", []
if code in (127, 8, getattr(curses, "KEY_BACKSPACE", -2)):
return "Backspace", []
keymap = {
getattr(curses, "KEY_UP", -1): "Up",
getattr(curses, "KEY_DOWN", -1): "Down",
getattr(curses, "KEY_LEFT", -1): "Left",
getattr(curses, "KEY_RIGHT", -1): "Right",
getattr(curses, "KEY_HOME", -1): "Home",
getattr(curses, "KEY_END", -1): "End",
getattr(curses, "KEY_PPAGE", -1): "PgUp",
getattr(curses, "KEY_NPAGE", -1): "PgDn",
getattr(curses, "KEY_IC", -1): "Ins",
getattr(curses, "KEY_DC", -1): "Del",
getattr(curses, "KEY_NUMLOCK", -1): "NumLock",
getattr(curses, "KEY_A1", -1): "Home",
getattr(curses, "KEY_A3", -1): "PgUp",
getattr(curses, "KEY_C1", -1): "PgDn",
getattr(curses, "KEY_C3", -1): "End",
getattr(curses, "KEY_B2", -1): "5",
}
if code in keymap:
return keymap[code], []
# Function keys F1..F12
for i in range(1, 13):
if code == getattr(curses, "KEY_F%d" % i, -1):
return "F%d" % i, []
return None, []
def detect_layout() -> str:
"""Attempt to detect the keyboard layout; state clearly if unavailable."""
lang = os.environ.get("LANG", "")
xkb = ""
try:
with open("/etc/default/keyboard", "r") as f:
for line in f:
if line.startswith("XKBLAYOUT="):
xkb = line.strip().split("=", 1)[1].strip('"')
break
except (OSError, IOError):
pass
if xkb:
return "Detected: %s (ISO/ANSI via xkb)" % xkb
if "en_US" in lang or lang.startswith("C."):
return "Detected: US / ANSI (from locale)"
if lang:
return "Possibly: %s" % lang
return "Unavailable (terminal)" # be honest when we cannot tell
# ─── The application ─────────────────────────────────────────────────────────
class KeyboardTestApp:
"""State machine + drawing for the keyboard diagnostic.
Logic methods never touch the screen, so they can be tested in isolation.
"""
def __init__(self, stdscr) -> None:
self.stdscr = stdscr
self.init_colors()
self.reset()
# ── State ────────────────────────────────────────────────────────────────
def reset(self) -> None:
self.mode = "free" # free | guided | gaming
self.sound = "off" # off | click | mech
self.states: Dict[str, KeyState] = {}
for spec in all_specs():
self.states.setdefault(spec.name, KeyState(spec.name))
self.covered: Set[str] = set()
self.held: Dict[str, float] = {} # name -> last keydown time
self.history: List[Tuple[str, str, str]] = [] # (time, name, event)
self.max_simul = 0
self.guided_idx = 0
self.guide_pulse = 0
self.repeats: Dict[str, List[float]] = {}
self.repeat_info: Optional[Dict] = None
self.last_release: Optional[Dict] = None # press-duration info
self.scan_info: Optional[Dict] = None # last key details
self.layout_name = detect_layout()
self.targets = coverage_targets()
def init_colors(self) -> None:
try:
curses.start_color()
curses.use_default_colors()
except curses.error:
pass
pairs = {
"gray": (curses.COLOR_WHITE, -1), "press": (curses.COLOR_GREEN, -1),
"held": (curses.COLOR_YELLOW, -1), "fade1": (curses.COLOR_GREEN, -1),
"fade2": (curses.COLOR_GREEN, -1), "ctrl": (curses.COLOR_RED, -1),
"alt": (curses.COLOR_BLUE, -1), "shift": (curses.COLOR_MAGENTA, -1),
"super": (curses.COLOR_CYAN, -1), "panel": (curses.COLOR_CYAN, -1),
"title": (curses.COLOR_WHITE, -1), "dim": (curses.COLOR_WHITE, -1),
"guide": (curses.COLOR_MAGENTA, -1), "ok": (curses.COLOR_GREEN, -1),
"err": (curses.COLOR_RED, -1), "gaming": (curses.COLOR_CYAN, -1),
}
for role, (fg, bg) in pairs.items():
try:
curses.init_pair(CP[role], fg, bg)
except curses.error:
pass
# ── Logic ────────────────────────────────────────────────────────────────
def _record_press(self, name: str, code: int, now: float) -> None:
st = self.states.get(name)
if st is None:
st = KeyState(name)
self.states[name] = st
was_held = name in self.held
st.press_ts = now
st.release_ts = None
if st.first_press_ts is None:
st.first_press_ts = now
if was_held:
# Auto-repeat of a held key -> feed the repeat-rate calculator
self.repeats.setdefault(name, []).append(now)
self._update_repeat_info(name, now)
else:
self.held[name] = now
self.covered.add(name)
self._push_history(name, "Pressed")
self.max_simul = max(self.max_simul, len(self.held))
# Scan-code info for the panel
unicode_ch = chr(code) if 32 <= code <= 126 else ""
self.scan_info = {
"name": name,
"code": code,
"unicode": unicode_ch,
"device": "Terminal (curses) - device info not available",
}
self._beep("press")
def _update_repeat_info(self, name: str, now: float) -> None:
lst = self.repeats.setdefault(name, [])
while lst and now - lst[0] > 1.0:
lst.pop(0)
if len(lst) >= 2:
span = lst[-1] - lst[0]
rate = (len(lst) - 1) / span if span > 0 else 0.0
delay = (lst[1] - lst[0]) * 1000.0
first = self.states[name].first_press_ts or now
self.repeat_info = {
"key": name, "rate": rate, "delay": delay,
"held_ms": (now - first) * 1000.0,
}
def _push_history(self, name: str, event: str) -> None:
ts = datetime.now().strftime("%H:%M:%S")
self.history.append((ts, name, event))
if len(self.history) > HISTORY_LIMIT:
self.history.pop(0)
def tick(self) -> None:
"""Advance time-dependent state: releases, fades, guided pulse."""
now = time.time()
# Detect releases: a key with no keydown events inside HOLD_TIMEOUT
for name in list(self.held.keys()):
if now - self.held[name] > HOLD_TIMEOUT:
st = self.states[name]
self.held.pop(name)
st.press_ts = now
st.release_ts = now
duration_ms = 0.0
if st.first_press_ts is not None:
duration_ms = (now - st.first_press_ts) * 1000.0
self.last_release = {"key": name, "duration_ms": duration_ms}
self._push_history(name, "Released")
self.guide_pulse = int(now * 2) % 2
def _active_mods(self) -> List[str]:
mods = []
for name in ("Ctrl", "Shift", "Alt", "Win"):
if name in self.held or (name in self.states and
self.states[name].release_ts is not None and
now_fresh(self.states[name].release_ts)):
mods.append(name)
return mods
def _beep(self, kind: str) -> None:
if self.sound == "off":
return
try:
if kind == "press":
self.stdscr.beep()
elif kind == "success":
for _ in range(2):
self.stdscr.beep()
elif kind == "failure":
self.stdscr.beep()
except (curses.error, AttributeError):
pass
def on_key(self, code: int) -> None:
"""Handle a keydown. Returns nothing."""
name, mods = code_to_key(code)
if name is None:
return
now = time.time()
if self.mode == "guided":
self._guided_check(name, now)
self._record_press(name, code, now)
# Also light the numpad cluster for digit/symbol keys
if 32 <= code <= 126:
ch = chr(code)
if ch in NUMPAD_CHARS and ch in self.states:
self._record_press(ch, code, now)
# Register inferred modifiers (Shift from shifted chars, Ctrl from
# control characters) so they light up and count toward coverage.
for mod in mods:
if mod in self.states:
self._record_press(mod, code, now)
def _guided_check(self, name: str, now: float) -> None:
if self.guided_idx >= len(GUIDED_ORDER):
return
expected = GUIDED_ORDER[self.guided_idx]
if name == expected:
self._push_history(expected, "Guide OK")
self.guided_idx += 1
if self.guided_idx >= len(GUIDED_ORDER):
self._beep("success")
else:
self._push_history(name + " (expected " + expected + ")", "Wrong")
self._beep("failure")
def coverage_count(self) -> Tuple[int, int]:
done = len([k for k in self.covered if k in self.targets])
return done, len(self.targets)
# ── Rendering helpers ────────────────────────────────────────────────────
def _attr(self, role: str, bold: bool = False) -> int:
attr = curses.color_pair(CP[role])
if bold:
attr |= curses.A_BOLD
return attr
def _key_color(self, name: str) -> Tuple[str, bool]:
"""Return (color_role, bold) for a key based on its state + modifiers."""
st = self.states.get(name)
now = time.time()
mods = self._active_mods()
mod_role = None
for m in ("Ctrl", "Shift", "Alt", "Win"):
if m in mods and MOD_ROLES.get(m):
mod_role = MOD_ROLES[m]
break
if st is not None and st.release_ts is not None:
age = now - st.release_ts
if age < FADE_DURATION:
frac = age / FADE_DURATION
if frac < 0.4:
return "fade1", True
if frac < 0.75:
return "fade2", False
# Fall through to default / modifier glow after fade
if name in MOD_ROLES and name in mods:
return MOD_ROLES[name], True
if name in self.held:
held_for = now - self.held[name]
if held_for < PRESS_HIGHLIGHT:
return "press", True
return "held", True
# Modifier glow while a modifier key is down
if name in MOD_ROLES and name in mods:
return MOD_ROLES[name], True
if mod_role and name not in ("Esc",):
# Letters/symbols tint by the active modifier (combine naturally)
if mod_role == "shift" and (name.isalpha() or name in SHIFTED_MAP.values()):
return "shift", True
if mod_role in ("ctrl", "alt", "super") and name.isalnum():
return mod_role, True
if self.mode == "gaming" and name in GAMING_KEYS:
return "gaming", True
if self.mode == "guided" and self.guided_idx < len(GUIDED_ORDER) \
and name == GUIDED_ORDER[self.guided_idx]:
role = "guide" if self.guide_pulse else "dim"
return role, True
return "gray", False
def _draw_chiclet(self, y: int, x: int, w: int, label: str,
role: str, bold: bool) -> None:
"""Draw a 2-line key box: top border + label row."""
if w < 3:
w = 3
inner = w - 2
lab = label
if len(lab) > inner:
lab = lab[:inner]
pad = (inner - len(lab)) // 2
attr = self._attr(role, bold)
try:
self.stdscr.addstr(y, x, "┌" + "─" * inner + "┐", attr)
self.stdscr.addstr(y + 1, x,
"│" + " " * pad + lab +
" " * (inner - pad - len(lab)) + "│", attr)
except curses.error:
pass
def _draw_key_row(self, y: int, row: List[KeySpec], w: int) -> int:
"""Draw a 2-line chiclet row, scaled to width. Returns next y."""
n = len(row)
if n == 0:
return y
# Pick the widest cell size (1..3 chars per unit) that still fits
best_cw = 1
for cw in (3, 2, 1):
total = sum(2 + int(cw * spec.units) for spec in row) + (n - 1)
if total <= w:
best_cw = cw
break
total_w = sum(2 + int(best_cw * spec.units) for spec in row) + (n - 1)
x = max(0, (w - total_w) // 2)
for i, spec in enumerate(row):
cw = 2 + int(best_cw * spec.units)
role, bold = self._key_color(spec.name)
self._draw_chiclet(y, x, cw, spec.label, role, bold)
x += cw + 1
return y + 2
def _draw_1line_key(self, y: int, x: int, label: str, role: str,
bold: bool) -> None:
try:
self.stdscr.addstr(y, x, "[" + label + "]",
self._attr(role, bold))
except curses.error:
pass
def _draw_1line_row(self, y: int, row: List[KeySpec], w: int,
max_width: int) -> int:
"""Draw compact one-line keys. Returns next y."""
total_w = sum(len("[" + s.label + "]") + 1 for s in row)
if total_w > w:
# Drop gaps to fit
total_w = sum(len("[" + s.label + "]") for s in row) + len(row) - 1
x = max(0, (w - total_w) // 2)
for spec in row:
role, bold = self._key_color(spec.name)
self._draw_1line_key(y, x, spec.label, role, bold)
x += len("[" + spec.label + "]") + 1
return y + 1
def _box(self, y: int, x: int, bw: int, title: str,
lines: List[str]) -> int:
"""Draw a titled box with lines. Returns next y."""
attr = self._attr("panel")
if bw < 4:
return y + 1
try:
t = (" %s " % title)[:bw - 2]
self.stdscr.addstr(y, x, "┌" + t + "─" * max(1, bw - 2 - len(t)) + "┐",
attr | curses.A_BOLD)
except curses.error:
pass
y += 1
for line in lines:
if len(line) > bw - 2:
line = line[:bw - 2]
try:
self.stdscr.addstr(y, x, "│" + line + " " * max(1, bw - 2 - len(line)) + "│",
attr)
except curses.error:
pass
y += 1
try:
self.stdscr.addstr(y, x, "└" + "─" * max(1, bw - 2) + "┘", attr)
except curses.error:
pass
return y + 1
# ── Main drawing ─────────────────────────────────────────────────────────
def draw(self) -> None:
stdscr = self.stdscr
stdscr.clear()
h, w = stdscr.getmaxyx()
# Title bar
title = "KEYBOARD DIAGNOSTIC"
mode_tag = {"free": "FREE", "guided": "GUIDED", "gaming": "GAMING"}[self.mode]
sound_tag = "SOUND:" + self.sound.upper()
head = " %s [%s] [%s] " % (title, mode_tag, sound_tag)
try:
stdscr.addstr(0, max(0, (w - len(head)) // 2), head,
self._attr("title", True))
except curses.error:
pass
# Coverage status strip
done, total = self.coverage_count()
if done >= total and total > 0:
status = "KEYBOARD SUCCESSFULLY TESTED!"
try:
stdscr.addstr(1, max(0, (w - len(status)) // 2), status,
self._attr("ok", True))
except curses.error:
pass
else:
pct = (done / total * 100) if total else 0
bar_w = min(24, max(4, w - 30))
filled = int(bar_w * pct / 100)
bar = "█" * filled + "░" * (bar_w - filled)
strip = "COVERAGE: [%s] %d/%d keys" % (bar, done, total)
try:
stdscr.addstr(1, max(0, (w - len(strip)) // 2), strip,
self._attr("dim"))
except curses.error:
pass
y = 3
rows = build_layout()
if h >= 4 + 2 * len(rows):
# Two-line chiclets for everything when there is room
for row in rows:
y = self._draw_key_row(y, row, w)
else:
# Compact fallback for very short windows
for row in rows:
y = self._draw_1line_row(y, row, w, 3)
y += 1
# Panels area
pan_top = y
pan_h = h - pan_top - 2
# Build panel content
held_lines, comb = self._held_panel()
hist_lines = self._history_panel(pan_h - 2)
info_lines = self._info_panel(pan_h - 2)
layout_lines = self._layout_panel()
ncols = 3 if w >= 96 else (2 if w >= 66 else 1)
col_w = (w - 4) // ncols if ncols > 1 else w - 2
if ncols == 3:
cols = [("CURRENTLY HELD", held_lines),
("HISTORY", hist_lines),
("DETAILS", info_lines)]
elif ncols == 2:
cols = [("CURRENTLY HELD", held_lines),
("HISTORY + DETAILS", hist_lines + info_lines)]
else:
cols = [("CURRENTLY HELD", held_lines),
("HISTORY", hist_lines),
("DETAILS", info_lines)]
yy = pan_top
if ncols == 1:
for title, lines in cols:
yy = self._box(yy, 1, col_w, title, lines[:max(1, pan_h - 2)])
yy += 1
else:
x = 1
for title, lines in cols:
self._box(pan_top, x, col_w, title, lines[:max(1, pan_h - 2)])
x += col_w + 2
yy = pan_top + pan_h
# Bottom control hint
hint = ("Ctrl+Q exit | Ctrl+F free | Ctrl+G guided | "
"Ctrl+B gaming | Ctrl+T sound | Layout: %s" % self.layout_name)
if len(hint) > w:
hint = hint[:w - 2]
try:
stdscr.addstr(h - 1, max(0, (w - len(hint)) // 2), hint,
self._attr("dim"))
except curses.error:
pass
if self.mode == "guided":
nxt = GUIDED_ORDER[self.guided_idx] if self.guided_idx < len(GUIDED_ORDER) else "DONE"
gline = "GUIDED MODE: press key -> %s" % nxt
try:
stdscr.addstr(h - 2, max(0, (w - len(gline)) // 2), gline,
self._attr("guide", True))
except curses.error:
pass
def _held_panel(self) -> Tuple[List[str], str]:
comb = " + ".join(self.held.keys()) or "None"
lines = [comb]
lines.append("Simultaneous: %d" % len(self.held))
lines.append("Max detected: %d" % self.max_simul)
return lines, comb
def _history_panel(self, max_lines: int) -> List[str]:
lines = []
for ts, name, event in self.history[-max_lines:][::-1]:
lines.append("%s %s %s" % (ts, name, event))
if not lines:
lines = ["(no events yet)"]
return lines
def _info_panel(self, max_lines: int) -> List[str]:
lines = []
if self.scan_info:
si = self.scan_info
lines.append("Key: %s" % si["name"])
lines.append("VK code: %d Unicode: %s" % (si["code"], si["unicode"] or "-"))
if self.last_release:
lr = self.last_release
lines.append("Hold: %s for %.0f ms" % (lr["key"], lr["duration_ms"]))
if self.repeat_info:
ri = self.repeat_info
lines.append("Repeat: %s %.1f Hz delay %.0f ms" %
(ri["key"], ri["rate"], ri["delay"]))
lines.append("Held %.0f ms" % ri["held_ms"])
lines.append("NKRO: terminal polling - motionless held keys may drop")
return lines
def _layout_panel(self) -> List[str]:
return ["Layout: " + self.layout_name,
"Keys not detectable via terminal:",
", ".join(sorted(UNDETECTABLE))]
# ── Main loop ────────────────────────────────────────────────────────────
def _has_activity(self) -> bool:
"""True if any key is held or still fading, so we must redraw."""
now = time.time()
if self.held:
return True
for st in self.states.values():
if st.release_ts is not None and now - st.release_ts < FADE_DURATION:
return True
return False
def loop(self) -> None:
stdscr = self.stdscr
stdscr.nodelay(False)
stdscr.timeout(POLL_MS)
try:
stdscr.keypad(True)
except curses.error:
pass
self._last_pulse = -1
self.draw()
while True:
self.tick()
redraw = self._has_activity()
if self.guide_pulse != self._last_pulse:
self._last_pulse = self.guide_pulse
redraw = True
if redraw:
self.draw()
key = stdscr.getch()
if key == -1:
continue
if key == 17: # Ctrl+Q -> back to menu
break
if key == 6: # Ctrl+F -> free mode
self.mode = "free"
self.draw()
continue
if key == 7: # Ctrl+G -> guided mode
self.mode = "guided"
self.guided_idx = 0
self.draw()
continue
if key == 2: # Ctrl+B -> gaming mode
self.mode = "gaming"
self.draw()
continue
if key == 20: # Ctrl+T -> cycle sound
self.sound = {"off": "click", "click": "mech",
"mech": "off"}[self.sound]
self.draw()
continue
self.on_key(key)
self.draw()
stdscr.timeout(-1)
def now_fresh(ts: Optional[float]) -> bool:
"""True if ts is within the fade window (used for modifier glow decay)."""
if ts is None:
return False
return time.time() - ts < FADE_DURATION
def run(stdscr) -> None:
"""Entry point used by Keybr.py. Runs until Ctrl+Q."""
app = KeyboardTestApp(stdscr)
app.loop()
if __name__ == "__main__":
curses.wrapper(run)