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

+1
View File
@@ -13,6 +13,7 @@ Cthulhu is a Linux screen reader written in Go.
- [Flatpak foreground accessibility](docs/testing/flatpak-foreground.md): process identity and proxy matching, tests, and live acceptance.
- [Background event filtering](docs/testing/background-events.md): early foreground checks, notification exceptions, and performance verification.
- [Browser Find](docs/testing/browser-find.md): native Ctrl+F focus, typing, window ownership and verification.
- [Browse-key focus routing](docs/testing/browser-focus-routing.md): native window transitions, stale foreground metadata, and key-delivery verification.
- [Native i3 announcements](docs/testing/i3-announcements.md): modes, workspaces, window states, urgency, marks, workspace moves, and live verification.
- [MATE window switcher](docs/testing/window-switcher.md): Marco selection announcements, isolated checks, and live verification.
- [MATE desktop](docs/testing/mate-desktop.md): Orca comparison, panel menus and icon labels, regression checks, and live verification.
+76
View File
@@ -0,0 +1,76 @@
# Browse keys during native focus transitions
Browse-only keys require both the recorded foreground client and native X11
input focus to belong to the document's window. A delayed `_NET_ACTIVE_WINDOW`
update must not let an old document consume typing in another window, including
another window of the browser's own process. The real grabbed event is replayed
to the focused application when ownership cannot be established.
Native focus inside a document's child windows retains browse navigation.
Verified GTK input-only grab windows retain their existing owner resolution:
the mapped transient popup, window group, and process metadata must agree.
Global reader commands keep their existing routing.
## Automated verification
```sh
python3 tests/native_test_session.py env GOWORK=off GOCACHE=/tmp/cthulhu-cache GOTMPDIR=/tmp CTHULHU_NATIVE_X11=1 go test ./internal/platform/xorg -run '^TestNativeBrowseFocusRouting$' -count=1 -v
CTHULHU_NATIVE_BROWSER_TESTS=focus-routing,keys,find,modes,menu,document python3 tests/native_browser.py
CTHULHU_FIREFOX_FIND=1 python3 tests/native_firefox.py
```
The browser menu proof requires Brave. The focused routing proof needs
`python-xlib`, as do the existing X11 window-group fixtures.
The routing fixture uses a private X11 connection and XTest events. It changes
input focus and sends keys in one server-grabbed batch, keeping the reader's
browse policy fixed to represent delayed accessibility updates. Application
receipt of an unbound F12 release is the ordered completion marker. Assertions
compare every received press/release and every reader command, checking for
lost, duplicated, misrouted, or incorrectly consumed input.
Cases include another window with current and stale EWMH state, returning to
the document before accessibility updates, child windows, input-only popup
grabs, and focus without an EWMH active-window property. The original code
consumed H, K, Right, and Return in the other window when EWMH still named the
document; this regression requires all eight events to reach that window.
These checks cover native key routing. They do not establish recovery from a
frozen reader process, kernel keyboard delivery, audible speech, or Braille.
## Verification results
On 2026-11-19, all ten routing cases passed five consecutive runs. The normal
`native_x11.py` command-listener selection, including the new test, passed with
a race-instrumented test binary. Input package tests, focused browser/document
app race tests, Xorg/input `go vet`, and Xorg package lint passed. Chromium and
Firefox Find, and Brave menu, document, key-transition, and mode checks passed.
The initial Brave mode run missed a Braille routing frame at
`document_native_test.go:965`. An isolated rerun with the original keyboard C
source through a Go overlay passed, and an isolated rerun with the fix passed.
The first failure remains unexplained. The complete app race run exceeded its
180-second total budget while constructing a Tentacle archive fixture; it is
not a full-suite pass. A direct bare-Xvfb run also failed
`TestNativeActiveWindowIsXTerm`, which is outside the normal harness selection
and expects EWMH active-window metadata. The intended native harness passed.
The subsequent pre-push review passed the complete `go test -race ./...` suite
with a 300-second per-package timeout, full `go vet` and lint, the native X11
listener selection, Firefox Find, and the clipboard, application chooser,
speech-history and voice-profile helper checks. Brave focus routing, key
transitions, Find, menus, document commands, dynamic and ticking navigation
passed. The Braille-frame failure at line 965 reproduced on unchanged commit
`8cc2931`, confirming that it also occurs without these changes. Another mode
run missed chrome key echo after Ctrl+L. Two later mode runs with the pending
changes passed; the intermittent failures remain unexplained.
## Live verification
After reviewing and building the change, switch rapidly between a webpage and
another window, including another window of the same browser. Check heading
and arrow navigation on the page, ordinary typing and Return elsewhere, and
return to browse navigation. Check Ctrl+F typing, browser menus, and native
buttons. Repeat with the physical keyboard and normal window manager; confirm
spoken output and Braille separately. No running reader is replaced by the
automated checks.
@@ -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;
}
}
+1
View File
@@ -12,6 +12,7 @@ from native_test_session import run_private_session
BROWSER_PROOFS = {
"focus-routing": ("./internal/platform/xorg", "^TestNativeBrowseFocusRouting$", 20, 25),
"find": ("./internal/app", "^TestNativeBrowserFind$", 35, 40, "browser-find.html"),
"disclosure": ("./internal/app", "^TestNativeBrowserDisclosureFocus$", 35, 40, "browser-actions.html"),
"actions": ("./internal/app", "^TestNativeBrowserActionOwnership$", 35, 40, "browser-actions.html"),
+1 -1
View File
@@ -175,7 +175,7 @@ def run_inside(directory):
subprocess.run(['xdotool', 'windowfocus', window], check=True)
nativeTest = os.environ.get('CTHULHU_XRECORD_TEST')
if nativeTest:
native_tests = os.environ.get('CTHULHU_NATIVE_X11_TESTS', '^TestNative(ModifierPressRelease|CommandBypass|CommandGrabSuspensionAndRestoration|BrowseKeyTransitions|DispatchBeforeRelease|CustomBindingsUpdateAndRelease|TentacleBindingsUpdateAndRelease|ModifierConfigurationUpdate|LockStatesAndShiftCapsLock|XTermHandoffKeepsKeypadReleased|SuspendedQueuedKey|LearnModeCapturesKeysAndRestoresCommands|SecureInputDropsKeysAndRestoresGrabs)$')
native_tests = os.environ.get('CTHULHU_NATIVE_X11_TESTS', '^TestNative(ModifierPressRelease|CommandBypass|CommandGrabSuspensionAndRestoration|BrowseFocusRouting|BrowseKeyTransitions|DispatchBeforeRelease|CustomBindingsUpdateAndRelease|TentacleBindingsUpdateAndRelease|ModifierConfigurationUpdate|LockStatesAndShiftCapsLock|XTermHandoffKeepsKeypadReleased|SuspendedQueuedKey|LearnModeCapturesKeysAndRestoresCommands|SecureInputDropsKeysAndRestoresGrabs)$')
subprocess.run([nativeTest, '-test.run', native_tests, '-test.timeout=40s'], env=dict(os.environ, CTHULHU_NATIVE_X11='1', CTHULHU_NATIVE_BROWSER='1'), check=True, timeout=45, cwd=Path(__file__).resolve().parents[1] / 'internal/platform/xorg')
if nativeTest and os.environ.get('CTHULHU_NATIVE_LISTENER_ONLY') == '1':
print('PASS: selected native X11 command listener tests')
+124
View File
@@ -0,0 +1,124 @@
"""Record real XTest key delivery to windows of one private X11 client.
F12's release ends each batch: receiving it proves earlier keys have passed
through any synchronous reader grab. No timeout or quiet period counts as proof
that a key was consumed.
"""
import json
import os
import select
import sys
from Xlib import X, Xatom, XK, display
from Xlib.ext import xtest
def main():
connection = display.Display()
root = connection.screen().root
activeAtom = connection.intern_atom("_NET_ACTIVE_WINDOW")
stateAtom = connection.intern_atom("WM_STATE")
pidAtom = connection.intern_atom("_NET_WM_PID")
leaderAtom = connection.intern_atom("WM_CLIENT_LEADER")
oldActive = root.get_full_property(activeAtom, X.AnyPropertyType)
oldFocus = connection.get_input_focus()
windows = {}
for index, name in enumerate(("document", "other")):
window = root.create_window(
20 + index * 350, 20, 300, 200, 0,
connection.screen().root_depth, X.InputOutput, X.CopyFromParent,
event_mask=X.KeyPressMask | X.KeyReleaseMask,
)
window.set_wm_class("cthulhu-key-probe", "CthulhuKeyProbe")
window.change_property(pidAtom, Xatom.CARDINAL, 32, [os.getpid()])
window.change_property(leaderAtom, Xatom.WINDOW, 32, [window.id])
window.change_property(stateAtom, stateAtom, 32, [1, 0])
window.map()
windows[name] = window
child = window.create_window(
0, 0, 100, 100, 0, connection.screen().root_depth,
X.InputOutput, X.CopyFromParent,
event_mask=X.KeyPressMask | X.KeyReleaseMask,
)
child.map()
windows[name + "-child"] = child
popup = root.create_window(
20 + index * 350, 30, 100, 60, 0, connection.screen().root_depth,
X.InputOutput, X.CopyFromParent, override_redirect=True,
)
grab = root.create_window(
0, 0, 1, 1, 0, 0, X.InputOnly, X.CopyFromParent,
override_redirect=True, event_mask=X.KeyPressMask | X.KeyReleaseMask,
)
for member in (popup, grab):
member.change_property(pidAtom, Xatom.CARDINAL, 32, [os.getpid()])
member.change_property(leaderAtom, Xatom.WINDOW, 32, [window.id])
member.map()
popup.set_wm_transient_for(window)
popup.change_property(connection.intern_atom("_NET_WM_WINDOW_TYPE"), Xatom.ATOM, 32,
[connection.intern_atom("_NET_WM_WINDOW_TYPE_COMBO")])
windows[name + "-popup"] = popup
windows[name + "-grab"] = grab
names = {window.id: name for name, window in windows.items()}
keyNames = ("h", "k", "Right", "Down", "Return", "F12")
codes = {name: connection.keysym_to_keycode(XK.string_to_keysym(name)) for name in keyNames}
symbols = {code: name for name, code in codes.items()}
windows["document"].set_input_focus(X.RevertToParent, X.CurrentTime)
root.change_property(activeAtom, Xatom.WINDOW, 32, [windows["document"].id])
connection.sync()
print(json.dumps({"windows": {name: window.id for name, window in windows.items()}}), flush=True)
records = []
try:
while True:
while connection.pending_events():
event = connection.next_event()
if event.type not in (X.KeyPress, X.KeyRelease):
continue
name = symbols.get(event.detail, str(event.detail))
if name == "F12":
if event.type == X.KeyRelease:
print(json.dumps({"events": records}), flush=True)
records = []
else:
records.append({"window": names[event.window.id], "key": name,
"pressed": event.type == X.KeyPress})
ready, _, _ = select.select([sys.stdin, connection], [], [])
if sys.stdin not in ready:
continue
line = sys.stdin.readline()
if not line:
return
request = json.loads(line)
# Prevent the command owner from observing a halfway-completed
# focus transition before the first key has reached the server.
connection.grab_server()
try:
if "focus" in request:
windows[request["focus"]].set_input_focus(X.RevertToParent, X.CurrentTime)
if "active" in request:
if request["active"]:
root.change_property(activeAtom, Xatom.WINDOW, 32,
[windows[request["active"]].id])
else:
root.delete_property(activeAtom)
for key in request.get("keys", []):
xtest.fake_input(connection, X.KeyPress, codes[key])
xtest.fake_input(connection, X.KeyRelease, codes[key])
xtest.fake_input(connection, X.KeyPress, codes["F12"])
xtest.fake_input(connection, X.KeyRelease, codes["F12"])
finally:
connection.ungrab_server()
connection.flush()
finally:
if oldActive is None:
root.delete_property(activeAtom)
else:
root.change_property(activeAtom, oldActive.property_type, oldActive.format, oldActive.value)
connection.set_input_focus(oldFocus.focus, oldFocus.revert_to, X.CurrentTime)
connection.sync()
connection.close()
if __name__ == "__main__":
main()