Replay browse keys when native focus leaves the document window

This commit is contained in:
Storm Dragon committed 2026-11-19 04:27:39 -05:00
1 parent 938847e6ae
commit 58d8f6bee1
7 files changed
+386 -2

No files matched your search

@@ -0,0 +1,159 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package xorg
import (
"bufio"
"context"
"encoding/json"
"os"
"os/exec"
"slices"
"testing"
"time"
"git.stormux.org/storm/cthulhu/internal/input"
)
type routingKey struct {
Window string `json:"window"`
Key string `json:"key"`
Pressed bool `json:"pressed"`
}
type routingReply struct {
Windows map[string]uint64 `json:"windows"`
Events []routingKey `json:"events"`
}
// The fixture's application-side marker acknowledges all preceding input,
// including keys replayed from a stale synchronous grab. Keep reader policy
// fixed throughout: these transitions deliberately precede AT-SPI's updates.
func TestNativeBrowseFocusRouting(t *testing.T) {
if os.Getenv("CTHULHU_NATIVE_X11") != "1" && os.Getenv("CTHULHU_NATIVE_BROWSER") != "1" {
t.Skip("requires private X11 display")
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
fixture := exec.CommandContext(ctx, "/usr/bin/python3", "-u", "../../../tests/x11_key_routing_fixture.py")
stdin, err := fixture.StdinPipe()
if err != nil {
t.Fatal(err)
}
stdout, err := fixture.StdoutPipe()
if err != nil {
t.Fatal(err)
}
fixture.Stderr = os.Stderr
if err := fixture.Start(); err != nil {
t.Fatal(err)
}
defer func() { stdin.Close(); fixture.Wait() }()
replies := make(chan routingReply)
readErrors := make(chan error, 1)
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
var reply routingReply
if err := json.Unmarshal(scanner.Bytes(), &reply); err != nil {
readErrors <- err
return
}
select {
case replies <- reply:
case <-ctx.Done():
return
}
}
readErrors <- scanner.Err()
}()
read := func(t *testing.T) routingReply {
t.Helper()
select {
case reply := <-replies:
return reply
case err := <-readErrors:
t.Fatalf("routing fixture stopped: %v", err)
case <-ctx.Done():
t.Fatal("routing fixture did not receive the application key marker", ctx.Err())
}
return routingReply{}
}
if reply := read(t); len(reply.Windows) != 8 {
t.Fatalf("missing fixture windows: %+v", reply)
}
listener := NewCommands([]string{"Insert", "KP_Insert"}, input.DesktopKeyboardLayout)
if err := listener.Start(ctx); err != nil {
t.Fatal(err)
}
defer listener.Stop(context.Background())
listener.SetBrowseNavigation(true)
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for !listener.BrowseNavigationEnabled() {
select {
case err := <-listener.Failures():
t.Fatal(err)
case <-ticker.C:
case <-ctx.Done():
t.Fatal("browse grabs were not installed", ctx.Err())
}
}
for _, test := range []struct {
name, focus, active string
keys []string
commands []input.Command
passed bool
}{
{"document", "document", "document", []string{"h"}, []input.Command{input.DocumentNextHeading}, false},
{"other-window", "other", "other", []string{"h", "k", "Right", "Return"}, nil, true},
{"return-before-accessibility-update", "document", "document", []string{"h"}, []input.Command{input.DocumentNextHeading}, false},
{"same-process-stale-active-window", "other", "document", []string{"h", "k", "Right", "Return"}, nil, true},
{"same-process-child-stale-active-window", "other-child", "document", []string{"h", "Down"}, nil, true},
{"document-child", "document-child", "document", []string{"h", "Right"}, []input.Command{input.DocumentNextHeading, input.DocumentCaretNextCharacter}, false},
{"document-input-only-grab", "document-grab", "document", []string{"h"}, []input.Command{input.DocumentNextHeading}, false},
{"other-input-only-grab", "other-grab", "document", []string{"h", "Return"}, nil, true},
{"other-without-ewmh", "other-child", "", []string{"h", "Return"}, nil, true},
{"document-without-ewmh", "document-child", "", []string{"h"}, []input.Command{input.DocumentNextHeading}, false},
} {
if !t.Run(test.name, func(t *testing.T) {
request := struct {
Focus string `json:"focus"`
Active string `json:"active"`
Keys []string `json:"keys"`
}{test.focus, test.active, test.keys}
if err := json.NewEncoder(stdin).Encode(request); err != nil {
t.Fatal(err)
}
reply := read(t)
var want []routingKey
if test.passed {
for _, key := range test.keys {
want = append(want, routingKey{test.focus, key, true}, routingKey{test.focus, key, false})
}
}
if !slices.Equal(reply.Events, want) {
t.Fatalf("application keys = %+v, want %+v", reply.Events, want)
}
var got []input.Command
drain:
for {
select {
case event := <-listener.Commands():
got = append(got, event.Command)
default:
break drain
}
}
if !slices.Equal(got, test.commands) {
t.Fatalf("reader commands = %v, want %v", got, test.commands)
}
if !listener.BrowseNavigationEnabled() {
t.Fatal("fixture accidentally changed the reader's stale browse policy")
}
}) {
return
}
}
}
+24 -1
View File
@@ -573,6 +573,29 @@ void toggle_command_caps_lock(CommandDevice *device) {
XkbLockModifiers(device->display,XkbUseCoreKbd,LockMask,device->capsLocked ? LockMask:0);
XSync(device->display,False);
}
// EWMH's active client can lag behind X input focus during a window switch.
// Browse-only keys belong to the recorded document only while native focus is
// inside that client too. A sibling window of the same process is not proof.
// Keep browser child windows and verified GTK input-only popup owners working.
static int cthulhu_browse_focus_matches(CommandDevice *device) {
Display *display = device->display;
Window focus = None, root = DefaultRootWindow(display);
int revert, matches = 0;
cthulhu_x11_begin_read(display);
XGetInputFocus(display, &focus, &revert);
focus = cthulhu_input_grab_owner(display, focus);
for (int depth = 0; focus != None && focus != PointerRoot &&
focus != root && depth < 64; depth++) {
if (focus == device->browseWindow) { matches = 1; break; }
Window treeRoot, parent, *children = NULL;
unsigned int count = 0;
if (!XQueryTree(display, focus, &treeRoot, &parent, &children, &count)) break;
if (children) XFree(children);
focus = parent;
}
if (cthulhu_x11_end_read(display)) return 0;
return matches;
}
int next_command_key(CommandDevice *device, CommandKey *key) {
if (!XPending(device->display)) {
struct pollfd fd={ConnectionNumber(device->display),POLLIN,0};
@@ -616,7 +639,7 @@ int next_command_key(CommandDevice *device, CommandKey *key) {
if (browseOnly) {
Foreground foreground=read_foreground(device->display);
if (!device->browse || !foreground.known || foreground.window==0 ||
foreground.window!=device->browseWindow) {
foreground.window!=device->browseWindow || !cthulhu_browse_focus_matches(device)) {
XAllowEvents(device->display,ReplayKeyboard,event.xkey.time); XFlush(device->display); return 0;
}
}