From 63dca2629035fa2d58b5e4025aa17f01a6a132e9 Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Tue, 1 Dec 2026 18:08:07 -0500 Subject: [PATCH] Announce confirmed keyboard lock state changes Track actual console lock flags and ordered XKB lock notifications so consumed keys stay silent and queued transitions are preserved. Refresh Num Lock routing and retain all lock changes in a console packet. Validated with the full Go race suite, go vet, golangci-lint, Python unit tests, translation and configuration checks, and full plus lock/Caps-specific private X11 fixtures. Audible speech and physical console acceptance remain pending. --- README.md | 2 + internal/app/commands.go | 30 +++++ internal/app/lock_announcements_test.go | 50 ++++++++ internal/console/lock_state_linux_test.go | 114 ++++++++++++++++++ internal/console/native_linux.go | 99 ++++++++++++++- internal/i18n/locale/de/LC_MESSAGES/fenrir.po | 51 ++++++-- internal/i18n/locale/es/LC_MESSAGES/fenrir.po | 46 +++++-- internal/i18n/locale/fenrir.pot | 40 ++++-- internal/i18n/locale/pl/LC_MESSAGES/fenrir.po | 50 ++++++-- internal/i18n/locale/pt/LC_MESSAGES/fenrir.po | 46 +++++-- internal/i18n/locale/ru/LC_MESSAGES/fenrir.po | 46 +++++-- internal/input/locks.go | 62 ++++++++++ internal/input/locks_test.go | 47 ++++++++ internal/input/router.go | 5 +- internal/terminal/keyboard_linux.go | 59 +++++++++ internal/terminal/locks_linux_test.go | 37 ++++++ internal/terminal/native.c | 53 +++++++- internal/terminal/native.h | 2 + internal/terminal/session_linux.go | 4 + tests/native_terminal.py | 49 ++++++++ 20 files changed, 825 insertions(+), 67 deletions(-) create mode 100644 internal/app/lock_announcements_test.go create mode 100644 internal/console/lock_state_linux_test.go create mode 100644 internal/input/locks.go create mode 100644 internal/input/locks_test.go create mode 100644 internal/terminal/locks_linux_test.go diff --git a/README.md b/README.md index 111c5b00..d380b2b1 100644 --- a/README.md +++ b/README.md @@ -425,6 +425,8 @@ export GOWORK=off go build -o /tmp/fenrir-test ./cmd/fenrir export FENRIR_TEST_BINARY=/tmp/fenrir-test xvfb-run -a env FENRIR_PRIVATE_X11=1 python3 -B tests/native_terminal.py +xvfb-run -a env FENRIR_PRIVATE_X11=1 FENRIR_LOCKS_TEST_ONLY=1 python3 -B tests/native_terminal.py +xvfb-run -a env FENRIR_PRIVATE_X11=1 FENRIR_CAPS_TEST_ONLY=1 python3 -B tests/native_terminal.py xvfb-run -a env FENRIR_PRIVATE_X11=1 python3 -B tests/native_hardware_settings.py xvfb-run -a env FENRIR_PRIVATE_X11=1 python3 -B tests/native_hardware_speech.py ``` diff --git a/internal/app/commands.go b/internal/app/commands.go index 57816bcf..5c2c977d 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -39,6 +39,10 @@ func (a *application) handleInput(decision input.Decision) { if a.quitting { return } + if decision.Lock != nil { + a.announceLock(*decision.Lock) + return + } diagnostic.Record("input decision", "command", decision.Command, "forward", decision.Forward, "interrupt", decision.Interrupt, "keypress", decision.Keypress, "typing", decision.Typing, "deletion", decision.Deletion, "ui_active", a.ui.active) @@ -89,6 +93,32 @@ func (a *application) handleInput(decision input.Decision) { a.handleCommand(decision.Command) } +// announceLock speaks a confirmed lock transition. The keyboard adapters send +// one only after observing the state change, never for the key press alone. +func (a *application) announceLock(change input.LockChange) { + var text string + switch change.Key { + case input.KeyCapsLock: + text = i18n.T("Caps Lock off") + if change.On { + text = i18n.T("Caps Lock on") + } + case input.KeyNumLock: + text = i18n.T("Num Lock off") + if change.On { + text = i18n.T("Num Lock on") + } + case input.KeyScrollLock: + text = i18n.T("Scroll Lock off") + if change.On { + text = i18n.T("Scroll Lock on") + } + default: + return + } + a.present(text, "") +} + func (a *application) handleCommand(id command.ID) { if a.overrideTransition && id != "" && id != command.Quit && id != command.Mute { a.voice.Say(i18n.T("Settings are busy")) diff --git a/internal/app/lock_announcements_test.go b/internal/app/lock_announcements_test.go new file mode 100644 index 00000000..f4f88fd5 --- /dev/null +++ b/internal/app/lock_announcements_test.go @@ -0,0 +1,50 @@ +// Fenrir console screen reader. +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package app + +import ( + "context" + "slices" + "testing" + + "git.stormux.org/storm/fenrir/internal/config" + "git.stormux.org/storm/fenrir/internal/input" +) + +func TestConfirmedLockChangesAreAnnounced(t *testing.T) { + settings := config.Defaults() + settings.Presentation.Sound.Enabled = false + voice := &fakeVoice{} + a, err := newApplication(context.Background(), &fakeSource{}, &fakeKeys{}, voice, RunOptions{Settings: settings}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(a.ui.close) + for _, change := range []input.LockChange{ + {Key: input.KeyCapsLock, On: true}, {Key: input.KeyCapsLock}, + {Key: input.KeyNumLock, On: true}, {Key: input.KeyNumLock}, + {Key: input.KeyScrollLock, On: true}, {Key: input.KeyScrollLock}, + {Key: input.KeyShift, On: true}, + } { + a.handleInput(input.Decision{Lock: &change}) + } + want := []string{"Caps Lock on", "Caps Lock off", "Num Lock on", "Num Lock off", "Scroll Lock on", "Scroll Lock off"} + if !slices.Equal(voice.messages, want) { + t.Fatalf("announcements = %q, want %q", voice.messages, want) + } +} diff --git a/internal/console/lock_state_linux_test.go b/internal/console/lock_state_linux_test.go new file mode 100644 index 00000000..adb973e9 --- /dev/null +++ b/internal/console/lock_state_linux_test.go @@ -0,0 +1,114 @@ +// Fenrir console screen reader. +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +//go:build linux && cgo + +package console + +import ( + "errors" + "slices" + "testing" + + "git.stormux.org/storm/fenrir/internal/input" +) + +func fakeLocks(t *testing.T, states ...uint8) { + t.Helper() + previous := readLocks + t.Cleanup(func() { readLocks = previous }) + readLocks = func() (uint8, error) { + if len(states) == 0 { + return 0, errors.New("unexpected lock query") + } + state := states[0] + states = states[1:] + return state, nil + } +} + +func TestNumLockPressRefreshesPassStateForQueuedKeys(t *testing.T) { + for _, test := range []struct { + name string + before, after uint8 + want bool + }{ + {"on", 0, input.LockNum, true}, + {"off", input.LockNum, 0, false}, + } { + fakeLocks(t, test.before, test.after) + device := &Device{} + numLock := !test.want // the stale value sampled before the pass + device.armLock(input.KeyNumLock, &numLock) + locks := device.resolveLocks(&numLock) + if numLock != test.want { + t.Errorf("%s: pass Num Lock = %v, want %v", test.name, numLock, test.want) + } + if !slices.Equal(locks, []input.LockChange{{Key: input.KeyNumLock, On: test.want}}) { + t.Errorf("%s: announcements = %+v", test.name, locks) + } + } +} + +func TestStaleNumLockIsCorrectedEvenWhenKeyDoesNotToggle(t *testing.T) { + // Application keypad mode consumes Num Lock; the real state still wins. + fakeLocks(t, input.LockNum, input.LockNum) + device := &Device{} + numLock := false + device.armLock(input.KeyNumLock, &numLock) + if lock := device.resolveLocks(&numLock); lock != nil { + t.Fatal("announced an unchanged lock", lock) + } + if !numLock { + t.Fatal("stale Num Lock kept") + } +} + +func TestLockQueryFailureKeepsStateAndStaysSilent(t *testing.T) { + fakeLocks(t) // every query fails + device := &Device{} + numLock := true + device.armLock(input.KeyNumLock, &numLock) + if lock := device.resolveLocks(&numLock); lock != nil || !numLock || len(device.lockKeys) != 0 { + t.Fatal("failed query changed state or announced", lock, numLock, device.lockKeys) + } +} + +func TestAllLockChangesInPacketAreReported(t *testing.T) { + fakeLocks(t, input.LockCaps, input.LockNum) + device := &Device{} + numLock := false + device.armLock(input.KeyCapsLock, &numLock) + device.armLock(input.KeyNumLock, &numLock) + want := []input.LockChange{{Key: input.KeyCapsLock}, {Key: input.KeyNumLock, On: true}} + if got := device.resolveLocks(&numLock); !slices.Equal(got, want) { + t.Fatalf("announcements = %+v, want %+v", got, want) + } + if !numLock || len(device.lockKeys) != 0 { + t.Fatal("packet state not refreshed", numLock, device.lockKeys) + } +} + +func TestLockResultQueryFailureDiscardsPacket(t *testing.T) { + fakeLocks(t, input.LockNum) // baseline succeeds, result query fails + device := &Device{} + numLock := true + device.armLock(input.KeyNumLock, &numLock) + if locks := device.resolveLocks(&numLock); len(locks) != 0 || !numLock || len(device.lockKeys) != 0 { + t.Fatal("failed result query changed state or retained packet", locks, numLock, device.lockKeys) + } +} diff --git a/internal/console/native_linux.go b/internal/console/native_linux.go index de9400ac..c38411b5 100644 --- a/internal/console/native_linux.go +++ b/internal/console/native_linux.go @@ -37,10 +37,20 @@ static int console_state(int fd, int *mode, unsigned char *leds) { return 0; } -static int toggle_caps_lock(int fd) { +static int toggle_caps_lock(int fd, unsigned char *after) { unsigned char leds; if (ioctl(fd, KDGKBLED, &leds) < 0) return -errno; if (ioctl(fd, KDSKBLED, (unsigned long)(leds ^ LED_CAP)) < 0) return -errno; + if (ioctl(fd, KDGKBLED, &leds) < 0) return -errno; + *after = leds & (LED_SCR | LED_NUM | LED_CAP); + return 0; +} + +// KDGKBLED reports the foreground console's lock flags, which drive typing, +// rather than KDGETLED's lights, which KDSETLED can override independently. +static int console_locks(int fd, unsigned char *leds) { + if (ioctl(fd, KDGKBLED, leds) < 0) return -errno; + *leds &= LED_SCR | LED_NUM | LED_CAP; return 0; } @@ -118,6 +128,10 @@ type Device struct { virtual *C.struct_libevdev_uinput grabbed bool syncing bool + // Lock keys forwarded in the current packet and the foreground console's + // lock flags sampled before the first of them reached the kernel. + lockKeys []uint16 + lockBefore uint8 } func openDevice(path string) (*Device, error) { @@ -177,6 +191,7 @@ func (d *Device) release(router *input.Router) error { errs = append(errs, d.forward(C.EV_SYN, C.SYN_REPORT, 0)) } router.Drop(d.fd) + d.lockKeys = nil if d.grabbed { errs = append(errs, kernelError(C.libevdev_grab(d.dev, C.LIBEVDEV_UNGRAB))) d.grabbed = false @@ -328,6 +343,8 @@ func (k *Keyboards) UpdateModifiers(fenrirKeys, scriptKeys []string) (bool, erro } func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) error { + // Shared by every device in this pass: lock state belongs to the console, + // and a Num Lock press refreshes it for the keys queued after it. if !textMode { for _, device := range k.devices { if device.grabbed { @@ -339,7 +356,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er k.router.Reset() } for path, device := range k.devices { - drained, err := k.drain(device, numLock, handle) + drained, err := k.drain(device, &numLock, handle) if errors.Is(err, syscall.ENODEV) || errors.Is(err, syscall.EIO) { _ = device.close(&k.router) // The device is already gone. delete(k.devices, path) @@ -368,7 +385,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er return kernelError(code) } device.syncing = true - ready, err := k.drain(device, numLock, handle) + ready, err := k.drain(device, &numLock, handle) if err != nil || !ready || device.held() { C.libevdev_grab(device.dev, C.LIBEVDEV_UNGRAB) if err != nil { @@ -388,7 +405,7 @@ func (k *Keyboards) Poll(textMode, numLock bool, handle func(input.Decision)) er return nil } -func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decision)) (bool, error) { +func (k *Keyboards) drain(device *Device, numLock *bool, handle func(input.Decision)) (bool, error) { // Bound each pass so busy input can't starve VT checks, speech, or quit. for count := 0; count < 256; count++ { var event C.struct_input_event @@ -408,7 +425,9 @@ func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decisi return false, kernelError(code) } if code == C.LIBEVDEV_READ_STATUS_SYNC && !device.syncing { + // Dropped events leave no reliable before/after pair for a lock. device.syncing = true + device.lockKeys = nil continue } if !device.grabbed { @@ -419,33 +438,101 @@ func (k *Keyboards) drain(device *Device, numLock bool, handle func(input.Decisi if event.value != 0 && !device.syncing && diagnostic.Enabled() { diagnostic.Timing("keyboard event age", time.UnixMicro(int64(C.input_event_time_us(&event)))) } - decision = k.router.Key(device.fd, uint16(event.code), int32(event.value), numLock, device.syncing) + decision = k.router.Key(device.fd, uint16(event.code), int32(event.value), *numLock, device.syncing) if err := k.uiText(uint16(event.code), decision); err != nil { return false, err } } + var locks []input.LockChange if decision.ToggleCapsLock { file, err := os.OpenFile("/dev/tty0", os.O_RDONLY|syscall.O_NOCTTY, 0) if err != nil { return false, err } - toggleErr := kernelError(C.toggle_caps_lock(C.int(file.Fd()))) + var after C.uchar + toggleErr := kernelError(C.toggle_caps_lock(C.int(file.Fd()), &after)) if err := errors.Join(toggleErr, file.Close()); err != nil { return false, err } + locks = append(locks, input.LockChange{Key: input.KeyCapsLock, On: uint8(after)&input.LockCaps != 0}) + } + if event._type == C.EV_KEY && event.value == 1 && decision.Forward && !device.syncing && input.LockBit(uint16(event.code)) != 0 { + device.armLock(uint16(event.code), numLock) } if decision.Forward { if err := device.forward(uint16(event._type), uint16(event.code), int32(event.value)); err != nil { return false, err } + if event._type == C.EV_SYN && event.code == C.SYN_REPORT { + locks = append(locks, device.resolveLocks(numLock)...) + } } if decision.Keypress || decision.Interrupt || decision.Command != "" || decision.UI != nil || decision.Released != 0 { handle(decision) } + for _, lock := range locks { + handle(input.Decision{Lock: &lock}) + } } return false, nil } +// readLocks is replaced in tests, which cannot open the foreground console. +var readLocks = consoleLocks + +func consoleLocks() (uint8, error) { + file, err := os.OpenFile("/dev/tty0", os.O_RDONLY|syscall.O_NOCTTY, 0) + if err != nil { + return 0, err + } + var leds C.uchar + queryErr := kernelError(C.console_locks(C.int(file.Fd()), &leds)) + return uint8(leds), errors.Join(queryErr, file.Close()) +} + +// armLock samples lock flags before a forwarded lock key press reaches the +// kernel. The input core applies key events at the following SYN_REPORT, so +// this sample cannot already include the press. It also refreshes the pass's +// Num Lock value, which was sampled before any queued key was read. +func (d *Device) armLock(key uint16, numLock *bool) { + if len(d.lockKeys) == 0 { + before, err := readLocks() + if err != nil { + // Without a baseline, silence is safer than guessing the state. + diagnostic.Record("lock state unavailable", "error", err) + return + } + d.lockBefore = before + *numLock = before&input.LockNum != 0 + } + d.lockKeys = append(d.lockKeys, key) +} + +// resolveLocks runs after the packet's SYN_REPORT was written to uinput. The +// kernel keyboard handler processes it synchronously, so the flags now show +// the result. Report only the pressed key's own lock, and only if it changed. +// Keys later in the same pass then route with the new Num Lock state. +func (d *Device) resolveLocks(numLock *bool) []input.LockChange { + if len(d.lockKeys) == 0 { + return nil + } + keys := d.lockKeys + d.lockKeys = nil + after, err := readLocks() + if err != nil { + diagnostic.Record("lock state unavailable", "error", err) + return nil + } + *numLock = after&input.LockNum != 0 + var locks []input.LockChange + for _, key := range keys { + if change, ok := input.ResolveLock(key, d.lockBefore, after); ok { + locks = append(locks, change) + } + } + return locks +} + func (d *Device) feedback() error { for count := 0; count < 64; count++ { var event C.struct_input_event diff --git a/internal/i18n/locale/de/LC_MESSAGES/fenrir.po b/internal/i18n/locale/de/LC_MESSAGES/fenrir.po index 266def55..f74a53fa 100644 --- a/internal/i18n/locale/de/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/de/LC_MESSAGES/fenrir.po @@ -474,6 +474,14 @@ msgstr "Kanu" msgid "Caps Lock" msgstr "Feststelltaste" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "Feststelltaste aus" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "Feststelltaste ein" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "Karotte" @@ -1174,7 +1182,7 @@ msgstr "Fenrir-Menü" msgid "Fenrir keys" msgstr "Fenrir-Tasten" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "Fenrir-Bildschirmleser Version {0}-{1}" @@ -1271,7 +1279,7 @@ msgstr "Fußabdrücke" msgid "Fortune Cookie" msgstr "Glückskeks" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "Nächste Taste durchreichen" @@ -2082,6 +2090,14 @@ msgstr "Benachrichtigungen" msgid "Num Lock" msgstr "Num-Taste" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "Num-Taste aus" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "Num-Taste ein" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "5 auf dem Ziffernblock" @@ -2403,7 +2419,13 @@ msgid "" "can be recorded. Press and release a modifier by itself to record it. " "Control+Enter finishes; Control+Escape cancels. Recording replaces the " "previous keys. Up to 64 keys can be recorded." -msgstr "Drücken Sie jede Taste, die die Sprachausgabe unterbrechen soll. Tab, Eingabe, Leertaste und Escape können aufgezeichnet werden. Drücken Sie eine Modifikatortaste einzeln und lassen Sie sie los, um sie aufzuzeichnen. Strg+Eingabe beendet die Aufzeichnung; Strg+Escape bricht ab. Die Aufzeichnung ersetzt die bisherigen Tasten. Bis zu 64 Tasten können aufgezeichnet werden." +msgstr "" +"Drücken Sie jede Taste, die die Sprachausgabe unterbrechen soll. Tab, " +"Eingabe, Leertaste und Escape können aufgezeichnet werden. Drücken Sie eine " +"Modifikatortaste einzeln und lassen Sie sie los, um sie aufzuzeichnen. " +"Strg+Eingabe beendet die Aufzeichnung; Strg+Escape bricht ab. Die " +"Aufzeichnung ersetzt die bisherigen Tasten. Bis zu 64 Tasten können " +"aufgezeichnet werden." #: screenreader-common/emoji/catalog.go msgid "Pretzel" @@ -2417,11 +2439,11 @@ msgstr "Druck" msgid "Printer" msgstr "Drucker" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "Fortschrittsüberwachung deaktiviert" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "Fortschrittsüberwachung aktiviert" @@ -2563,7 +2585,8 @@ msgstr "Liest vom oberen Bildschirmrand bis zur Cursorposition" #: screenreader-common/interruption msgid "Record at least one key, then press Control+Enter." -msgstr "Zeichnen Sie mindestens eine Taste auf und drücken Sie dann Strg+Eingabe." +msgstr "" +"Zeichnen Sie mindestens eine Taste auf und drücken Sie dann Strg+Eingabe." #: internal/preferences/interruption.go:50 msgid "Record interruption keys" @@ -2773,7 +2796,7 @@ msgstr "Skorpion" msgid "Screaming" msgstr "Schreiend" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "Skript fehlgeschlagen" @@ -2801,6 +2824,14 @@ msgstr "Schriftrolle" msgid "Scroll Lock" msgstr "Rollen" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "Rollen aus" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "Rollen ein" + #: screenreader-common/internalui msgid "Search cleared" msgstr "Suche gelöscht" @@ -2854,7 +2885,7 @@ msgid "Set window begin and end marks" msgstr "Setze Fensteranfangs- und -endmarken" #: internal/app/application_overrides.go:183 -#: internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "Einstellungen sind beschäftigt" @@ -4419,7 +4450,7 @@ msgstr "Sprache" msgid "speech and beeps" msgstr "Sprache und Signaltöne" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "Sprachausgabe eingeschaltet" @@ -4435,7 +4466,7 @@ msgstr "Tonhöhe" msgid "speech rate" msgstr "Sprechgeschwindigkeit" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "Sprachausgabe vorübergehend ausgeschaltet" diff --git a/internal/i18n/locale/es/LC_MESSAGES/fenrir.po b/internal/i18n/locale/es/LC_MESSAGES/fenrir.po index 4637b53f..0c4f97cf 100644 --- a/internal/i18n/locale/es/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/es/LC_MESSAGES/fenrir.po @@ -474,6 +474,14 @@ msgstr "Canoa" msgid "Caps Lock" msgstr "Bloq Mayús" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "Bloq Mayús desactivado" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "Bloq Mayús activado" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "Zanahoria" @@ -1177,7 +1185,7 @@ msgstr "Menú de Fenrir" msgid "Fenrir keys" msgstr "Teclas de Fenrir" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "Lector de pantalla Fenrir versión {0}-{1}" @@ -1274,7 +1282,7 @@ msgstr "Huellas de pies" msgid "Fortune Cookie" msgstr "Galleta de la fortuna" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "Enviar la siguiente tecla" @@ -2093,6 +2101,14 @@ msgstr "Notificaciones" msgid "Num Lock" msgstr "Bloqueo numérico" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "Bloqueo numérico desactivado" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "Bloqueo numérico activado" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "5 del teclado numérico" @@ -2412,7 +2428,11 @@ msgid "" "can be recorded. Press and release a modifier by itself to record it. " "Control+Enter finishes; Control+Escape cancels. Recording replaces the " "previous keys. Up to 64 keys can be recorded." -msgstr "Pulse cada tecla que deba interrumpir la voz. Se pueden registrar Tabulador, Intro, Espacio y Escape. Para registrar un modificador, púlselo y suéltelo por separado. Control+Intro finaliza; Control+Escape cancela. El registro sustituye las teclas anteriores. Se pueden registrar hasta 64 teclas." +msgstr "" +"Pulse cada tecla que deba interrumpir la voz. Se pueden registrar Tabulador, " +"Intro, Espacio y Escape. Para registrar un modificador, púlselo y suéltelo " +"por separado. Control+Intro finaliza; Control+Escape cancela. El registro " +"sustituye las teclas anteriores. Se pueden registrar hasta 64 teclas." #: screenreader-common/emoji/catalog.go msgid "Pretzel" @@ -2426,11 +2446,11 @@ msgstr "Imprimir pantalla" msgid "Printer" msgstr "Impresora" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "Seguimiento del progreso desactivado" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "Seguimiento del progreso activado" @@ -2782,7 +2802,7 @@ msgstr "Escorpión" msgid "Screaming" msgstr "Gritando" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "El script falló" @@ -2810,6 +2830,14 @@ msgstr "Pergamino" msgid "Scroll Lock" msgstr "Bloqueo de desplazamiento" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "Bloqueo de desplazamiento desactivado" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "Bloqueo de desplazamiento activado" + #: screenreader-common/internalui msgid "Search cleared" msgstr "Búsqueda borrada" @@ -2863,7 +2891,7 @@ msgid "Set window begin and end marks" msgstr "Establece una marca de principio y otra para el final de la ventana" #: internal/app/application_overrides.go:183 -#: internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "La configuración está ocupada" @@ -4427,7 +4455,7 @@ msgstr "voz" msgid "speech and beeps" msgstr "voz y pitidos" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "Habla activada" @@ -4443,7 +4471,7 @@ msgstr "tono de voz" msgid "speech rate" msgstr "velocidad de voz" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "Habla desactivada temporalmente" diff --git a/internal/i18n/locale/fenrir.pot b/internal/i18n/locale/fenrir.pot index 737509e3..c9f78a74 100644 --- a/internal/i18n/locale/fenrir.pot +++ b/internal/i18n/locale/fenrir.pot @@ -461,6 +461,14 @@ msgstr "" msgid "Caps Lock" msgstr "" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "" @@ -1141,7 +1149,7 @@ msgstr "" msgid "Fenrir keys" msgstr "" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "" @@ -1237,7 +1245,7 @@ msgstr "" msgid "Fortune Cookie" msgstr "" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "" @@ -2041,6 +2049,14 @@ msgstr "" msgid "Num Lock" msgstr "" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "" @@ -2369,11 +2385,11 @@ msgstr "" msgid "Printer" msgstr "" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "" @@ -2725,7 +2741,7 @@ msgstr "" msgid "Screaming" msgstr "" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "" @@ -2753,6 +2769,14 @@ msgstr "" msgid "Scroll Lock" msgstr "" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "" + #: screenreader-common/internalui msgid "Search cleared" msgstr "" @@ -2805,7 +2829,7 @@ msgstr "" msgid "Set window begin and end marks" msgstr "" -#: internal/app/application_overrides.go:183 internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:183 internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "" @@ -4301,7 +4325,7 @@ msgstr "" msgid "speech and beeps" msgstr "" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "" @@ -4317,7 +4341,7 @@ msgstr "" msgid "speech rate" msgstr "" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "" diff --git a/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po b/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po index 84adc7cd..7df9e0d6 100644 --- a/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/pl/LC_MESSAGES/fenrir.po @@ -475,6 +475,14 @@ msgstr "kajak" msgid "Caps Lock" msgstr "Caps Lock" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "Caps Lock wyłączony" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "Caps Lock włączony" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "Marchew" @@ -1176,7 +1184,7 @@ msgstr "Menu Fenrira" msgid "Fenrir keys" msgstr "Klawisze Fenrira" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "Czytnik ekranu Fenrir, wersja {0}-{1}" @@ -1273,7 +1281,7 @@ msgstr "ślady stóp" msgid "Fortune Cookie" msgstr "ciastko z wróżbą" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "Przepuść następny klawisz" @@ -2087,6 +2095,14 @@ msgstr "Powiadomienia" msgid "Num Lock" msgstr "Num Lock" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "Num Lock wyłączony" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "Num Lock włączony" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "5 na klawiaturze numerycznej" @@ -2406,7 +2422,12 @@ msgid "" "can be recorded. Press and release a modifier by itself to record it. " "Control+Enter finishes; Control+Escape cancels. Recording replaces the " "previous keys. Up to 64 keys can be recorded." -msgstr "Naciśnij każdy klawisz, który ma przerywać mowę. Można zarejestrować Tab, Enter, Spację i Escape. Aby zarejestrować modyfikator, naciśnij i zwolnij go osobno. Control+Enter kończy rejestrowanie; Control+Escape anuluje. Rejestrowanie zastępuje poprzednie klawisze. Można zarejestrować do 64 klawiszy." +msgstr "" +"Naciśnij każdy klawisz, który ma przerywać mowę. Można zarejestrować Tab, " +"Enter, Spację i Escape. Aby zarejestrować modyfikator, naciśnij i zwolnij go " +"osobno. Control+Enter kończy rejestrowanie; Control+Escape anuluje. " +"Rejestrowanie zastępuje poprzednie klawisze. Można zarejestrować do 64 " +"klawiszy." #: screenreader-common/emoji/catalog.go msgid "Pretzel" @@ -2420,11 +2441,11 @@ msgstr "Print Screen" msgid "Printer" msgstr "Drukarka" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "Monitorowanie postępu wyłączone" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "Monitorowanie postępu włączone" @@ -2566,7 +2587,8 @@ msgstr "Czyta od góry ekranu do pozycji kursora." #: screenreader-common/interruption msgid "Record at least one key, then press Control+Enter." -msgstr "Zarejestruj co najmniej jeden klawisz, a następnie naciśnij Control+Enter." +msgstr "" +"Zarejestruj co najmniej jeden klawisz, a następnie naciśnij Control+Enter." #: internal/preferences/interruption.go:50 msgid "Record interruption keys" @@ -2776,7 +2798,7 @@ msgstr "brązowy skorpion" msgid "Screaming" msgstr "Krzyk" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "Skrypt nie powiódł się" @@ -2804,6 +2826,14 @@ msgstr "Zwój" msgid "Scroll Lock" msgstr "Scroll Lock" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "Scroll Lock wyłączony" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "Scroll Lock włączony" + #: screenreader-common/internalui msgid "Search cleared" msgstr "Wyszukiwanie wyczyszczone" @@ -2857,7 +2887,7 @@ msgid "Set window begin and end marks" msgstr "Ustaw początek i koniec okna." #: internal/app/application_overrides.go:183 -#: internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "Ustawienia są zajęte" @@ -4418,7 +4448,7 @@ msgstr "mowa" msgid "speech and beeps" msgstr "mowa i sygnały" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "Mowa włączona." @@ -4434,7 +4464,7 @@ msgstr "wysokość głosu" msgid "speech rate" msgstr "szybkość mowy" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "Mowa tymczasowo wyłączona." diff --git a/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po b/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po index a21b83c1..4391e545 100644 --- a/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/pt/LC_MESSAGES/fenrir.po @@ -473,6 +473,14 @@ msgstr "Canoa" msgid "Caps Lock" msgstr "Caps Lock" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "Caps Lock desativado" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "Caps Lock ativado" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "Cenoura" @@ -1176,7 +1184,7 @@ msgstr "Menu do Fenrir" msgid "Fenrir keys" msgstr "Teclas do Fenrir" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "Leitor de tela Fenrir versão {0}-{1}" @@ -1273,7 +1281,7 @@ msgstr "Pegadas" msgid "Fortune Cookie" msgstr "Biscoito da sorte" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "Avançar próxima tecla pressionada" @@ -2090,6 +2098,14 @@ msgstr "Notificações" msgid "Num Lock" msgstr "Num Lock" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "Num Lock desativado" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "Num Lock ativado" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "5 do teclado numérico" @@ -2410,7 +2426,11 @@ msgid "" "can be recorded. Press and release a modifier by itself to record it. " "Control+Enter finishes; Control+Escape cancels. Recording replaces the " "previous keys. Up to 64 keys can be recorded." -msgstr "Pressione cada tecla que deve interromper a fala. Tab, Enter, Espaço e Escape podem ser registradas. Para registrar um modificador, pressione e solte a tecla sozinha. Control+Enter conclui; Control+Escape cancela. O registro substitui as teclas anteriores. Até 64 teclas podem ser registradas." +msgstr "" +"Pressione cada tecla que deve interromper a fala. Tab, Enter, Espaço e " +"Escape podem ser registradas. Para registrar um modificador, pressione e " +"solte a tecla sozinha. Control+Enter conclui; Control+Escape cancela. O " +"registro substitui as teclas anteriores. Até 64 teclas podem ser registradas." #: screenreader-common/emoji/catalog.go msgid "Pretzel" @@ -2424,11 +2444,11 @@ msgstr "Print Screen" msgid "Printer" msgstr "Impressora" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "Monitoramento de progresso desativado" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "Monitoramento de progresso ativado" @@ -2780,7 +2800,7 @@ msgstr "Escorpião" msgid "Screaming" msgstr "Gritando" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "O script falhou" @@ -2808,6 +2828,14 @@ msgstr "Pergaminho" msgid "Scroll Lock" msgstr "Scroll Lock" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "Scroll Lock desativado" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "Scroll Lock ativado" + #: screenreader-common/internalui msgid "Search cleared" msgstr "Pesquisa limpa" @@ -2861,7 +2889,7 @@ msgid "Set window begin and end marks" msgstr "Definir marcas de início e fim da janela" #: internal/app/application_overrides.go:183 -#: internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "As configurações estão ocupadas" @@ -4431,7 +4459,7 @@ msgstr "fala" msgid "speech and beeps" msgstr "fala e sinais sonoros" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "fala ativada" @@ -4447,7 +4475,7 @@ msgstr "tom da fala" msgid "speech rate" msgstr "velocidade da fala" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "fala temporariamente desativada" diff --git a/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po b/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po index 2cc8f0eb..b0b7ac74 100644 --- a/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po +++ b/internal/i18n/locale/ru/LC_MESSAGES/fenrir.po @@ -472,6 +472,14 @@ msgstr "Каноэ" msgid "Caps Lock" msgstr "Caps Lock" +#: internal/app/commands.go:102 +msgid "Caps Lock off" +msgstr "Caps Lock выключен" + +#: internal/app/commands.go:104 +msgid "Caps Lock on" +msgstr "Caps Lock включён" + #: screenreader-common/emoji/catalog.go msgid "Carrot" msgstr "Морковь" @@ -1172,7 +1180,7 @@ msgstr "Меню Fenrir" msgid "Fenrir keys" msgstr "Клавиши Fenrir" -#: internal/app/commands.go:112 +#: internal/app/commands.go:142 msgid "Fenrir screen reader version {0}-{1}" msgstr "Программа экранного доступа Fenrir, версия {0}-{1}" @@ -1269,7 +1277,7 @@ msgstr "Следы" msgid "Fortune Cookie" msgstr "Печенье с предсказанием" -#: internal/app/commands.go:157 +#: internal/app/commands.go:187 msgid "Forward next keypress" msgstr "Переслать следующую клавишу." @@ -2082,6 +2090,14 @@ msgstr "Уведомления" msgid "Num Lock" msgstr "Num Lock" +#: internal/app/commands.go:107 +msgid "Num Lock off" +msgstr "Num Lock выключен" + +#: internal/app/commands.go:109 +msgid "Num Lock on" +msgstr "Num Lock включён" + #: screenreader-common/interruption msgid "Numpad 5" msgstr "5 на цифровой клавиатуре" @@ -2402,7 +2418,11 @@ msgid "" "can be recorded. Press and release a modifier by itself to record it. " "Control+Enter finishes; Control+Escape cancels. Recording replaces the " "previous keys. Up to 64 keys can be recorded." -msgstr "Нажмите каждую клавишу, которая должна прерывать речь. Можно записать Tab, Enter, Пробел и Escape. Чтобы записать модификатор, нажмите и отпустите его отдельно. Control+Enter завершает запись; Control+Escape отменяет. Запись заменяет предыдущие клавиши. Можно записать до 64 клавиш." +msgstr "" +"Нажмите каждую клавишу, которая должна прерывать речь. Можно записать Tab, " +"Enter, Пробел и Escape. Чтобы записать модификатор, нажмите и отпустите его " +"отдельно. Control+Enter завершает запись; Control+Escape отменяет. Запись " +"заменяет предыдущие клавиши. Можно записать до 64 клавиш." #: screenreader-common/emoji/catalog.go msgid "Pretzel" @@ -2416,11 +2436,11 @@ msgstr "Print Screen" msgid "Printer" msgstr "Принтер" -#: internal/app/commands.go:143 +#: internal/app/commands.go:173 msgid "Progress monitoring disabled" msgstr "Отслеживание хода выполнения отключено" -#: internal/app/commands.go:141 +#: internal/app/commands.go:171 msgid "Progress monitoring enabled" msgstr "Отслеживание хода выполнения включено" @@ -2772,7 +2792,7 @@ msgstr "Скорпион" msgid "Screaming" msgstr "Крик" -#: internal/app/commands.go:168 internal/app/scripts.go +#: internal/app/commands.go:198 internal/app/scripts.go msgid "Script failed" msgstr "Ошибка сценария" @@ -2800,6 +2820,14 @@ msgstr "Свиток" msgid "Scroll Lock" msgstr "Scroll Lock" +#: internal/app/commands.go:112 +msgid "Scroll Lock off" +msgstr "Scroll Lock выключен" + +#: internal/app/commands.go:114 +msgid "Scroll Lock on" +msgstr "Scroll Lock включён" + #: screenreader-common/internalui msgid "Search cleared" msgstr "Поиск очищен" @@ -2853,7 +2881,7 @@ msgid "Set window begin and end marks" msgstr "Установка начала и конца окна" #: internal/app/application_overrides.go:183 -#: internal/app/application_overrides.go:356 internal/app/commands.go:94 +#: internal/app/application_overrides.go:356 internal/app/commands.go:124 msgid "Settings are busy" msgstr "Настройки заняты" @@ -4415,7 +4443,7 @@ msgstr "речь" msgid "speech and beeps" msgstr "речь и звуковые сигналы" -#: internal/app/commands.go:71 internal/app/feedback.go:45 +#: internal/app/commands.go:75 internal/app/feedback.go:45 msgid "speech enabled" msgstr "Речь включена" @@ -4431,7 +4459,7 @@ msgstr "высота голоса" msgid "speech rate" msgstr "скорость речи" -#: internal/app/commands.go:152 +#: internal/app/commands.go:182 msgid "speech temporary disabled" msgstr "Речь временно отключена" diff --git a/internal/input/locks.go b/internal/input/locks.go new file mode 100644 index 00000000..eb2535fd --- /dev/null +++ b/internal/input/locks.go @@ -0,0 +1,62 @@ +// Fenrir console screen reader. +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package input + +const ( + KeyNumLock = 69 + KeyScrollLock = 70 +) + +// Lock state bits use the kernel's KDGKBLED layout so console state needs no +// translation. X11 adapters convert their modifier masks to the same bits. +const ( + LockScroll uint8 = 1 << iota + LockNum + LockCaps +) + +// LockChange is an observed lock transition caused by a lock key press. +type LockChange struct { + Key uint16 + On bool +} + +// LockBit returns the state bit a lock key controls, or zero for other keys. +func LockBit(key uint16) uint8 { + switch key { + case KeyCapsLock: + return LockCaps + case KeyNumLock: + return LockNum + case KeyScrollLock: + return LockScroll + } + return 0 +} + +// ResolveLock reports a change only when the pressed key's own lock differs +// between the state sampled before the press and the state after it. Keys +// the system consumed without toggling, such as Num Lock in application +// keypad mode, and lock changes caused by anything else are not reported. +func ResolveLock(key uint16, before, after uint8) (LockChange, bool) { + bit := LockBit(key) + if bit == 0 || before&bit == after&bit { + return LockChange{}, false + } + return LockChange{Key: key, On: after&bit != 0}, true +} diff --git a/internal/input/locks_test.go b/internal/input/locks_test.go new file mode 100644 index 00000000..8d8d94ba --- /dev/null +++ b/internal/input/locks_test.go @@ -0,0 +1,47 @@ +// Fenrir console screen reader. +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later +// +// This program is free software: you can redistribute it and/or modify it +// under the terms of the GNU General Public License as published by the Free +// Software Foundation, either version 3 of the License, or (at your option) +// any later version. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +// more details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . + +package input + +import "testing" + +func TestResolveLockReportsOnlyThePressedKeysChange(t *testing.T) { + for _, test := range []struct { + name string + key uint16 + before, after uint8 + want LockChange + changed bool + }{ + {"caps on", KeyCapsLock, 0, LockCaps, LockChange{KeyCapsLock, true}, true}, + {"caps off", KeyCapsLock, LockCaps | LockNum, LockNum, LockChange{KeyCapsLock, false}, true}, + {"num on", KeyNumLock, LockCaps, LockCaps | LockNum, LockChange{KeyNumLock, true}, true}, + {"num off", KeyNumLock, LockNum, 0, LockChange{KeyNumLock, false}, true}, + {"scroll on", KeyScrollLock, 0, LockScroll, LockChange{KeyScrollLock, true}, true}, + {"scroll off", KeyScrollLock, LockScroll, 0, LockChange{KeyScrollLock, false}, true}, + // Application keypad mode consumes Num Lock without toggling it. + {"num unchanged", KeyNumLock, LockNum, LockNum, LockChange{}, false}, + // Another lock changing is not attributed to the pressed key. + {"other lock changed", KeyNumLock, 0, LockCaps, LockChange{}, false}, + {"not a lock key", KeyShift, 0, LockCaps, LockChange{}, false}, + } { + got, changed := ResolveLock(test.key, test.before, test.after) + if got != test.want || changed != test.changed { + t.Errorf("%s: got %+v %v, want %+v %v", test.name, got, changed, test.want, test.changed) + } + } +} diff --git a/internal/input/router.go b/internal/input/router.go index 665b580d..21dce923 100644 --- a/internal/input/router.go +++ b/internal/input/router.go @@ -79,8 +79,9 @@ type Decision struct { WordBoundary bool // a forwarded Space, rather than cursor navigation Command command.ID UI *internalui.Key - Learn *LearnKey // captured physical press and its inactive command - Released uint16 // physical key released while the UI owned it + Learn *LearnKey // captured physical press and its inactive command + Released uint16 // physical key released while the UI owned it + Lock *LockChange // confirmed lock transition, sent as its own decision } type Router struct { diff --git a/internal/terminal/keyboard_linux.go b/internal/terminal/keyboard_linux.go index aa8e9ec3..141097d6 100644 --- a/internal/terminal/keyboard_linux.go +++ b/internal/terminal/keyboard_linux.go @@ -38,6 +38,11 @@ func (s *Session) Keyboard() *Keyboard { return &Keyboard{session: s} } type Keyboard struct{ session *Session } +type lockPress struct { + key uint16 + before uint8 +} + func (k *Keyboard) Events() <-chan error { return k.session.inputEvents } func (k *Keyboard) Scan() error { return nil } func (k *Keyboard) PassNext() { k.session.router.PassNext() } @@ -120,6 +125,7 @@ func (s *Session) captureKeyboard() (int, error) { s.router.Capture(captured) clear(s.held) clear(s.replayed) + clear(s.lockPending) s.grabbed = false s.captureBlocked = true return int(status), nil @@ -142,6 +148,14 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error if err := nativeError(code); err != nil { return fmt.Errorf("X11 terminal input: %w", err) } + if event._type == 2 { + if active && !s.captureBlocked { + if lock := s.observeLockEvent(int(event.keycode), uint8(event.state)); lock != nil { + handle(input.Decision{Lock: lock}) + } + } + continue + } if event._type != 1 { continue } @@ -153,6 +167,7 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error } if !active { C.terminal_x_release(s.x) + clear(s.lockPending) continue } // ReplayKeyboard redelivers a forwarded press to normal event @@ -160,6 +175,10 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error if event.value == 1 && s.lastReplay.code == int(event.keycode) && s.lastReplay.time == uint64(event.time) { continue } + // Route each queued key using its own modifier state, rather than the + // server's possibly newer state sampled at the beginning of this pass. + bits := uint8(C.terminal_x_lock_bits(s.x, event.state)) + numLock = bits&input.LockNum != 0 key := uint16(C.terminal_key_code(event.symbol, event.keycode)) if held, exists := s.held[int(event.keycode)]; exists { key = held @@ -205,10 +224,23 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error s.capsConsumed = false } } + var lock *input.LockChange if decision.ToggleCapsLock { if err := nativeError(C.terminal_x_toggle_caps(s.x)); err != nil { return err } + if after, ok := s.locks(); ok { + lock = &input.LockChange{Key: input.KeyCapsLock, On: after&input.LockCaps != 0} + } + } + if value == 1 { + delete(s.lockPending, int(event.keycode)) + if decision.Forward && input.LockBit(key) != 0 { + if s.lockPending == nil { + s.lockPending = make(map[int]lockPress) + } + s.lockPending[int(event.keycode)] = lockPress{key: key, before: bits} + } } // Acquire before dispatch: a failed capture must not execute a command // or open a form from a partial, stale chord. @@ -229,6 +261,9 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error } } handle(decision) + if lock != nil { + handle(input.Decision{Lock: lock}) + } if event.value == 1 { if decision.Forward && !s.grabbed { C.terminal_x_replay(s.x, event.time) @@ -256,3 +291,27 @@ func (k *Keyboard) Poll(active, numLock bool, handle func(input.Decision)) error } return s.relayInput() } + +func (s *Session) locks() (uint8, bool) { + var bits C.int + if err := nativeError(C.terminal_x_locks(s.x, &bits)); err != nil { + // Without the server's state, silence is safer than guessing. + diagnostic.Record("X11 lock state unavailable", "error", err) + return 0, false + } + return uint8(bits), true +} + +// observeLockEvent pairs an ordered XKB notification with a forwarded press. +// Queries of the current server state can skip transitions in queued input. +func (s *Session) observeLockEvent(keycode int, after uint8) *input.LockChange { + pending, ok := s.lockPending[keycode] + if !ok { + return nil + } + if change, changed := input.ResolveLock(pending.key, pending.before, after); changed { + delete(s.lockPending, keycode) + return &change + } + return nil +} diff --git a/internal/terminal/locks_linux_test.go b/internal/terminal/locks_linux_test.go new file mode 100644 index 00000000..10dad2c5 --- /dev/null +++ b/internal/terminal/locks_linux_test.go @@ -0,0 +1,37 @@ +// Fenrir console screen reader. +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +//go:build linux && cgo + +package terminal + +import ( + "testing" + + "git.stormux.org/storm/fenrir/internal/input" +) + +func TestOrderedLockNotifications(t *testing.T) { + s := &Session{lockPending: map[int]lockPress{ + 66: {key: input.KeyCapsLock, before: input.LockCaps}, + 77: {key: input.KeyNumLock, before: input.LockCaps}, + }} + // An unchanged press waits for its release. A second lock must not + // overwrite it while both keys are down. + if got := s.observeLockEvent(66, input.LockCaps); got != nil { + t.Fatal("unchanged lock announced", got) + } + if got := s.observeLockEvent(77, input.LockCaps|input.LockNum); got == nil || *got != (input.LockChange{Key: input.KeyNumLock, On: true}) { + t.Fatal("Num Lock transition lost", got) + } + if got := s.observeLockEvent(66, input.LockNum); got == nil || *got != (input.LockChange{Key: input.KeyCapsLock}) { + t.Fatal("Caps Lock release transition lost", got) + } + if len(s.lockPending) != 0 { + t.Fatal("resolved locks retained", s.lockPending) + } + if got := s.observeLockEvent(66, input.LockCaps); got != nil { + t.Fatal("lock announced without a forwarded press", got) + } +} diff --git a/internal/terminal/native.c b/internal/terminal/native.c index 41c04d12..f83d7457 100644 --- a/internal/terminal/native.c +++ b/internal/terminal/native.c @@ -175,7 +175,7 @@ int terminal_key(VTerm *vt, const TerminalEvent *event, char *bytes, int size) { return length; } -struct TerminalX { Display *display; Window window; unsigned int numlock; int grabbed; XIM im; XIC ic; int scriptKeys[KEY_MAX+1]; int scriptKeyCount; unsigned char grabbedKeys[256]; }; +struct TerminalX { Display *display; Window window; unsigned int numlock, scrolllock; int grabbed, xkbEvent; XIM im; XIC ic; int scriptKeys[KEY_MAX+1]; int scriptKeyCount; unsigned char grabbedKeys[256]; }; static int x_error; static int trap_error(Display *display, XErrorEvent *event) { (void)display; @@ -208,13 +208,19 @@ static void observe_windows(TerminalX *x, Window window, int depth, int *remaini } static void collect_grabs(TerminalX *x, const int *keys, int count, unsigned char wanted[256]) { x->numlock = 0; + x->scrolllock = 0; XModifierKeymap *modifiers = XGetModifierMapping(x->display); KeyCode numlock = XKeysymToKeycode(x->display, XK_Num_Lock); + // Scroll Lock usually has no modifier under X; then it changes nothing + // and is never announced. + KeyCode scrolllock = XKeysymToKeycode(x->display, XK_Scroll_Lock); if (modifiers) { for (int mask=0; mask<8; mask++) - for (int k=0; kmax_keypermod; k++) - if (numlock && modifiers->modifiermap[mask*modifiers->max_keypermod+k] == numlock) - x->numlock |= 1u << mask; + for (int k=0; kmax_keypermod; k++) { + KeyCode code = modifiers->modifiermap[mask*modifiers->max_keypermod+k]; + if (numlock && code == numlock) x->numlock |= 1u << mask; + if (scrolllock && code == scrolllock) x->scrolllock |= 1u << mask; + } XFreeModifiermap(modifiers); } KeySym fixedKeys[] = {XK_Insert, @@ -327,6 +333,11 @@ TerminalX *terminal_x_open(unsigned long window, int *error) { int remaining = 1024; observe_windows(x, window, 0, &remaining); install_grabs(x); + int opcode, errorBase, major = XkbMajorVersion, minor = XkbMinorVersion; + if (!XkbQueryExtension(x->display, &opcode, &x->xkbEvent, &errorBase, &major, &minor) || + !XkbSelectEventDetails(x->display, XkbUseCoreKbd, XkbStateNotify, + XkbAllStateComponentsMask, XkbModifierLockMask)) + x_error = BadImplementation; Bool supported; XkbSetDetectableAutoRepeat(x->display, True, &supported); if (!supported) x_error = BadImplementation; @@ -395,11 +406,43 @@ int terminal_x_state(TerminalX *x, int *active, int *numlock, int *capslock) { if (error == BadWindow) { *active = 0; return 0; } return error ? -EIO : 0; } +// Bits match the console's KDGKBLED layout: 1 Scroll, 2 Num, 4 Caps. +int terminal_x_lock_bits(TerminalX *x, unsigned int mods) { + int bits = 0; + if (mods & x->scrolllock) bits |= 1; + if (mods & x->numlock) bits |= 2; + if (mods & LockMask) bits |= 4; + return bits; +} +// Locked modifiers only: a lock key's base modifier stays set while it is +// held, and XKB clears a lock on release when the press began locked. +int terminal_x_locks(TerminalX *x, int *bits) { + XErrorHandler previous = begin_trap(x->display); + XkbStateRec state; + int haveState = XkbGetState(x->display, XkbUseCoreKbd, &state) == Success; + int error = end_trap(x->display, previous); + if (error || !haveState) return -EIO; + *bits = terminal_x_lock_bits(x, state.locked_mods); + return 0; +} int terminal_x_next(TerminalX *x, TerminalEvent *event) { if (!XPending(x->display)) return 0; XEvent native; XNextEvent(x->display, &native); memset(event, 0, sizeof(*event)); + if (native.type == x->xkbEvent) { + XkbStateNotifyEvent *state = &((XkbEvent *)&native)->state; + // Key-generated notifications preserve the transition's position in + // the input stream. Ignore programmatic changes and other XKB events. + if (state->xkb_type == XkbStateNotify && + (state->changed & XkbModifierLockMask) && state->keycode && + (state->event_type == KeyPress || state->event_type == KeyRelease)) { + event->type = 2; + event->keycode = state->keycode; + event->state = terminal_x_lock_bits(x, state->locked_mods); + } + return 1; + } if (native.type == DestroyNotify) return native.xdestroywindow.window == x->window ? -EPIPE : 1; if (native.type == CreateNotify) { XErrorHandler previous = begin_trap(x->display); @@ -499,6 +542,8 @@ int terminal_key_code(unsigned long symbol, int keycode) { case XK_Page_Down: return KEY_PAGEDOWN; case XK_Insert: return KEY_INSERT; case XK_Caps_Lock: return KEY_CAPSLOCK; + case XK_Num_Lock: return KEY_NUMLOCK; + case XK_Scroll_Lock: return KEY_SCROLLLOCK; case XK_Multi_key: return KEY_COMPOSE; case XK_Menu: return KEY_MENU; case XK_Super_L: case XK_Meta_L: return KEY_LEFTMETA; diff --git a/internal/terminal/native.h b/internal/terminal/native.h index d96245fc..20081f78 100644 --- a/internal/terminal/native.h +++ b/internal/terminal/native.h @@ -36,6 +36,8 @@ int terminal_x_down(TerminalX *x, int code); int terminal_x_keys_down(TerminalX *x); int terminal_x_pending(TerminalX *x); int terminal_x_state(TerminalX *x, int *active, int *numlock, int *capslock); +int terminal_x_lock_bits(TerminalX *x, unsigned int mods); +int terminal_x_locks(TerminalX *x, int *bits); int terminal_x_next(TerminalX *x, TerminalEvent *event); enum { TERMINAL_CAPTURE_INACTIVE = 5 }; // Zero means captured; positive values are X grab refusal statuses or diff --git a/internal/terminal/session_linux.go b/internal/terminal/session_linux.go index c50eecdd..85f01897 100644 --- a/internal/terminal/session_linux.go +++ b/internal/terminal/session_linux.go @@ -83,6 +83,9 @@ type Session struct { code int time uint64 } + + // A lock can unlock on release, after another lock key has been pressed. + lockPending map[int]lockPress } func nativeError(code C.int) error { @@ -188,6 +191,7 @@ func (s *Session) State() (int, bool, bool, error) { } if s.active && active == 0 { C.terminal_x_release(s.x) + clear(s.lockPending) s.router.Reset() clear(s.held) clear(s.replayed) diff --git a/tests/native_terminal.py b/tests/native_terminal.py index b0f49ab5..448406d0 100644 --- a/tests/native_terminal.py +++ b/tests/native_terminal.py @@ -538,6 +538,53 @@ def main(): print("PASS: modifier checkbox announcements, rejected overlap without saving, passive grab conflict rollback, retry after held-key release, immediate key role changes, restarted Super review, Caps Lock script dispatch, Shift Caps toggle and ordinary typing") return + if os.environ.get("FENRIR_LOCKS_TEST_ONLY") == "1": + def lock_messages(start): + return [item for item in server.events[start:] + if item.startswith(("Caps Lock ", "Num Lock ", "Scroll Lock "))] + + for name, label in [("Caps_Lock", "Caps Lock"), ("Num_Lock", "Num Lock")]: + for enabled in ["on", "off"]: + start = len(server.events) + key(name) + spoken(label + " " + enabled, start) + time.sleep(0.05) + assert lock_messages(start) == [label + " " + enabled], server.events[start:] + start = len(server.events) + key("Scroll_Lock") + time.sleep(0.1) + assert not lock_messages(start), server.events[start:] + subprocess.run(["xmodmap", "-e", "add mod3 = Scroll_Lock"], check=True) + for enabled in ["on", "off"]: + start = len(server.events) + key("Scroll_Lock") + spoken("Scroll Lock " + enabled, start) + assert lock_messages(start) == ["Scroll Lock " + enabled], server.events[start:] + + # A later programmatic change must not hide a queued physical + # transition or generate an announcement of its own. + start = len(server.events) + os.kill(state["pid"], signal.SIGSTOP) + try: + wait_for(lambda: "State:\tT" in Path(f'/proc/{state["pid"]}/status').read_text(), "lock reader paused") + key("Caps_Lock") + keyboard.x11.XkbLockModifiers.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint] + assert keyboard.x11.XkbLockModifiers(keyboard.display, 0x100, 2, 0) + keyboard.x11.XSync(keyboard.display, 0) + finally: + os.kill(state["pid"], signal.SIGCONT) + spoken("Caps Lock on", start) + time.sleep(0.1) + assert lock_messages(start) == ["Caps Lock on"], server.events[start:] + key("a") + wait_for(lambda: recorded() == b"a", "typing after queued locks") + assert not server.errors, server.errors + key("Insert+q") + wait_for(lambda: (root / "finished").exists(), "lock fixture quit") + assert json.loads((root / "finished").read_text()) == {"status": 0, "restored": True, "flagsRestored": True} + print("PASS: lock on/off announcements, unmapped Scroll Lock silence, mapped Scroll Lock, queued transitions and typing") + return + if os.environ.get("FENRIR_CAPS_TEST_ONLY") == "1": start = len(server.events) key("Caps_Lock+i") @@ -546,6 +593,7 @@ def main(): key("a") wait_for(lambda: recorded() == b"a", "Caps modifier leaves lowercase typing") key("Shift_L+Caps_Lock", "b") + spoken("Caps Lock on") wait_for(lambda: recorded() == b"aB", "Shift Caps turns capitalization on") start = len(server.events) key("Caps_Lock+i") @@ -553,6 +601,7 @@ def main(): key("c") wait_for(lambda: recorded() == b"aBC", "reader chord preserves Caps on") key("Caps_Lock+Shift_R", "d") + spoken("Caps Lock off") wait_for(lambda: recorded() == b"aBCd", "Caps then Shift turns capitalization off") start = len(server.events) key("Caps_Lock+Shift_L+u")