Discard stale typing history after pointer input and Ctrl shortcuts
gswitch version
0.8.0 (official package); locally tested fix based on v0.8.0.
Installation method
deb package
Distribution
Ubuntu 26.04.1 LTS, x86_64
Desktop environment and session type
GNOME, Wayland
Keyboard layouts
us, ru
What happened
Word conversion sometimes replays text typed in a previous field, prefixing the current word with unrelated characters. Changing the conversion key from Insert to Pause did not resolve this. The problem is stale keystroke history; plain Pause conversion is not a clipboard paste.
Reproduction with Pause configured:
- Use the Russian layout and type
сбербinto a text field (physical keys corresponding toc,th,). Do not navigate with an arrow key or press Enter afterwards. - Press Ctrl+L to focus Chrome's address bar.
- Type
ьсаекthere, replacing the selected address. - Press Pause to correct the word.
Expected: only mcftr is replayed, with five characters deleted from the current field.
Actual: stale history is combined with the new word. The user observed c,th,mcftr; the deterministic regression test also shows ten backspaces instead of five. Moving between fields with the mouse can leave the same stale history.
The initial real-world report used the same new input/output (ьсаек → c,th,mcftr); the previous-field text above makes the stale prefix explicit for reproduction.
Config
[gswitch]
layout-switch=auto
convert-key=119
swap-conversion-modifiers=false
delay=10
layout-switch-delay=100
Layout switch detection
{"schema":1,"status":"found","result":{"scancodes":[125,57],"source":"gnome","raw":"<Super>space","keys":"LSuper+Space"},"attempts":[{"provider":"gnome","status":"found","raw":"<Super>space","keys":"LSuper+Space"}]}
Root cause and proposed improvement
Checked v0.8.0 and current public main (bcec45748de943edabb381ed4056e643e49e783b):
InputReader.AddDevicerequires KEY_A, excluding normal pointer devices, so clicking to change focus/caret is invisible to history tracking.Switcher.processKeyEventskips Ctrl+ordinary-key events without clearing the converter history. Ctrl+L changes focus; Ctrl+A/V/X and other shortcuts can invalidate the tracked text as well.- The packaged
configs/70-gswitch.rulesgrants active-session access only to keyboards and uinput. Accepting pointers in Go code alone is insufficient: the patched daemon initially still could not open the mouse/touchpad.
A local patch now:
- Observes pointer button/touch-contact events and clears typed history and pending buffer conversion on press, without adding pointer events to text history.
- Clears history on Ctrl+ordinary-key down, while retaining Ctrl+Pause / Ctrl+Shift+Pause and swapped-modifier gestures.
- Re-seeds any physically held Shift after clearing history, so uppercase typing after the focus change replays correctly.
- Sorts queued key/button events from different devices by evdev timestamps within each read batch, for both epoll and polling. The included test covers both orders of pre-queued device data; this is not a claim of strict ordering for all concurrently arriving events.
- Adds mouse/touchpad/touchscreen
uaccessrules before73-seat-late.rules, using logind's active-session ACLs, without adding the user to the input group or running the daemon as root.
Clearing on touch contact is intentionally conservative: after clicking/touching, previously typed text is no longer eligible for word conversion; typing that follows can be converted. Programmatic focus changes without observed input are outside this patch's scope. If a different invalidation policy is preferable, the reproduction and tests should still be useful.
Validation
- Before the reset fix, all four regression scenarios (mouse, touch, Ctrl+L, Ctrl+V) failed: ten deleted characters versus the expected five. Removing the reset mechanism makes those tests fail again.
- With the patch, regression tests verify both exact replayed keys and deletion count, held left/right Shift across reset, pointer release, capability bitmaps, and pre-queued cross-device ordering.
go test ./...andgo vet ./...passed with Go 1.26.8; existing modifier-swap and conversion tests also pass. Tests use regular temporary files for virtual-keyboard output, requiring no root/input devices/desktop.- Built and installed a separate local daemon. Verified the running process loaded that binary and opened the real mouse and touchpad after installing the additional udev rule.
- The original reporter subsequently confirmed that the Chrome behavior is now normal. Full cross-distribution/VM validation and golangci-lint were not run.
Definition of Done (DoD)
- [ ] After changing fields with Ctrl+L or a pointer click, converting newly typed text never replays the previous field's history; deterministic tests check emitted keys and deletion count.
- [ ] Held Shift preserves the case of subsequent typing after invalidation, and existing word/phrase/selection/case conversion gestures remain functional.
- [ ] Packaged active-session permissions allow the pointer events required by the chosen invalidation implementation; behavior and its limits are documented.
Reference patch
This is a tested local prototype for discussing the approach, rather than a request to merge without review.
Go implementation and rootless regression tests against v0.8.0
diff --git a/internal/gswitch/runtime/buffer_reset_test.go b/internal/gswitch/runtime/buffer_reset_test.go
new file mode 100644
index 0000000..72fafbc
--- /dev/null
+++ b/internal/gswitch/runtime/buffer_reset_test.go
@@ -0,0 +1,184 @@
+package runtime
+
+import (
+ "context"
+ "encoding/binary"
+ "io"
+ "os"
+ "reflect"
+ "syscall"
+ "testing"
+)
+
+func TestQueuedDevicesPreserveFocusEventOrder(t *testing.T) {
+ keyboard, err := os.CreateTemp(t.TempDir(), "keyboard")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer keyboard.Close()
+ pointer, err := os.CreateTemp(t.TempDir(), "pointer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pointer.Close()
+ write := func(file *os.File, stamp int64, code uint16) {
+ t.Helper()
+ if err := binary.Write(file, binary.LittleEndian, InputEvent{Time: syscall.Timeval{Sec: stamp}, Type: EV_KEY, Code: code, Value: K_DOWN}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write(keyboard, 1, testKeyA)
+ write(pointer, 2, 272)
+ write(keyboard, 3, KEY_C)
+ write(keyboard, 4, testKeyPause)
+ for _, files := range [][]*os.File{{keyboard, pointer}, {pointer, keyboard}} {
+ reader := &InputReader{devices: make(map[int]*Device)}
+ var fds []int
+ for _, file := range files {
+ if _, err := file.Seek(0, 0); err != nil {
+ t.Fatal(err)
+ }
+ fd := int(file.Fd())
+ fds = append(fds, fd)
+ reader.devices[fd] = &Device{FD: fd, File: file}
+ }
+ s := &Switcher{ctx: context.Background(), inputReader: reader, eventChan: make(chan *InputEvent, 8)}
+ s.readDeviceEvents(fds)
+ for _, want := range []uint16{testKeyA, 272, KEY_C, testKeyPause} {
+ select {
+ case event := <-s.eventChan:
+ if event.Code != want {
+ t.Fatalf("got key %d, want chronological key %d", event.Code, want)
+ }
+ default:
+ t.Fatal("missing event")
+ }
+ }
+ }
+}
+
+// All replay output stays in a regular file, never the host's input devices.
+func TestFocusChangeDiscardsPreviousWord(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ change []KeyEvent
+ }{
+ {"mouse", []KeyEvent{{272, K_DOWN}, {272, K_UP}}},
+ {"touch", []KeyEvent{{330, K_DOWN}, {330, K_UP}}},
+ {"ctrl-l", []KeyEvent{{KEY_LEFTCTRL, K_DOWN}, {38, K_DOWN}, {38, K_UP}, {KEY_LEFTCTRL, K_UP}}},
+ {"ctrl-v", []KeyEvent{{KEY_LEFTCTRL, K_DOWN}, {KEY_V, K_DOWN}, {KEY_V, K_UP}, {KEY_LEFTCTRL, K_UP}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ output, err := os.CreateTemp(t.TempDir(), "events")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer output.Close()
+ s := &Switcher{config: &Config{ConvertKey: testKeyPause}, converter: NewConverter(), vKeyboard: &VirtualKeyboard{fd: output}, inputReader: &InputReader{}}
+ s.converter.ConvKey = testKeyPause
+ send := func(e KeyEvent) { s.processKeyEvent(&InputEvent{Type: EV_KEY, Code: e.Code, Value: e.Value}) }
+ typeKeys := func(keys []uint16) {
+ for _, c := range keys {
+ send(KeyEvent{c, K_DOWN})
+ send(KeyEvent{c, K_UP})
+ }
+ }
+ // c,th, came from a previous field; mcftr corresponds to the user's ьсаек.
+ typeKeys([]uint16{46, 51, 20, 35, 51})
+ for _, e := range tc.change {
+ send(e)
+ }
+ want := []uint16{50, 46, 33, 20, 19}
+ typeKeys(want)
+ send(KeyEvent{testKeyPause, K_DOWN})
+ send(KeyEvent{testKeyPause, K_UP})
+ if n := capturedBackspaces(t, output, KEY_LEFTCTRL); n != len(want) {
+ t.Fatalf("deleted %d characters, want %d from current field only", n, len(want))
+ }
+ if _, err := output.Seek(0, 0); err != nil {
+ t.Fatal(err)
+ }
+ var replay []uint16
+ for {
+ var e InputEvent
+ err := binary.Read(output, binary.LittleEndian, &e)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if e.Type == EV_KEY && e.Value == K_DOWN && e.Code != KEY_BACKSPACE && e.Code != KEY_LEFTSHIFT && e.Code != KEY_RIGHTSHIFT {
+ replay = append(replay, e.Code)
+ }
+ }
+ if !reflect.DeepEqual(replay, want) {
+ t.Fatalf("replayed %v, want only %v", replay, want)
+ }
+ })
+ }
+}
+
+func TestPointerReleaseDoesNotDiscardNewTyping(t *testing.T) {
+ s := &Switcher{config: &Config{ConvertKey: testKeyPause}, converter: NewConverter()}
+ s.processKeyEvent(&InputEvent{Type: EV_KEY, Code: testKeyA, Value: K_DOWN})
+ s.processKeyEvent(&InputEvent{Type: EV_KEY, Code: 272, Value: K_UP})
+ if s.converter.BufferLen() != 1 {
+ t.Fatal("pointer release discarded typing")
+ }
+}
+
+func TestFocusResetPreservesHeldShift(t *testing.T) {
+ for _, shift := range []uint16{KEY_LEFTSHIFT, KEY_RIGHTSHIFT} {
+ for _, change := range []uint16{272, 38} {
+ s := &Switcher{config: &Config{ConvertKey: testKeyPause}, converter: NewConverter()}
+ send := func(code uint16, value int32) { s.processKeyEvent(&InputEvent{Type: EV_KEY, Code: code, Value: value}) }
+ send(shift, K_DOWN)
+ if change == 38 {
+ send(KEY_LEFTCTRL, K_DOWN)
+ }
+ send(change, K_DOWN)
+ send(change, K_UP)
+ if change == 38 {
+ send(KEY_LEFTCTRL, K_UP)
+ }
+ send(testKeyA, K_DOWN)
+ send(testKeyA, K_UP)
+ send(shift, K_UP)
+ pressed := false
+ found := false
+ for _, event := range s.converter.Convert(ActionConvertWord) {
+ if event.Code == shift {
+ pressed = event.Value == K_DOWN
+ }
+ if event.Code == testKeyA && event.Value == K_DOWN {
+ found = true
+ if !pressed {
+ t.Fatalf("shift %d missing during replay after focus event %d", shift, change)
+ }
+ }
+ }
+ if !found {
+ t.Fatal("letter was not replayed")
+ }
+ }
+ }
+}
+
+func TestInputCapabilityKeys(t *testing.T) {
+ for _, code := range []uint16{30, 272, 273, 274, 330} {
+ bits := make([]byte, KeyBitsSize)
+ bits[code/8] |= 1 << (code % 8)
+ if !keyBitsHaveAny(bits, 30, 272, 273, 274, 330) {
+ t.Fatalf("device key %d was not accepted", code)
+ }
+ }
+ if keyBitsHaveAny(nil, 30, 272, 330) {
+ t.Fatal("empty capability set was accepted")
+ }
+ bits := make([]byte, KeyBitsSize)
+ bits[115/8] |= 1 << (115 % 8)
+ if keyBitsHaveAny(bits, 30, 272, 273, 274, 330) {
+ t.Fatal("media-only device was accepted")
+ }
+}
diff --git a/internal/gswitch/runtime/input_reader.go b/internal/gswitch/runtime/input_reader.go
index 238087b..2b21224 100644
--- a/internal/gswitch/runtime/input_reader.go
+++ b/internal/gswitch/runtime/input_reader.go
@@ -170,6 +170,15 @@ func HasKeyboardCapability(fd int) bool {
// hasKeyACapability checks if device has KEY_A (basic keyboard test)
func hasKeyACapability(fd int) bool {
+ return hasInputKeys(fd, 30)
+}
+
+// Accept pointer devices only for focus/caret invalidation, never text input.
+func hasPointerCapability(fd int) bool {
+ return hasInputKeys(fd, 0x110, 0x111, 0x112, 0x14a)
+}
+
+func hasInputKeys(fd int, keys ...uint16) bool {
// Get buffer from pool to reduce allocations
keyBitsPtr, ok := keyBitsPool.Get().(*[]byte)
if !ok || keyBitsPtr == nil {
@@ -192,11 +201,17 @@ func hasKeyACapability(fd int) bool {
return false
}
- // Check for KEY_A (30) - byte 3, bit 6
- keyA := 30
- byteIndex := keyA / 8
- bitIndex := keyA % 8
- return keyBits[byteIndex]&(1<<bitIndex) != 0
+ return keyBitsHaveAny(keyBits, keys...)
+}
+
+func keyBitsHaveAny(bits []byte, keys ...uint16) bool {
+ for _, key := range keys {
+ index := int(key / 8)
+ if index < len(bits) && bits[index]&(1<<(key%8)) != 0 {
+ return true
+ }
+ }
+ return false
}
// AddDevice adds a new input device
@@ -216,10 +231,10 @@ func (ir *InputReader) AddDevice(path string) (*Device, error) {
return nil, fmt.Errorf("failed to open %s: %w", path, err)
}
- // Check if it's a keyboard
- if !hasKeyboardCapability(fd) || !hasKeyACapability(fd) {
+ // Watch keyboards and pointer buttons; ignore unrelated event devices.
+ if !hasKeyboardCapability(fd) || (!hasKeyACapability(fd) && !hasPointerCapability(fd)) {
unix.Close(fd)
- return nil, fmt.Errorf("device is not a keyboard: %s", path)
+ return nil, fmt.Errorf("device has no keyboard or pointer buttons: %s", path)
}
// Get device info
diff --git a/internal/gswitch/runtime/switcher.go b/internal/gswitch/runtime/switcher.go
index 927a6cd..1c763d3 100644
--- a/internal/gswitch/runtime/switcher.go
+++ b/internal/gswitch/runtime/switcher.go
@@ -527,18 +527,8 @@ func (s *Switcher) processKeyEventsEpoll() {
continue
}
- // Read events only from ready file descriptors
- for _, fd := range readyFds {
- for {
- event, ok := s.inputReader.ReadEvent(fd)
- if !ok {
- break
- }
- if event.Type == EV_KEY {
- s.enqueueEvent(event)
- }
- }
- }
+ // Include every device: a queued click must precede later typing.
+ s.readAllDeviceEvents()
}
}
@@ -644,7 +634,11 @@ func isRetryableDeviceOpenError(err error) bool {
}
func (s *Switcher) readAllDeviceEvents() {
- fds := s.inputReader.GetAllFDs()
+ s.readDeviceEvents(s.inputReader.GetAllFDs())
+}
+
+func (s *Switcher) readDeviceEvents(fds []int) {
+ var events []*InputEvent
for _, fd := range fds {
for {
event, ok := s.inputReader.ReadEvent(fd)
@@ -652,14 +646,42 @@ func (s *Switcher) readAllDeviceEvents() {
break
}
if event.Type == EV_KEY {
- s.enqueueEvent(event)
+ events = append(events, event)
}
}
}
+ // evdev timestamps use the same clock across devices. Preserve per-device
+ // order on ties, and merge queued pointer/keyboard input chronologically.
+ slices.SortStableFunc(events, func(a, b *InputEvent) int {
+ if a.Time.Sec < b.Time.Sec {
+ return -1
+ }
+ if a.Time.Sec > b.Time.Sec {
+ return 1
+ }
+ if a.Time.Usec < b.Time.Usec {
+ return -1
+ }
+ if a.Time.Usec > b.Time.Usec {
+ return 1
+ }
+ return 0
+ })
+ for _, event := range events {
+ s.enqueueEvent(event)
+ }
}
func (s *Switcher) processKeyEvent(event *InputEvent) {
s.logDebug("input event received")
+ // Pointer presses can move focus or the caret without a keyboard event.
+ // They invalidate typed history, but must never enter the text buffer.
+ if isPointerButton(event.Code) {
+ if event.Value == K_DOWN {
+ s.resetTypedHistory()
+ }
+ return
+ }
defer s.finishSelectionModifierEvent(event)
s.trackSelectionModifiers(event)
@@ -669,6 +691,12 @@ func (s *Switcher) processKeyEvent(event *InputEvent) {
// Skip regular keys when Ctrl is pressed (Ctrl+key is a hotkey, not text input)
if s.ctrlPressed.Load() && Letters[event.Code] {
+ // Ctrl+L changes focus; Ctrl+A/V/X and editor shortcuts change the
+ // visible text independently of our history. Preserve Ctrl itself
+ // so Ctrl+Pause and the modifier-swap line gesture still work.
+ if event.Value == K_DOWN {
+ s.resetTypedHistory()
+ }
s.logDebug("skipping key (Ctrl pressed)")
return
}
@@ -1240,3 +1268,21 @@ func (s *Switcher) waitForSessionWithConfig(ctx context.Context, cfg WaitConfig)
}
}
}
+
+// Mouse buttons and touch contact are focus/caret-changing input.
+func isPointerButton(code uint16) bool {
+ return (code >= 0x110 && code <= 0x117) || code == 0x14a
+}
+
+func (s *Switcher) resetTypedHistory() {
+ s.converter.ClearBuffer()
+ s.pendingBufferAction = ActionNone
+ // The physical Shift state survives a focus change. Keep its down event
+ // so subsequent uppercase letters replay with the same modifier.
+ if s.leftShiftPressed.Load() {
+ s.converter.Push(KEY_LEFTSHIFT, K_DOWN)
+ }
+ if s.rightShiftPressed.Load() {
+ s.converter.Push(KEY_RIGHTSHIFT, K_DOWN)
+ }
+}
Additional udev rule used for the local fix
Installed separately before 73-seat-late.rules; upstream could incorporate these entries into its existing input-access rule.
# Allow the active local session to observe focus-changing pointer events.
# Must precede systemd's 73-seat-late.rules, like the official keyboard rule.
SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_MOUSE}=="1", TAG+="uaccess"
SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_TOUCHPAD}=="1", TAG+="uaccess"
SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT_TOUCHSCREEN}=="1", TAG+="uaccess"
Update after re-checking the reference patch against current main (bcec457).
- The patch applies cleanly to
main;go test ./...andgo vet ./...pass. golangci-lint v2.6.0(the version used in CI) reports four issues in the new tests:errorlint: useerrors.Is(err, io.EOF);gocritic:0600/0700→0o600/0o700;intrange: usefor pass := range 3.
- The patch still needs the packaging side:
configs/70-gswitch.rulesmust grantuaccessfor pointer devices. Accepting pointers in Go alone is not enough under the installed rule; my local workaround was a separate71-gswitch-pointer.rules, but upstream should extend the existing rule. - I also see a gap in the reset path:
resetTypedHistoryclears the converter buffer and pending buffer action, but notselectionPending/pendingSelection. If a selection conversion is armed and the user clicks into another field before releasing the modifiers, the deferred selection transform can still run in the new context. I can add the reset and a regression test. - The periodic device-recovery patching (5 s rescan for missed hotplug/late ACL) is a separate concern and is not part of this issue's patch; I would keep it out of this PR.
If the approach is acceptable, I can open a clean PR from current main with the pointer rule, lint fixes, selection-pending fix, and a short docs note about the pointer uaccess trade-off. I would also like to know whether the intended scope includes Ctrl+Backspace, Ctrl+Delete, and arrow/Home/End caret moves: they also invalidate the tracked word but are not covered by the current "Ctrl+ordinary key" rule.