diff --git a/AGENTS.md b/AGENTS.md index fcd9cf6..f49b710 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,8 @@ After synchronization, check whether the reported issue still exists and inspect Cthulhu is a Go Linux screen reader. `cmd/` contains executables; `internal/` owns reader subsystems. Embedded audio lives in `assets/sounds/`, Tentacle libraries in `sdk/`, native harnesses in `tests/`, and parity records in `testdata/`. Go tests sit beside implementation files. Arch packaging lives in `distro-packages/Arch-Linux/cthulhu-git/`. +Touch screen support lives in `internal/touch` (gesture recognizer), `internal/platform/evdev` (direct touch screen input with `EVIOCGRAB`; needs the `input` group), `internal/platform/xorg/touch*` (window lookup and activation clicks) and `internal/app/touch.go` (service). Read [touch support](docs/touch-support.md) for its design, status, test procedure and running log before changing it, and update that file when touch behavior changes. + Reader-independent Go code shared with Fenrir lives in `git.stormux.org/storm/screenreader-common`; check it before duplicating pure data or behavior. Shared packages own the emoji catalog, internal interaction diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..eab5f8d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,21 @@ +# Claude Code Notes + +Follow the repository guidelines, which are shared with Codex: + +@AGENTS.md + +Touch screen work in progress, with design, status, testing and the running log: + +@docs/touch-support.md + +## Working With the Maintainer's Testers + +- Testers use screen readers. Keep replies plain text: short sentences and + simple lists, no tables or decorative symbols. +- Test touch changes on real hardware with spoken feedback, one gesture at a + time, and do not move on until each one works. +- Never replace a running reader without asking, and always keep a way back + to the installed reader for the tester. +- Add a dated entry to the log in `docs/touch-support.md` after each working + session, and update its roadmap and open issues instead of appending stale + notes. diff --git a/docs/touch-support.md b/docs/touch-support.md new file mode 100644 index 0000000..7318a39 --- /dev/null +++ b/docs/touch-support.md @@ -0,0 +1,263 @@ +# Touch Screen Support + +Goal: a blind user can run the whole Linux desktop with the touch screen as the +only input, the way TalkBack, VoiceOver and NVDA touch work. Touch is its own +subsystem with its own gestures, bindings and modes. It shares only the +"what is at this point" hit test with mouse review. + +Integrated into `testing` from Chase Cichorz's three-commit touch patch. + +## Design + +- `internal/platform/evdev`: reads the touch screen directly from the Linux + input layer, pure Go with no cgo. It finds direct multitouch devices + (`INPUT_PROP_DIRECT` with `ABS_MT_SLOT`, positions and tracking IDs), grabs + the device with `EVIOCGRAB` while touch is on, and turns multitouch + protocol B frames into begin, update and end contacts in screen pixels. While + grabbed, the X server and every other program get no touches; releasing the + grab gives them back. Requires read access to `/dev/input`: the user must be + in the `input` group (or an equivalent udev rule), as Fenrir already needs. + Cthulhu speaks a message once if access is denied. +- `internal/platform/xorg/touch.go`, `touch_native.c`, `touch_native.h`: the + only X11 parts. A `WindowLocator` on its own X connection finds the client + PID under a point (`_NET_WM_PID`, then XRes) and clicks with XTest for + activation. No XInput2 touch grab is used. +- `internal/touch`: pure Go gesture recognizer, no native code. Callers feed + timestamped contacts and call `Tick`. Recognizes 1 to 4 finger tap, double + tap, triple tap, hold, flicks in four directions, double tap and hold, two + finger rotation, and up to ten fingers. One finger held past 200 ms explores + instead of gesturing, so quick flicks never speak. Taps wait 350 ms for more + taps. Contact state is bounded at 64 and lifted slots are reused, so finger + bounces can never lose a lift. +- `internal/app/touch.go`: lifecycle service. Grabs only while + `Reading.EnableTouchScreen` is on and the focus gate is not locked. Hit tests + run in a separate worker that keeps only the latest point. +- Setting: `enable-touch-screen` in `[profiles..presentation.reading]`, + default off. Preferences checkbox "Use the touch screen with gestures" and + quick toggle "Touch screen". +- Keyboard: `toggle-touch-screen`, Cthulhu+Ctrl+Alt+T (as NVDA+Ctrl+Alt+T), + flips the quick toggle for the session and says "Touch screen on" or "off". + Saving speech settings keeps it. + +## Current gestures + +Gestures map to Cthulhu's keyboard commands, so touch and keyboard users +reach the same features. The mapping lives in `internal/app/touch_navigation.go` +as one table per mode, and every row below is tested in +`touch_navigation_test.go`. Rules from testers: within a mode every gesture +does one thing; shared gestures mean the same in every mode; every mode has +its own rotor and no two modes share a rotor list. Each mode remembers its +own rotor position. + +Shared by every mode: + +- One finger rest or drag: speak what is under the finger (line of text over + unnamed containers). Lifting moves object review there. Empty space says + "Blank" once until the finger reaches something; testers found silence + sounded broken. Crossing into another window, or off every window, says + that window's title (or "Desktop") first, once per crossing. +- One finger tap: speak it again. Double tap: activate what was last moved + (click an explored point, `object-activate` after an object move or Tab, + `document-activate` after a browse move). In speech settings mode, double + tap saves. +- Double tap and hold: right click an explored point, or press the context + menu key after an object move. +- Two finger tap: stop speech. Two finger triple tap: Escape. Two finger + rotate: the current mode's rotor. +- Three finger tap: next mode. Three finger flick right and left: Tab and + Shift+Tab. Down: `read-all`. Up: `present-window-title`. +- Four finger tap: `present-last-notification`. Double tap: + `show-notification-list`. + +Modes, in three finger tap order: + +- Navigation mode (default, like TalkBack): flick right and left + `object-next-item` and `object-previous-item`. Rotor chooses flick down and + up: Scroll (mouse wheel at the last touch), Windows and Workspaces (i3), or + Notifications (next and previous). +- Text mode: rotor chooses Lines, Words or Characters. Flick right and left + move by the unit, down reads the current one, up spells it (phonetic for + characters). Flat review commands. +- Browse mode: flick right and left move the browse cursor by line in page + order, like the Down and Up arrows. Rotor chooses headings, links, + buttons, form fields, landmarks, tables, lists, list items, paragraphs, + images, check boxes, combo boxes, radio buttons or clickables; flick down + and up move by it. Entered by itself on a + web page and left again with it, unless chosen by hand. +- Object mode: flick right and left siblings, up parent, down first child. + No rotor. +- Speech settings mode: flick right and left choose a setting, up and down + change it; the rotor changes category. + +Touch commands enter the keyboard command dispatch through +`commandRuntime.touchCommands`, so gestures behave exactly like the bound +keys. The three new commands have no default keys yet. + +Hit testing (`internal/atspi/mouse_review_native.go`, shared with mouse +review) now scans the children of the object where the provider's own hit +test stopped. Chromium stopped at tables, so cells were never reached. + +## Roadmap + +1. Done: direct touch screen input, recognizer, explore by touch, activate, stop speech. +2. Done: item navigation, rotor, web mode, Tab, Shift+Tab and Escape. + Still to add: Enter outside web mode. +3. Rotor done. Later: continuous rotation while turning, and per mode lists. +4. Desktop gestures through i3: switch windows and workspaces, launcher, + notifications. +5. Touch typing: an on-screen keyboard explored by finger, lift to type. + Braille screen input later. +6. Pass-through mode and double tap and hold pass-through for sliders and + drags; gesture remapping in preferences. + +## Open issues + +- Lock screen: Stormux enables I38lock by default on new installs. Touch is + turned off while the focus gate is locked, so a touch-only user cannot + unlock. Needs touch on the lock screen plus touch typing for the password. +- Activation clicks at the explored point. AT-SPI actions may be better for + some widgets. +- Only X11 is supported. Wayland needs a compositor protocol and is deferred. +- Coordinates map the whole touch range onto the X screen. Rotation (tablet + mode) and multiple monitors are not handled yet. +- Pass-through could use uinput to replay touches to the desktop as a virtual + touch screen. Not built yet. +- Packaging must tell users to join the `input` group. +- App survey on the test laptop (32 point hit test grid per window): + Shelly (Avalonia) exposes nothing; Mousepad reports one text object with no + text at the point; PCManFM list view and Thunar list view find file names; + GTK dialogs (Thunar preferences, Mumble wizard, preferred applications) + find labels, check boxes and combo boxes; qv4l2, qvidcap and tkremind opened + no window in time. +- Thunar's icon view exposes one empty panel and no items, so files cannot + be explored by touch there. Thunar's detailed list view exposes table rows + and cells. Hit testing now also searches up to three levels below where the + provider stops (GTK notebooks report page tabs as only their label). +- Tests in `internal/app` read the real session bus. When I38lock is active + they fail on an unchanged tree too. Run them under `dbus-run-session --`. + +## Testing + +- Automated: `python3 tests/native_test_session.py go test ./internal/touch ./internal/platform/evdev ./internal/i3command ./internal/review ./internal/app ./internal/config ./internal/preferences ./internal/platform/xorg -count=1`. + `internal/app` tests read the real session bus, so run them under + `dbus-run-session` or they fail while a screen lock is active. +- Native X11: `python3 tests/native_test_session.py env CTHULHU_NATIVE_X11=1 go test ./internal/platform/xorg -run "TestNativeWindowLocator|TestNativeTouchKey" -count=1` + (needs xterm, xdotool and xprop). Real touch device discovery: + `CTHULHU_NATIVE_EVDEV=1 go test ./internal/platform/evdev -run TestNativeFindTouchScreens`. +- Live: run `build/cthulhu --replace --config --debug-file ` + with `enable-touch-screen = true` in the copy, and keep a way back to the + installed reader. Use a separate settings file: the testing branch writes + settings schema 3, which master refuses to load. Touch gestures are logged + at debug level as `touch gesture`; silent explore points as + `touch review silent` with a reason. +- Testers used local helper scripts (switching between the test and + installed builds, a spoken gesture trainer, an app hit test survey). They + are not part of this repository. +- Test hardware: Lenovo Yoga 7 2-in-1 14AKP10, touch screen + "Wacom HID 53FC Finger", 10 touch points, 1920x1200, Stormux on XLibre + with i3, MATE and SonicDE. + +## Log + +- 2026-11-24: Spoken trainer passed all 29 gestures on the Yoga, including ten + fingers at once. Recognizer, X11 grab, explore by touch, double tap + activation and two finger stop speech added. Automated tests pass. Live + testing started with `cthulhu-switch test`. +- 2026-11-24: First live test in Brave. Explore by touch worked but was chatty + about unnamed containers and repeated link text. About a minute in, AT-SPI + speech stopped and the touch service later hung on shutdown; a reboot was + needed. The X server touch class on the core pointer had grown from 10 to 41, + so sequences may have leaked. Changes: touch accepts are flushed at once, + window lookups moved off the touch loop to the reviewer's own X connection, + explore hit tests limited to one per 40 ms and 3 px, mouse review stays quiet + for one second after touch input, unnamed containers and repeated names are + skipped. `cthulhu-switch` now records native and Go stacks of a test build + that does not hand over, and runs `touchcount` to log touch class sizes. +- 2026-11-24: Root cause of the freeze found with gdb: the window lookup held + the X11 guard and then called the XRes helpers, which take the same + non-recursive guard. The lookup deadlocked and every other X11 reader blocked + behind it, so AT-SPI speech stopped. It happened when the point had no + `_NET_WM_PID`, for example the screen edge. Fixed by running the XRes fallback + after releasing the guard and checking XRes support once per connection. + `TestNativeWindowLocatorFallbackReleasesGuard` reproduces it with an xterm + whose `_NET_WM_PID` is removed: it fails on the old code and passes now. +- 2026-11-24: Switched touch input from the XInput2 grab to evdev with + `EVIOCGRAB`, at the tester's request, so touch no longer depends on X11 + input handling. The test user was added to the `input` group. Tracker tests + cover one and two fingers, slot reuse, one-frame touches and `SYN_DROPPED`. +- 2026-11-24: Live test of direct input passed: explore, tap, double tap and + two finger stop speech work in Brave. Added item navigation (flick right + and left), explore committing to object review, and `object-activate` with + a preferred default action (click, press, activate, jump, open, toggle, + select). Item walk tests cover reading order, skipped containers, window + edges and `Cursor.Set`. +- 2026-11-24: Live test passed: flick right and left item navigation and double + tap activation after a flick work in Brave. +- 2026-11-24: Explore in Brave said only "Files, table" over a file list: + Chromium's hit test stopped at the table. Added the child scan fallback to + the shared hit test and line reading over unnamed containers. Added the + rotor, web mode, three finger mode switch, three finger Tab, and two finger + triple tap Escape. The native mouse review test still passes. +- 2026-11-24: Rotor works live. Tester feedback: web mode duplicated flicks + and rotor units. Removed modes; flicks are always items, the rotor picks + browse or flat review commands automatically, and the three finger tap is + free. +- 2026-11-24: Desktop mode (arrow key flicks) was hard to discover and was + dropped. Rebuilt the mapping on Cthulhu's keyboard commands and NVDA's touch + modes: object, text, speech settings and automatic browse mode; four finger + flicks for windows and workspaces; four finger taps for notifications. +- 2026-11-24: Switched the tester's Thunar to the detailed list view; a hit + test probe now finds file names (git, Projects, Videos). Browse mode can be + chosen by hand in any app. +- 2026-11-24: Added `toggle-touch-screen` (Cthulhu+Ctrl+Alt+T) and surveyed + twelve installed apps. +- 2026-11-24: Tester found object mode odd as a default and text mode weird. + Navigation mode is now the default; every mode has its own rotor, as one + table per mode; scrolling added. Four finger flicks were moved into the + navigation rotor so windows and workspaces live in one place. +- 2026-11-24: Settings saved in the test build were lost on restart because + `cthulhu-switch` copied the installed settings over them each time. The + test settings file is now kept. +- 2026-11-24: Browse mode flicks swapped at the tester's request: right and + left read in page order, down and up follow the rotor. +- 2026-11-24: MATE testing: the 24 pixel panels were too thin to find by + touch (the tester's MATE panels were raised to 64). Explore now says + "Blank" over empty space and names the window a finger crosses into. + +## Integration review and acceptance + +The integration fixes device retry starvation; uses scalar EVIOCGRAB arguments +for acquisition and release; decodes native input-event sizes and byte order; +rejects unsupported descriptors and slots; and cancels lost input instead of +turning it into a tap. After overflow the service releases and reopens the +device after five seconds to discard unknown slot state. Disable, lock and +device loss clear the activation point and retire pending exploration results. +Wayland sessions never grab a device. Synthesized keys preserve keys already +held by the user. Item traversal has an explicit ascent limit. Empty i3 replies +are failures and cancellation closes an outstanding command connection. + +Before pushing, build from testing and check on the touchscreen: + +1. Toggle with Cthulhu+Ctrl+Alt+T; explore, tap, double tap, rotate, and flick + through each mode. Check speech and Braille, including window boundaries. +2. Unplug/reconnect or enable before connecting the device. It should become + available after the retry interval. Toggle off/on; a double tap must not + activate an old point. Lock/unlock using the keyboard and repeat. +3. Hold either physical Shift while issuing touch Shift+Tab. Shift must remain + held until physically released; normal keyboard navigation must still work. +4. Check mouse review, GTK notebook pages, browser tables, browse navigation, + object navigation, and activation. Keep the reader responsive while moving + a finger rapidly over a large page. +5. Tab and Shift+Tab through the touch preferences checkbox, Apply, reopen, + and restart using the saved test configuration to verify persistence. + +Private automated tests do not establish physical touch, audible speech, +Braille, or preferences keyboard acceptance. The original contributor's live +results above are historical evidence, not verification of these review fixes. + +Validation for this integration: the full Go suite passed in a private +Xvfb/D-Bus session; focused touch/review/app race checks and focused go vet +passed; native mouse hit testing, XRes window lookup, and held-key preservation +passed. The reader, input helper, and BrlAPI-tagged Braille helper built. +Translation catalog checks and git diff whitespace checks passed. No running +reader was replaced and no physical touchscreen acceptance was performed. diff --git a/internal/app/app.go b/internal/app/app.go index 751eabc..6658cca 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -262,9 +262,15 @@ func Run(ctx context.Context, options Options) error { return settings } } + // Touch gestures enter the same command dispatch as keyboard commands. + touchCommands := make(chan input.CommandEvent, 8) if pointAdapter, ok := adapter.(pointReviewAdapter); ok { + touchInput := &touchActivity{} services = append(services, mouseReviewService(logger, pointAdapter, - gatedSpeech{speech: speechOutput, gate: focusGate}, brailleOutput, live, focusGate)) + gatedSpeech{speech: speechOutput, gate: focusGate}, brailleOutput, live, focusGate, touchInput)) + services = append(services, touchService(logger, pointAdapter, + gatedSpeech{speech: speechOutput, gate: focusGate}, brailleOutput, live, focusGate, touchInput, + objectReview, touchCommands, browser.Browsing)) } if speechMessages != nil { speechMessages.capitalization = func() (bool, bool) { @@ -415,6 +421,7 @@ func Run(ctx context.Context, options Options) error { onPreferences: options.onPreferences, onSpeechHistory: options.onSpeechHistory, onSpeechMonitor: options.onSpeechMonitor, onNotificationList: options.onNotificationList, tentacles: tentacles, ocr: ocrSession, objectReview: objectReview, notifications: notifications, stopRun: stopRun, + touchCommands: touchCommands, } commandWorker.actionSource, _ = adapter.(accessibleActionSource) workers := startRuntimeWorkers(ctx, commandWorker, inputListener, settings, backends.copyChanges, brailleOutput) diff --git a/internal/app/browser_mode.go b/internal/app/browser_mode.go index 934d74b..98fac3b 100644 --- a/internal/app/browser_mode.go +++ b/internal/app/browser_mode.go @@ -8,6 +8,7 @@ import ( "context" "errors" "sync" + "sync/atomic" "time" "git.stormux.org/storm/cthulhu/internal/atspi" @@ -60,6 +61,20 @@ type browserModeController struct { mode review.DocumentMode ready bool resolving bool + // browsing mirrors mode == BrowseMode for readers on other goroutines, + // such as touch navigation. + browsing atomic.Bool +} + +// setMode is the only writer of mode, so Browsing always matches it. +func (browser *browserModeController) setMode(mode review.DocumentMode) { + browser.mode = mode + browser.browsing.Store(mode == review.BrowseMode) +} + +// Browsing reports whether browse mode is active. Safe from any goroutine. +func (browser *browserModeController) Browsing() bool { + return browser != nil && browser.browsing.Load() } func newBrowserModeController(source any, keys browseKeyOwner, capturer documentContextCapturer) *browserModeController { @@ -170,7 +185,7 @@ func (browser *browserModeController) clear() { browser.generation++ browser.resolving = false browser.ready = false - browser.mode = review.InactiveMode + browser.setMode(review.InactiveMode) browser.state = review.DocumentModeState{} browser.invalidateCaptureContextLocked() browser.mutex.Unlock() @@ -215,7 +230,7 @@ func (browser *browserModeController) accept(result browserModeResult, speech sp browser.resolving = false if result.err != nil { browser.ready = false - browser.mode = review.InactiveMode + browser.setMode(review.InactiveMode) browser.keys.SetBrowseNavigation(false) return } @@ -255,7 +270,7 @@ func (browser *browserModeController) navigationMode(result review.Result, speec func (browser *browserModeController) set(mode review.DocumentMode, speech speechEnqueuer, manual bool) { previous := browser.mode - browser.mode = mode + browser.setMode(mode) browser.keys.SetBrowseNavigation(mode == review.BrowseMode) // Python starts web content in browse mode. Entering ordinary document // content is therefore silent; only an actual automatic mode change (for @@ -313,7 +328,7 @@ func (browser *browserModeController) navigated(position review.DocumentPosition browser.mutex.Unlock() browser.state = review.DocumentModeState{} browser.state.SetSticky(browser.stickyModes[browser.document.BusName]) - browser.mode = browser.state.Current() + browser.setMode(browser.state.Current()) browser.ready = true browser.keys.SetBrowseNavigation(browser.mode == review.BrowseMode) } @@ -357,7 +372,7 @@ func (browser *browserModeController) loaded(focus atspi.ObjectID) { browser.document = atspi.ObjectID{} browser.invalidateCaptureContextLocked() browser.mutex.Unlock() - browser.mode = review.InactiveMode + browser.setMode(review.InactiveMode) browser.state = review.DocumentModeState{} browser.follow(focus) } @@ -375,7 +390,7 @@ func (browser *browserModeController) loading() { browser.navigation = atspi.ObjectID{} browser.navigationDocument = atspi.ObjectID{} browser.navigationFocus = atspi.ObjectID{} - browser.mode = review.InactiveMode + browser.setMode(review.InactiveMode) browser.state = review.DocumentModeState{} browser.invalidateCaptureContextLocked() browser.mutex.Unlock() @@ -479,7 +494,7 @@ func (browser *browserModeController) sticky(mode review.DocumentMode, speech sp } browser.stickyModes[browser.document.BusName] = mode browser.state.SetSticky(mode) - browser.mode = mode + browser.setMode(mode) browser.keys.SetBrowseNavigation(mode == review.BrowseMode) text := "Browse mode is sticky." if mode == review.FocusMode { diff --git a/internal/app/event_review_results.go b/internal/app/event_review_results.go index bf40131..ff8e1f4 100644 --- a/internal/app/event_review_results.go +++ b/internal/app/event_review_results.go @@ -127,7 +127,10 @@ func (handler *eventReviewHandler) handle(result review.Result) { return } syncForeground() - if !state.current.ID().Valid() { + // Object review stands on its own position, which touch can set without + // any focus event, so its results do not need a known focus. + if !state.current.ID().Valid() && (result.Direction == 0 || result.FlatUnit != 0 || + result.DocumentTarget != 0 || result.DocumentCaretCommand != 0) { return } if result.WhereAmI { @@ -334,6 +337,10 @@ func objectReviewBoundaryMessage(direction review.Direction) string { return "No previous." case review.NextSibling: return "No next." + case review.PreviousItem: + return "No previous item." + case review.NextItem: + return "No next item." default: return "Could not find current location." } diff --git a/internal/app/learn_mode.go b/internal/app/learn_mode.go index e3c2676..549be79 100644 --- a/internal/app/learn_mode.go +++ b/internal/app/learn_mode.go @@ -156,6 +156,14 @@ func learnCommandDescription(command input.Command) string { return "Open the Emoji Menu" case input.ShowActions: return "Show the actions available for the current object" + case input.ObjectNextItem: + return "Move object review to the next item in reading order" + case input.ObjectPreviousItem: + return "Move object review to the previous item in reading order" + case input.ObjectActivate: + return "Activate the object under review with its default action" + case input.ToggleTouchScreen: + return "Turn touch screen gestures on or off" case input.ToggleLearnMode: return "Enter or exit learn mode." case input.ToggleCommandBypass: diff --git a/internal/app/mouse_review.go b/internal/app/mouse_review.go index 1482626..60ab770 100644 --- a/internal/app/mouse_review.go +++ b/internal/app/mouse_review.go @@ -79,7 +79,8 @@ func (state *mouseReviewState) presentation(point atspi.PointReview, settings co // Mouse review owns its pointer connection and last spoken item for one // enabled session. Only copied snapshots leave the AT-SPI owner thread. func mouseReviewService(logger *slog.Logger, adapter pointReviewAdapter, speech speechEnqueuer, - braille interface{ EnqueueMessage(string) bool }, live *liveSettings, gate *focusGate) lifecycle.Service { + braille interface{ EnqueueMessage(string) bool }, live *liveSettings, gate *focusGate, + touchInput *touchActivity) lifecycle.Service { var cancel context.CancelFunc var done chan struct{} return lifecycle.Service{Name: "mouse review", Start: func(ctx context.Context) error { @@ -116,6 +117,12 @@ func mouseReviewService(logger *slog.Logger, adapter pointReviewAdapter, speech state.clearItem(position) continue } + // The X server moves the pointer with the finger. Touch review + // speaks that object; follow the position here without speaking. + if touchInput.recent(touchQuietsMouseReview) { + state.clearItem(position) + continue + } if state.ready && position == state.position { continue } diff --git a/internal/app/object_activate.go b/internal/app/object_activate.go new file mode 100644 index 0000000..2472ce1 --- /dev/null +++ b/internal/app/object_activate.go @@ -0,0 +1,74 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "context" + "log/slog" + "strings" + "time" + + "git.stormux.org/storm/cthulhu/internal/atspi" + "git.stormux.org/storm/cthulhu/internal/i18n" + "git.stormux.org/storm/cthulhu/internal/review" +) + +// defaultActionNames lists what activating an object most likely means, in +// order. Providers name actions differently; the first listed one wins. +var defaultActionNames = []string{"click", "press", "activate", "jump", "open", "toggle", "select", + "expand or contract"} + +func chooseDefaultAction(actions []atspi.AccessibleAction) (string, bool) { + if len(actions) == 0 { + return "", false + } + for _, want := range defaultActionNames { + for _, action := range actions { + if strings.EqualFold(strings.TrimSpace(action.Name), want) { + return action.Name, true + } + } + } + return actions[0].Name, true +} + +// activateObjectOfInterest performs the default action of the object under +// review, or focus when nothing is under explicit review. It runs off the +// command loop so a slow provider never delays other commands. +func activateObjectOfInterest(ctx context.Context, logger *slog.Logger, worker *review.Worker, + source accessibleActionSource, speech speechEnqueuer, gate *focusGate) { + say := func(text string) { + speech.Enqueue(speechRequest{Text: text, Role: "system", Cause: "object-activate"}) + } + if worker == nil || source == nil { + say(i18n.T("Activation unavailable.")) + return + } + lookup, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + interest, err := worker.ObjectOfInterest(lookup) + var actions atspi.ActionSet + if err == nil { + actions, err = source.AccessibleActions(lookup, interest.Object) + } + name, ok := chooseDefaultAction(actions.Actions) + if err != nil || !ok { + if ctx.Err() == nil { + logger.Debug("object activation unavailable", "error", err) + say(i18n.T("No action available.")) + } + return + } + if ctx.Err() != nil || (gate != nil && gate.Locked()) { + return + } + if err := source.PerformAccessibleAction(lookup, actions.Target, name); err != nil { + if ctx.Err() == nil { + logger.Warn("object activation failed", "action", name, "error", err) + say(i18n.T("Could not activate.")) + } + return + } + logger.Debug("object activated", "action", name, "role", actions.Target.Role) +} diff --git a/internal/app/object_activate_test.go b/internal/app/object_activate_test.go new file mode 100644 index 0000000..74dacd4 --- /dev/null +++ b/internal/app/object_activate_test.go @@ -0,0 +1,33 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "testing" + + "git.stormux.org/storm/cthulhu/internal/atspi" +) + +func TestBehaviorDefaultActionPrefersActivationNames(t *testing.T) { + for _, tc := range []struct { + names []string + want string + ok bool + }{ + {nil, "", false}, + {[]string{"showMenu", "click"}, "click", true}, + {[]string{"jump"}, "jump", true}, + {[]string{"Press", "showMenu"}, "Press", true}, + {[]string{"customThing"}, "customThing", true}, + } { + actions := make([]atspi.AccessibleAction, len(tc.names)) + for i, name := range tc.names { + actions[i] = atspi.AccessibleAction{Name: name} + } + got, ok := chooseDefaultAction(actions) + if got != tc.want || ok != tc.ok { + t.Errorf("actions %v: got %q %v, want %q %v", tc.names, got, ok, tc.want, tc.ok) + } + } +} diff --git a/internal/app/runtime_commands.go b/internal/app/runtime_commands.go index ad5ab04..1ba3439 100644 --- a/internal/app/runtime_commands.go +++ b/internal/app/runtime_commands.go @@ -57,11 +57,50 @@ type commandRuntime struct { ocr *ocrSession notifications *notification.Presenter stopRun context.CancelFunc + // touchCommands carries touch gestures; they are dispatched exactly like + // keyboard commands. + touchCommands <-chan input.CommandEvent +} + +// mergeTouchCommands forwards keyboard and touch commands into one channel +// owned by the command loop. Without touch it returns the keyboard channel. +func mergeTouchCommands(ctx context.Context, keyboard, touch <-chan input.CommandEvent) <-chan input.CommandEvent { + if touch == nil { + return keyboard + } + merged := make(chan input.CommandEvent) + go func() { + for keyboard != nil || touch != nil { + var event input.CommandEvent + var ok bool + select { + case <-ctx.Done(): + return + case event, ok = <-keyboard: + if !ok { + keyboard = nil + continue + } + case event, ok = <-touch: + if !ok { + touch = nil + continue + } + } + select { + case merged <- event: + case <-ctx.Done(): + return + } + } + }() + return merged } func (worker commandRuntime) run(ctx context.Context) error { logger := worker.logger commands := worker.commands + commandEvents := mergeTouchCommands(ctx, commands.Commands(), worker.touchCommands) focusChanges := worker.focusChanges focusGate := worker.focusGate speechMessages := worker.speechMessages @@ -127,7 +166,7 @@ func (worker commandRuntime) run(ctx context.Context) error { focusGate.dismissConfirmation() speechOutput.Enqueue(speechRequest{Text: state.Text(), Role: "system", Cause: "lock-state"}) logger.Debug("keyboard lock state changed", "key", state.Name, "locked", state.Locked) - case event := <-commands.Commands(): + case event := <-commandEvents: focusGate.retireTentacleOutput() if focusGate.Locked() { continue @@ -205,7 +244,7 @@ func (worker commandRuntime) run(ctx context.Context) error { default: } } - case input.SelectPreviousSpeechSetting, input.SelectNextSpeechSetting, input.DecreaseSpeechSetting, input.IncreaseSpeechSetting, input.SelectPreviousSpeechCategory, input.SelectNextSpeechCategory, input.SaveSpeechSettings, input.CycleProgressBarOutput: + case input.SelectPreviousSpeechSetting, input.SelectNextSpeechSetting, input.DecreaseSpeechSetting, input.IncreaseSpeechSetting, input.SelectPreviousSpeechCategory, input.SelectNextSpeechCategory, input.SaveSpeechSettings, input.CycleProgressBarOutput, input.ToggleTouchScreen: logger.Debug("speech setting command received", "command", command) preferences.SpeechCommand(command) case input.Preferences: @@ -283,6 +322,12 @@ func (worker commandRuntime) run(ctx context.Context) error { queueObjectReviewMove(logger, objectReview, review.PreviousSibling) case input.ObjectNextSibling: queueObjectReviewMove(logger, objectReview, review.NextSibling) + case input.ObjectNextItem: + queueObjectReviewMove(logger, objectReview, review.NextItem) + case input.ObjectPreviousItem: + queueObjectReviewMove(logger, objectReview, review.PreviousItem) + case input.ObjectActivate: + go activateObjectOfInterest(ctx, logger, objectReview, worker.actionSource, speechOutput, focusGate) case input.DocumentActivate: if objectReview != nil { if err := objectReview.ActivateDocumentCaret(); err != nil { diff --git a/internal/app/speech_settings.go b/internal/app/speech_settings.go index 4e4bbdd..8b8fb50 100644 --- a/internal/app/speech_settings.go +++ b/internal/app/speech_settings.go @@ -48,6 +48,10 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman worker.cycleProgressOutput() return } + if command == input.ToggleTouchScreen { + worker.toggleQuickSetting(ctx, "reading.touch-screen", "Touch screen") + return + } ctx, cancel := context.WithTimeout(ctx, 6*time.Second) defer cancel() if command == input.SaveSpeechSettings { @@ -89,6 +93,28 @@ func (worker *preferencesWorker) handleSpeechCommand(ctx context.Context, comman worker.announceSpeechSetting(result.Text) } +// toggleQuickSetting flips one boolean quick setting from a direct command, +// exactly as choosing it in the speech settings menu would: for this session +// until speech settings are saved. +func (worker *preferencesWorker) toggleQuickSetting(ctx context.Context, id, label string) { + toggle, ok := quickToggleByID(id) + if !ok { + return + } + host := &quickSettingsHost{worker: worker, ctx: ctx, settings: worker.effectiveSettings(worker.settings)} + enabled := !*toggle.field(&host.settings) + result := quicksettings.Result{Entry: quicksettings.Entry{ID: id, Label: label, Kind: quicksettings.Toggle}, + Value: quicksettings.Value{Checked: enabled}, Changed: true, Available: true} + if !worker.applyQuickSetting(ctx, host, result) { + return + } + if enabled { + worker.announceSpeechSetting(label + " on") + } else { + worker.announceSpeechSetting(label + " off") + } +} + // quickVoiceStep matches Fenrir: 5% of Speech Dispatcher's -100..100 scale. const quickVoiceStep = 10 @@ -118,6 +144,7 @@ var quickReadingToggles = []quickToggle{ {"reading.color-names", "Use color names", func(s *config.Settings) *bool { return &s.Reading.UseColorNames }}, {"reading.tooltips", "Present tooltips", func(s *config.Settings) *bool { return &s.Reading.PresentTooltips }}, {"reading.mouse-review", "Mouse review", func(s *config.Settings) *bool { return &s.Reading.EnableMouseReview }}, + {"reading.touch-screen", "Touch screen", func(s *config.Settings) *bool { return &s.Reading.EnableTouchScreen }}, {"reading.clipboard-changes", "Automatically read clipboard changes", func(s *config.Settings) *bool { return &s.Reading.AutomaticallyReadClipboardChanges }}, {"reading.title-changes", "Automatically read title changes", func(s *config.Settings) *bool { return &s.Reading.AutomaticallyReadTitleChanges }}, {"reading.tutorial-messages", "Tutorial messages", func(s *config.Settings) *bool { return &s.Reading.EnableTutorialMessages }}, diff --git a/internal/app/speech_settings_test.go b/internal/app/speech_settings_test.go index 572fb47..26e2230 100644 --- a/internal/app/speech_settings_test.go +++ b/internal/app/speech_settings_test.go @@ -660,3 +660,25 @@ func TestQuickSpeechLanguageFiltersVoicesAndKeepsDefaultLanguage(t *testing.T) { t.Fatal("language default did not reset selection", applied) } } + +func TestToggleTouchScreenCommandFlipsTheSessionSetting(t *testing.T) { + settings := config.DefaultSettings() + worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, settingsUpdateFunc(func(context.Context, speech.Settings) error { + return nil + })) + worker.catalog = speech.Catalog{"": {{Name: "default", Language: "en"}}} + worker.live = &liveSettings{} + worker.live.Store(settings) + var messages []string + worker.announce = func(text string) { messages = append(messages, text) } + worker.handleSpeechCommand(t.Context(), input.ToggleTouchScreen) + if !worker.live.Load().Reading.EnableTouchScreen || !worker.globalSettings.Reading.EnableTouchScreen || + messages[len(messages)-1] != "Touch screen on" { + t.Fatalf("first toggle: live %v, global %v, said %q", worker.live.Load().Reading.EnableTouchScreen, + worker.globalSettings.Reading.EnableTouchScreen, messages[len(messages)-1]) + } + worker.handleSpeechCommand(t.Context(), input.ToggleTouchScreen) + if worker.live.Load().Reading.EnableTouchScreen || messages[len(messages)-1] != "Touch screen off" { + t.Fatalf("second toggle: live %v, said %q", worker.live.Load().Reading.EnableTouchScreen, messages[len(messages)-1]) + } +} diff --git a/internal/app/touch.go b/internal/app/touch.go new file mode 100644 index 0000000..68919ba --- /dev/null +++ b/internal/app/touch.go @@ -0,0 +1,525 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "context" + "log/slog" + "strings" + "sync/atomic" + "time" + + "git.stormux.org/storm/cthulhu/internal/i18n" + "git.stormux.org/storm/cthulhu/internal/i3command" + "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/cthulhu/internal/lifecycle" + "git.stormux.org/storm/cthulhu/internal/platform/evdev" + "git.stormux.org/storm/cthulhu/internal/platform/session" + "git.stormux.org/storm/cthulhu/internal/platform/xorg" + "git.stormux.org/storm/cthulhu/internal/review" + "git.stormux.org/storm/cthulhu/internal/touch" +) + +const ( + touchPollInterval = 30 * time.Millisecond + touchRetryInterval = 5 * time.Second + // Explore hit tests are limited so a moving finger cannot flood the + // AT-SPI owner. The newest position always wins. + touchExploreInterval = 40 * time.Millisecond + touchExploreMinMove = 3 + // Mouse review stays quiet this long after touch input, because an + // activation click moves the pointer briefly. + touchQuietsMouseReview = time.Second +) + +// touchActivity records the last touch input so mouse review can stay quiet. +type touchActivity struct{ last atomic.Int64 } + +func (activity *touchActivity) mark() { + if activity != nil { + activity.last.Store(time.Now().UnixNano()) + } +} + +func (activity *touchActivity) recent(window time.Duration) bool { + if activity == nil { + return false + } + last := activity.last.Load() + return last != 0 && time.Since(time.Unix(0, last)) < window +} + +// touchPoint is one hit test request. Force speaks the object even when it is +// the one already spoken, as a tap asks for. Commit also moves object review +// to the object, so flicks continue from where the finger lifted. +type touchPoint struct { + x, y int + force, commit bool + generation uint64 +} + +// touchReviewer speaks what is under the finger. It owns its own last spoken +// state, separate from mouse review, and its own X connection for finding the +// window under a point. While one hit test runs, newer points replace older +// waiting ones. +type touchReviewer struct { + logger *slog.Logger + adapter pointReviewAdapter + speech speechEnqueuer + braille interface{ EnqueueMessage(string) bool } + live *liveSettings + gate *focusGate + review *review.Worker + // browsing reports whether browse mode is active on a web page. + browsing func() bool + points chan touchPoint + generation atomic.Uint64 +} + +func (reviewer *touchReviewer) request(point touchPoint) { + point.generation = reviewer.generation.Load() + for { + select { + case reviewer.points <- point: + return + default: + } + select { + case old := <-reviewer.points: + if old.generation == point.generation { + point.force = point.force || old.force + point.commit = point.commit || old.commit + } + default: + } + } +} + +func (reviewer *touchReviewer) run(ctx context.Context) { + locator := xorg.OpenWindowLocator() + if locator == nil { + reviewer.logger.Warn("touch review window locator unavailable") + } + defer locator.Close() + var state mouseReviewState + state.clearItem(xorg.PointerPosition{}) + lastName := "" + // Silence over empty space sounds like a broken screen reader, so empty + // space says "Blank" once, until the finger reaches something again. + blank := false + // Crossing into another window says its title first, so a finger that + // slides off one app always knows where it landed. + var lastWindow uint64 + windowKnown := false + var lastGeneration uint64 + entered := "" + withWindow := func(text string) string { + if entered == "" { + return text + } + text, entered = entered+", "+text, "" + return text + } + sayBlank := func(reason string, point touchPoint) { + if ctx.Err() != nil || point.generation != reviewer.generation.Load() || !reviewer.live.Load().Reading.EnableTouchScreen || reviewer.gate.Locked() { + return + } + reviewer.logger.Debug("touch review blank", "reason", reason, "x", point.x, "y", point.y) + state.clearItem(xorg.PointerPosition{}) + lastName = "" + if blank && !point.force && entered == "" { + return + } + blank = true + text := withWindow(i18n.T("Blank")) + reviewer.speech.Interrupt() + reviewer.speech.Enqueue(speechRequest{Text: text, Role: "system", Cause: "touch-review"}) + reviewer.braille.EnqueueMessage(text) + } + for { + var point touchPoint + select { + case <-ctx.Done(): + return + case point = <-reviewer.points: + } + if point.generation != reviewer.generation.Load() || ctx.Err() != nil || !reviewer.live.Load().Reading.EnableTouchScreen || reviewer.gate.Locked() { + continue + } + if point.generation != lastGeneration { + state.clearItem(xorg.PointerPosition{}) + lastName, entered, blank, windowKnown = "", "", false, false + lastGeneration = point.generation + } + pid, window := locator.WindowAt(point.x, point.y) + if !windowKnown || window != lastWindow { + title := i18n.T("Desktop") + if window != 0 { + if title = locator.WindowTitle(window); title == "" { + title = i18n.T("Window") + } + } + // The first touch after starting has no window to leave. + if windowKnown { + entered = title + } + lastWindow, windowKnown = window, true + state.clearItem(xorg.PointerPosition{}) + lastName = "" + } + if pid <= 0 { + sayBlank("no window", point) + continue + } + if point.force { + state.clearItem(xorg.PointerPosition{}) + lastName = "" + } + started := time.Now() + queryCtx, stop := context.WithTimeout(ctx, 2*time.Second) + hit, err := reviewer.adapter.ReviewAtPoint(queryCtx, point.x, point.y, pid) + stop() + elapsed := time.Since(started) + if err != nil { + if ctx.Err() == nil { + reviewer.logger.Debug("touch review hit test", "error", err, "ms", elapsed.Milliseconds()) + } + continue + } + if elapsed > 500*time.Millisecond { + reviewer.logger.Debug("touch review hit test slow", "ms", elapsed.Milliseconds(), "pid", pid) + } + // A newer point is waiting: its answer matters more than this one. + if len(reviewer.points) > 0 && !point.force && !point.commit { + continue + } + settings := reviewer.live.Load() + if point.generation != reviewer.generation.Load() || ctx.Err() != nil || !settings.Reading.EnableTouchScreen || reviewer.gate.Locked() { + continue + } + snapshot := hit.Snapshot + if !snapshot.ID().Valid() { + sayBlank("no object", point) + continue + } + if review.ItemSkips(snapshot) { + // An unnamed container says nothing useful, but the text under the + // finger does: exploring is for reading what is there. + if line := strings.TrimSpace(hit.Line); line != "" && line != state.spoken { + state.spoken, state.last = line, hit + text := withWindow(line) + reviewer.speech.Interrupt() + reviewer.speech.Enqueue(speechRequest{Text: text, Cause: "touch-review"}) + reviewer.braille.EnqueueMessage(text) + blank = false + reviewer.logger.Debug("touch review line", "role", snapshot.Role, "x", point.x, "y", point.y, "speech", line) + continue + } + if strings.TrimSpace(hit.Line) == "" { + sayBlank("empty "+snapshot.Role, point) + continue + } + if !point.force { + continue + } + } else if point.commit && reviewer.review != nil { + if err := reviewer.review.ReviewObject(snapshot.ID()); err != nil { + reviewer.logger.Debug("touch review object", "error", err) + } + } + // Moving from a link onto the text inside it names the same thing. + name := strings.TrimSpace(snapshot.Name) + if !point.force && name != "" && name == lastName && snapshot.ID() != state.last.Snapshot.ID() { + state.last = hit + continue + } + spoken := state.presentation(hit, settings) + if spoken.Text == "" { + reviewer.logger.Debug("touch review silent", "reason", "nothing new", "role", snapshot.Role, + "name", snapshot.Name, "line", hit.Line, "x", point.x, "y", point.y) + continue + } + if name != "" { + lastName = name + } + blank = false + chunks := spoken.Chunks + if entered != "" { + spoken.Text, chunks = withWindow(spoken.Text), nil + } + reviewer.speech.Interrupt() + reviewer.speech.Enqueue(speechRequest{Text: spoken.Text, Chunks: chunks, + Role: snapshot.Role, Cause: "touch-review"}) + reviewer.braille.EnqueueMessage(spoken.Text) + reviewer.logger.Debug("touch review presentation", "bus", snapshot.BusName, + "path", snapshot.Path, "x", point.x, "y", point.y, "ms", elapsed.Milliseconds(), "speech", spoken.Text) + } +} + +// touchService owns the evdev touch grab while the touch screen setting is +// on and the session is not locked. When it is off, touches go to applications. +func touchService(logger *slog.Logger, adapter pointReviewAdapter, speech speechEnqueuer, + braille interface{ EnqueueMessage(string) bool }, live *liveSettings, gate *focusGate, + activity *touchActivity, objectReview *review.Worker, commands chan<- input.CommandEvent, + browsing func() bool) lifecycle.Service { + if browsing == nil { + browsing = func() bool { return false } + } + var cancel context.CancelFunc + var done chan struct{} + return lifecycle.Service{Name: "touch screen", Start: func(ctx context.Context) error { + ctx, cancel = context.WithCancel(ctx) + done = make(chan struct{}) + reviewer := &touchReviewer{logger: logger, adapter: adapter, speech: speech, braille: braille, + live: live, gate: gate, review: objectReview, browsing: browsing, points: make(chan touchPoint, 1)} + reviewerDone := make(chan struct{}) + go func() { + defer close(reviewerDone) + reviewer.run(ctx) + }() + go func() { + defer close(done) + defer func() { <-reviewerDone }() + runTouchScreen(ctx, logger, reviewer, speech, activity, commands) + }() + return nil + }, Stop: func(ctx context.Context) error { + if cancel != nil { + cancel() + } + if done != nil { + select { + case <-done: + case <-ctx.Done(): + return ctx.Err() + } + } + return nil + }} +} + +// runTouchScreen reads the touch screen directly from the Linux input layer +// and recognizes gestures. The device is grabbed only while touch is on, so +// otherwise the desktop gets touches as usual. Hit tests and speech happen in +// the reviewer so this loop never waits on AT-SPI or speech while touches are +// arriving. Activation clicks use this loop's own X connection. +func runTouchScreen(ctx context.Context, logger *slog.Logger, reviewer *touchReviewer, + speech speechEnqueuer, activity *touchActivity, commands chan<- input.CommandEvent) { + if session.Wayland() { + logger.Info("touch screen requires an X11 session") + return + } + var screen *evdev.TouchScreen + var locator *xorg.WindowLocator + defer func() { + screen.Close() + locator.Close() + }() + var recognizer *touch.Recognizer + nav := newTouchNavigation() + var retryAt time.Time + epoch := time.Now() + toldDenied := false + + haveExplored := false + var exploredX, exploredY int + command := func(name input.Command) { + select { + case commands <- input.CommandEvent{Command: name}: + default: + logger.Warn("touch command dropped", "command", name) + } + } + // Explore positions waiting for the next allowed hit test. + exploreWaiting := false + var waitX, waitY, sentX, sentY int + var sentAt time.Time + + release := func() { + reviewer.generation.Add(1) + if screen != nil { + screen.Close() + screen = nil + logger.Info("touch screen released") + } + exploreWaiting = false + haveExplored = false + nav = newTouchNavigation() + sentAt = time.Time{} + if recognizer != nil { + recognizer.Reset() + } + } + idle := func() bool { + select { + case <-ctx.Done(): + return false + case <-time.After(250 * time.Millisecond): + return true + } + } + open := func() bool { + if locator == nil { + locator = xorg.OpenWindowLocator() + if locator == nil { + logger.Warn("touch screen needs an X display for activation") + return false + } + } + devices, denied := evdev.FindTouchScreens() + if len(devices) == 0 { + if denied && !toldDenied { + toldDenied = true + logger.Warn("touch screen unreadable: add the user to the input group") + speech.Enqueue(speechRequest{Text: i18n.T("Touch screen needs input group access. Add your user to the input group and log in again."), Cause: "touch-screen"}) + } + return false + } + width, height := locator.ScreenSize() + if width <= 0 || height <= 0 { + return false + } + opened, err := evdev.Open(devices[0], width, height) + if err != nil { + logger.Warn("touch screen open failed", "device", devices[0].Path, "error", err) + return false + } + screen = opened + recognizer = touch.New(touch.DefaultConfig(width)) + logger.Info("touch screen grabbed", "device", screen.Device.Path, "name", screen.Device.Name, + "slots", screen.Device.Slots, "width", width, "height", height) + return true + } + for ctx.Err() == nil { + settings := reviewer.live.Load() + if ctx.Err() != nil || !settings.Reading.EnableTouchScreen || reviewer.gate.Locked() { + release() + if !idle() { + return + } + continue + } + if screen == nil { + if !time.Now().Before(retryAt) { + if !open() { + retryAt = time.Now().Add(touchRetryInterval) + } + } + if screen == nil { + if !idle() { + return + } + continue + } + } + + contact, ok, failed := screen.Next(touchPollInterval) + if failed { + logger.Warn("touch screen lost", "device", screen.Device.Path) + release() + retryAt = time.Now().Add(touchRetryInterval) + continue + } + if ctx.Err() != nil || !reviewer.live.Load().Reading.EnableTouchScreen || reviewer.gate.Locked() { + release() + continue + } + now := time.Since(epoch) + var outputs []touch.Output + if ok { + activity.mark() + outputs = recognizer.Feed(touch.Event{Phase: touch.Phase(contact.Phase), ID: contact.ID, + X: contact.X, Y: contact.Y, At: now}) + } + outputs = append(outputs, recognizer.Tick(now)...) + for _, output := range outputs { + switch output.Type { + case touch.ExploreOutput: + waitX, waitY, exploreWaiting = int(output.X), int(output.Y), true + haveExplored, exploredX, exploredY = true, waitX, waitY + nav.explored() + case touch.ExploreEndOutput: + // Where the finger lifted becomes the object under review. + x, y := int(output.X), int(output.Y) + exploreWaiting = false + reviewer.request(touchPoint{x: x, y: y, commit: true}) + haveExplored, exploredX, exploredY = true, x, y + // The next explore always speaks its first position. + sentAt = time.Time{} + case touch.GestureOutput: + gesture := output.Gesture + logger.Debug("touch gesture", "gesture", gesture.Kind.String(), "fingers", gesture.Fingers, + "x", int(gesture.X), "y", int(gesture.Y)) + action := nav.gesture(gesture, reviewer.browsing()) + switch { + case action.speakAtPoint: + x, y := int(gesture.X), int(gesture.Y) + exploreWaiting = false + reviewer.request(touchPoint{x: x, y: y, force: true, commit: true}) + sentX, sentY, sentAt = x, y, time.Now() + haveExplored, exploredX, exploredY = true, x, y + case action.clickPoint, action.rightClickPoint: + button := 1 + if action.rightClickPoint { + button = 3 + } + if haveExplored && !locator.Click(exploredX, exploredY, button) { + logger.Warn("touch click failed", "x", exploredX, "y", exploredY, "button", button) + } + case action.stopSpeech: + speech.Interrupt() + case action.scroll != 0: + // Scroll what is under the last touch, or the screen centre. + x, y := exploredX, exploredY + if !haveExplored { + width, height := locator.ScreenSize() + x, y = width/2, height/2 + } + if !locator.Scroll(x, y, action.scroll) { + logger.Warn("touch scroll failed", "x", x, "y", y) + } + case action.i3 != "": + // i3 replies quickly, but never make touch input wait on it. + go func(name string) { + runCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + if err := i3command.Run(runCtx, xorg.I3Socket(), name); err != nil && ctx.Err() == nil { + logger.Debug("touch desktop command", "command", name, "error", err) + speech.Enqueue(speechRequest{Text: i18n.T("Not available"), Role: "system", Cause: "touch-mode"}) + } + }(action.i3) + case action.command != "": + command(action.command) + case action.key != touchNoKey: + sent := false + switch action.key { + case touchKeyTab: + sent = locator.Key(xorg.KeyTab, false) + case touchKeyShiftTab: + sent = locator.Key(xorg.KeyTab, true) + case touchKeyEscape: + sent = locator.Key(xorg.KeyEscape, false) + case touchKeyMenu: + sent = locator.Key(xorg.KeyMenu, false) + } + if !sent { + logger.Warn("touch key failed", "key", int(action.key)) + } + } + if action.announce != "" { + speech.Interrupt() + speech.Enqueue(speechRequest{Text: action.announce, Role: "system", Cause: "touch-mode"}) + } + } + } + if exploreWaiting && time.Since(sentAt) >= touchExploreInterval { + exploreWaiting = false + dx, dy := waitX-sentX, waitY-sentY + if dx*dx+dy*dy >= touchExploreMinMove*touchExploreMinMove || sentAt.IsZero() { + reviewer.request(touchPoint{x: waitX, y: waitY}) + sentX, sentY, sentAt = waitX, waitY, time.Now() + } + } + } +} diff --git a/internal/app/touch_navigation.go b/internal/app/touch_navigation.go new file mode 100644 index 0000000..cdc0051 --- /dev/null +++ b/internal/app/touch_navigation.go @@ -0,0 +1,324 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "git.stormux.org/storm/cthulhu/internal/i18n" + "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/cthulhu/internal/touch" +) + +// Touch gestures map to Cthulhu's keyboard commands so a touch user and a +// keyboard user reach the same features. Rules, from tester feedback: +// - Within a mode, every gesture does one thing. +// - Gestures shared by all modes mean the same thing everywhere. +// - Every mode has its own rotor: turning two fingers chooses what that +// mode's flicks do, and no two modes share a rotor list. +// See docs/touch-support.md for the full table. + +// touchMode decides what flicks and the rotor do. A three finger tap moves to +// the next mode. +type touchMode int + +const ( + // touchNavigationMode is the default, like TalkBack: flick right and left + // move item by item; the rotor chooses what flick down and up do. + touchNavigationMode touchMode = iota + // touchTextMode reviews screen text by the rotor's unit. + touchTextMode + // touchBrowseMode reads a web page: right and left in page order, down + // and up by the rotor's element type. It is entered by itself when browse + // mode becomes active. + touchBrowseMode + // touchObjectMode walks the object tree: siblings, parent and children. + touchObjectMode + // touchSpeechMode chooses and changes speech settings. + touchSpeechMode + touchModeCount +) + +func (mode touchMode) label() string { + return i18n.T([...]string{"Navigation mode", "Text mode", "Browse mode", "Object mode", + "Speech settings mode"}[mode]) +} + +// touchFlick names one flick. +type touchFlick struct { + kind touch.Kind + fingers int +} + +var ( + flickRight = touchFlick{touch.FlickRight, 1} + flickLeft = touchFlick{touch.FlickLeft, 1} + flickDown = touchFlick{touch.FlickDown, 1} + flickUp = touchFlick{touch.FlickUp, 1} +) + +// touchKey is a key press synthesized for a gesture. +type touchKey int + +const ( + touchNoKey touchKey = iota + touchKeyTab + touchKeyShiftTab + touchKeyEscape + touchKeyMenu // the context menu key +) + +// touchAction is what one recognized gesture asks for. +type touchAction struct { + command input.Command + key touchKey + i3 string // a window-management command, such as "workspace next" + scroll int // mouse wheel steps at the explored point: positive is down + announce string + // clickPoint and rightClickPoint act at the explored point. + clickPoint, rightClickPoint bool + stopSpeech bool + speakAtPoint bool // a one finger tap +} + +func touchCmd(command input.Command) touchAction { return touchAction{command: command} } + +// touchRotorUnit is one rotor choice: a name and what it makes flicks do. +type touchRotorUnit struct { + label string + flicks map[touchFlick]touchAction +} + +// touchModeSetup is one mode: flicks that never change, plus its own rotor. +type touchModeSetup struct { + flicks map[touchFlick]touchAction + rotor []touchRotorUnit +} + +var touchModes = [touchModeCount]touchModeSetup{ + touchNavigationMode: { + flicks: map[touchFlick]touchAction{ + flickRight: touchCmd(input.ObjectNextItem), flickLeft: touchCmd(input.ObjectPreviousItem), + }, + rotor: []touchRotorUnit{ + {"Scroll", map[touchFlick]touchAction{flickDown: {scroll: 3}, flickUp: {scroll: -3}}}, + {"Windows", map[touchFlick]touchAction{flickDown: {i3: "focus next"}, flickUp: {i3: "focus prev"}}}, + {"Workspaces", map[touchFlick]touchAction{flickDown: {i3: "workspace next"}, flickUp: {i3: "workspace prev"}}}, + {"Notifications", map[touchFlick]touchAction{ + flickDown: touchCmd(input.PresentNextNotification), flickUp: touchCmd(input.PresentPreviousNotification)}}, + }, + }, + touchTextMode: { + rotor: []touchRotorUnit{ + {"Lines", map[touchFlick]touchAction{ + flickRight: touchCmd(input.ReviewNextLine), flickLeft: touchCmd(input.ReviewPreviousLine), + flickDown: touchCmd(input.ReviewCurrentLine), flickUp: touchCmd(input.ReviewSpellLine)}}, + {"Words", map[touchFlick]touchAction{ + flickRight: touchCmd(input.ReviewNextWord), flickLeft: touchCmd(input.ReviewPreviousWord), + flickDown: touchCmd(input.ReviewCurrentWord), flickUp: touchCmd(input.ReviewSpellWord)}}, + {"Characters", map[touchFlick]touchAction{ + flickRight: touchCmd(input.ReviewNextCharacter), flickLeft: touchCmd(input.ReviewPreviousCharacter), + flickDown: touchCmd(input.ReviewCurrentCharacter), flickUp: touchCmd(input.ReviewPhoneticCharacter)}}, + }, + }, + touchBrowseMode: { + // Right and left read in page order, like the Down and Up arrows in + // browse mode; down and up move by the rotor's element type. + flicks: map[touchFlick]touchAction{ + flickRight: touchCmd(input.DocumentCaretNextLine), flickLeft: touchCmd(input.DocumentCaretPreviousLine), + }, + rotor: browseRotor([]struct { + label string + next, previous input.Command + }{ + {"Headings", input.DocumentNextHeading, input.DocumentPreviousHeading}, + {"Links", input.DocumentNextLink, input.DocumentPreviousLink}, + {"Buttons", input.DocumentNextButton, input.DocumentPreviousButton}, + {"Form fields", input.DocumentNextFormField, input.DocumentPreviousFormField}, + {"Landmarks", input.DocumentNextLandmark, input.DocumentPreviousLandmark}, + {"Tables", input.DocumentNextTable, input.DocumentPreviousTable}, + {"Lists", input.DocumentNextList, input.DocumentPreviousList}, + {"List items", input.DocumentNextListItem, input.DocumentPreviousListItem}, + {"Paragraphs", input.DocumentNextParagraph, input.DocumentPreviousParagraph}, + {"Images", input.DocumentNextImage, input.DocumentPreviousImage}, + {"Check boxes", input.DocumentNextCheckBox, input.DocumentPreviousCheckBox}, + {"Combo boxes", input.DocumentNextComboBox, input.DocumentPreviousComboBox}, + {"Radio buttons", input.DocumentNextRadioButton, input.DocumentPreviousRadioButton}, + {"Clickables", input.DocumentNextClickable, input.DocumentPreviousClickable}, + }), + }, + touchObjectMode: { + flicks: map[touchFlick]touchAction{ + flickRight: touchCmd(input.ObjectNextSibling), flickLeft: touchCmd(input.ObjectPreviousSibling), + flickUp: touchCmd(input.ObjectParent), flickDown: touchCmd(input.ObjectFirstChild), + }, + }, + touchSpeechMode: { + // The rotor here moves between Cthulhu's own setting categories. + flicks: map[touchFlick]touchAction{ + flickRight: touchCmd(input.SelectNextSpeechSetting), flickLeft: touchCmd(input.SelectPreviousSpeechSetting), + flickUp: touchCmd(input.IncreaseSpeechSetting), flickDown: touchCmd(input.DecreaseSpeechSetting), + }, + }, +} + +func browseRotor(units []struct { + label string + next, previous input.Command +}) []touchRotorUnit { + rotor := make([]touchRotorUnit, len(units)) + for i, unit := range units { + rotor[i] = touchRotorUnit{unit.label, map[touchFlick]touchAction{ + flickDown: touchCmd(unit.next), flickUp: touchCmd(unit.previous)}} + } + return rotor +} + +// touchLast records what the user last moved, so a double tap activates it. +type touchLast int + +const ( + touchLastNone touchLast = iota + touchLastPoint // explored with a finger: click where it was + touchLastObject // an object, review or focus: its default action + touchLastBrowse // the browse mode cursor on a web page +) + +// touchNavigation maps gestures to actions and owns the mode and each +// mode's rotor position. It has no devices or speech, so it is testable. +type touchNavigation struct { + mode touchMode + rotor [touchModeCount]int + last touchLast + wasBrowsing bool + // autoBrowse is set when browse mode was entered by itself; only then + // does leaving the web page leave it. + autoBrowse bool +} + +func newTouchNavigation() *touchNavigation { return &touchNavigation{} } + +// explored records that a finger explored or tapped a point. +func (nav *touchNavigation) explored() { nav.last = touchLastPoint } + +// follow enters browse mode when a web page gains browse mode and leaves it +// when browse mode ends, as NVDA does, unless the user chose it by hand. +func (nav *touchNavigation) follow(browsing bool) { + if browsing && !nav.wasBrowsing { + nav.mode, nav.autoBrowse = touchBrowseMode, true + } else if !browsing && nav.mode == touchBrowseMode && nav.autoBrowse { + nav.mode, nav.autoBrowse = touchNavigationMode, false + } + nav.wasBrowsing = browsing +} + +func (nav *touchNavigation) nextMode() touchAction { + nav.mode = (nav.mode + 1) % touchModeCount + nav.autoBrowse = false + return touchAction{announce: nav.mode.label()} +} + +func (nav *touchNavigation) turn(clockwise bool) touchAction { + if nav.mode == touchSpeechMode { + if clockwise { + return touchCmd(input.SelectNextSpeechCategory) + } + return touchCmd(input.SelectPreviousSpeechCategory) + } + rotor := touchModes[nav.mode].rotor + if len(rotor) == 0 { + return touchAction{announce: i18n.Format("{0} has no rotor", nav.mode.label())} + } + step := 1 + if !clockwise { + step = len(rotor) - 1 + } + nav.rotor[nav.mode] = (nav.rotor[nav.mode] + step) % len(rotor) + return touchAction{announce: i18n.T(rotor[nav.rotor[nav.mode]].label)} +} + +// flick finds a flick in the current rotor unit, then in the mode itself. +func (nav *touchNavigation) flick(flick touchFlick) (touchAction, bool) { + setup := touchModes[nav.mode] + if len(setup.rotor) > 0 { + if action, ok := setup.rotor[nav.rotor[nav.mode]].flicks[flick]; ok { + return action, true + } + } + action, ok := setup.flicks[flick] + return action, ok +} + +// gesture maps one gesture. browsing reports whether browse mode is active +// on a web page right now. +func (nav *touchNavigation) gesture(gesture touch.Gesture, browsing bool) touchAction { + nav.follow(browsing) + if action, ok := nav.flick(touchFlick{gesture.Kind, gesture.Fingers}); ok { + switch { + case nav.mode == touchBrowseMode && action.command != "": + nav.last = touchLastBrowse + case nav.mode != touchSpeechMode && (action.command != "" || action.i3 != ""): + nav.last = touchLastObject + } + return action + } + switch gesture.Fingers { + case 1: + switch gesture.Kind { + case touch.Tap: + nav.last = touchLastPoint + return touchAction{speakAtPoint: true} + case touch.DoubleTap: + if nav.mode == touchSpeechMode { + return touchCmd(input.SaveSpeechSettings) + } + switch nav.last { + case touchLastPoint: + return touchAction{clickPoint: true} + case touchLastBrowse: + return touchCmd(input.DocumentActivate) + case touchLastObject: + return touchCmd(input.ObjectActivate) + } + return touchAction{announce: i18n.T("Nothing to activate")} + case touch.DoubleTapHold: + if nav.last == touchLastPoint { + return touchAction{rightClickPoint: true} + } + return touchAction{key: touchKeyMenu} + } + case 2: + switch gesture.Kind { + case touch.Tap: + return touchAction{stopSpeech: true} + case touch.TripleTap: + return touchAction{key: touchKeyEscape} + case touch.RotateClockwise: + return nav.turn(true) + case touch.RotateCounterclockwise: + return nav.turn(false) + } + case 3: + switch gesture.Kind { + case touch.Tap: + return nav.nextMode() + case touch.FlickRight: + nav.last = touchLastObject + return touchAction{key: touchKeyTab} + case touch.FlickLeft: + nav.last = touchLastObject + return touchAction{key: touchKeyShiftTab} + case touch.FlickDown: + return touchCmd(input.ReadAll) + case touch.FlickUp: + return touchCmd(input.PresentWindowTitle) + } + case 4: + switch gesture.Kind { + case touch.Tap: + return touchCmd(input.PresentLastNotification) + case touch.DoubleTap: + return touchCmd(input.ShowNotificationList) + } + } + return touchAction{} +} diff --git a/internal/app/touch_navigation_test.go b/internal/app/touch_navigation_test.go new file mode 100644 index 0000000..c772933 --- /dev/null +++ b/internal/app/touch_navigation_test.go @@ -0,0 +1,234 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "testing" + + "git.stormux.org/storm/cthulhu/internal/input" + "git.stormux.org/storm/cthulhu/internal/touch" +) + +func g(kind touch.Kind, fingers int) touch.Gesture { + return touch.Gesture{Kind: kind, Fingers: fingers} +} + +// toMode taps three fingers until nav is in mode. +func toMode(t *testing.T, nav *touchNavigation, mode touchMode) { + t.Helper() + for range touchModeCount { + if nav.mode == mode { + return + } + nav.gesture(g(touch.Tap, 3), false) + } + t.Fatalf("could not reach %s", mode.label()) +} + +func expect(t *testing.T, nav *touchNavigation, want map[touch.Gesture]touchAction) { + t.Helper() + for gesture, action := range want { + if got := nav.gesture(gesture, nav.mode == touchBrowseMode && nav.autoBrowse); got != action { + t.Errorf("%s: %d finger %s = %+v, want %+v", nav.mode.label(), gesture.Fingers, gesture.Kind, got, action) + } + } +} + +func TestBehaviorNavigationModeIsTheDefaultAndMovesByItem(t *testing.T) { + nav := newTouchNavigation() + if nav.mode != touchNavigationMode { + t.Fatalf("default mode = %s", nav.mode.label()) + } + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.ObjectNextItem), g(touch.FlickLeft, 1): touchCmd(input.ObjectPreviousItem), + g(touch.FlickDown, 1): {scroll: 3}, g(touch.FlickUp, 1): {scroll: -3}, + }) + if got := nav.gesture(g(touch.DoubleTap, 1), false).command; got != input.ObjectActivate { + t.Fatalf("double tap after an item move = %q", got) + } + for _, step := range []struct { + label string + down, up touchAction + }{ + {"Windows", touchAction{i3: "focus next"}, touchAction{i3: "focus prev"}}, + {"Workspaces", touchAction{i3: "workspace next"}, touchAction{i3: "workspace prev"}}, + {"Notifications", touchCmd(input.PresentNextNotification), touchCmd(input.PresentPreviousNotification)}, + {"Scroll", touchAction{scroll: 3}, touchAction{scroll: -3}}, + } { + if got := nav.gesture(g(touch.RotateClockwise, 2), false).announce; got != step.label { + t.Fatalf("navigation rotor = %q, want %q", got, step.label) + } + expect(t, nav, map[touch.Gesture]touchAction{g(touch.FlickDown, 1): step.down, g(touch.FlickUp, 1): step.up}) + if got := nav.gesture(g(touch.FlickRight, 1), false).command; got != input.ObjectNextItem { + t.Fatalf("flick right must stay next item with %s, got %q", step.label, got) + } + } +} + +func TestBehaviorTextModeRotorChoosesTheUnit(t *testing.T) { + nav := newTouchNavigation() + toMode(t, nav, touchTextMode) + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.ReviewNextLine), g(touch.FlickLeft, 1): touchCmd(input.ReviewPreviousLine), + g(touch.FlickDown, 1): touchCmd(input.ReviewCurrentLine), g(touch.FlickUp, 1): touchCmd(input.ReviewSpellLine), + }) + if got := nav.gesture(g(touch.RotateClockwise, 2), false).announce; got != "Words" { + t.Fatalf("text rotor after lines = %q", got) + } + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.ReviewNextWord), g(touch.FlickLeft, 1): touchCmd(input.ReviewPreviousWord), + g(touch.FlickDown, 1): touchCmd(input.ReviewCurrentWord), g(touch.FlickUp, 1): touchCmd(input.ReviewSpellWord), + }) + if got := nav.gesture(g(touch.RotateClockwise, 2), false).announce; got != "Characters" { + t.Fatalf("text rotor after words = %q", got) + } + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.ReviewNextCharacter), g(touch.FlickLeft, 1): touchCmd(input.ReviewPreviousCharacter), + g(touch.FlickDown, 1): touchCmd(input.ReviewCurrentCharacter), g(touch.FlickUp, 1): touchCmd(input.ReviewPhoneticCharacter), + }) + if got := nav.gesture(g(touch.RotateClockwise, 2), false).announce; got != "Lines" { + t.Fatalf("text rotor must wrap, got %q", got) + } +} + +func TestBehaviorEachModeKeepsItsOwnRotorPosition(t *testing.T) { + nav := newTouchNavigation() + nav.gesture(g(touch.RotateClockwise, 2), false) // navigation: Windows + toMode(t, nav, touchTextMode) + if got := nav.gesture(g(touch.FlickRight, 1), false).command; got != input.ReviewNextLine { + t.Fatalf("text mode must start on lines, got %q", got) + } + toMode(t, nav, touchNavigationMode) + if got := nav.gesture(g(touch.FlickDown, 1), false).i3; got != "focus next" { + t.Fatalf("navigation mode must remember Windows, got %+v", nav.gesture(g(touch.FlickDown, 1), false)) + } +} + +func TestBehaviorBrowseModeFollowsWebPagesUnlessChosenByHand(t *testing.T) { + nav := newTouchNavigation() + if got := nav.gesture(g(touch.FlickDown, 1), true).command; got != input.DocumentNextHeading { + t.Fatalf("a web page must enter browse mode on headings, got %q", got) + } + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.DocumentCaretNextLine), g(touch.FlickLeft, 1): touchCmd(input.DocumentCaretPreviousLine), + g(touch.FlickUp, 1): touchCmd(input.DocumentPreviousHeading), + }) + if got := nav.gesture(g(touch.DoubleTap, 1), true).command; got != input.DocumentActivate { + t.Fatalf("double tap after a browse move = %q", got) + } + if got := nav.gesture(g(touch.RotateClockwise, 2), true).announce; got != "Links" { + t.Fatalf("browse rotor after headings = %q", got) + } + if got := nav.gesture(g(touch.FlickUp, 1), true).command; got != input.DocumentPreviousLink { + t.Fatalf("flick up on links = %q", got) + } + if got := nav.gesture(g(touch.FlickRight, 1), true).command; got != input.DocumentCaretNextLine { + t.Fatalf("flick right must stay page order with links chosen, got %q", got) + } + nav.gesture(g(touch.Tap, 2), false) // leaving the page + if nav.mode != touchNavigationMode { + t.Fatalf("leaving the web page must leave automatic browse mode, mode = %s", nav.mode.label()) + } + toMode(t, nav, touchBrowseMode) + nav.gesture(g(touch.Tap, 2), false) + if nav.mode != touchBrowseMode { + t.Fatalf("browse mode chosen by hand must stay, mode = %s", nav.mode.label()) + } +} + +func TestBehaviorObjectModeWalksTheTreeWithoutARotor(t *testing.T) { + nav := newTouchNavigation() + toMode(t, nav, touchObjectMode) + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.ObjectNextSibling), g(touch.FlickLeft, 1): touchCmd(input.ObjectPreviousSibling), + g(touch.FlickUp, 1): touchCmd(input.ObjectParent), g(touch.FlickDown, 1): touchCmd(input.ObjectFirstChild), + }) + if got := nav.gesture(g(touch.RotateClockwise, 2), false).announce; got != "Object mode has no rotor" { + t.Fatalf("object mode rotor = %q", got) + } +} + +func TestBehaviorSpeechModeRotorChangesCategory(t *testing.T) { + nav := newTouchNavigation() + toMode(t, nav, touchSpeechMode) + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.FlickRight, 1): touchCmd(input.SelectNextSpeechSetting), g(touch.FlickLeft, 1): touchCmd(input.SelectPreviousSpeechSetting), + g(touch.FlickUp, 1): touchCmd(input.IncreaseSpeechSetting), g(touch.FlickDown, 1): touchCmd(input.DecreaseSpeechSetting), + g(touch.RotateClockwise, 2): touchCmd(input.SelectNextSpeechCategory), + g(touch.RotateCounterclockwise, 2): touchCmd(input.SelectPreviousSpeechCategory), + g(touch.DoubleTap, 1): touchCmd(input.SaveSpeechSettings), + }) +} + +func TestBehaviorThreeFingerTapVisitsEveryModeInOrder(t *testing.T) { + nav := newTouchNavigation() + var heard []string + for range touchModeCount { + heard = append(heard, nav.gesture(g(touch.Tap, 3), false).announce) + } + want := []string{"Text mode", "Browse mode", "Object mode", "Speech settings mode", "Navigation mode"} + for i := range want { + if heard[i] != want[i] { + t.Fatalf("modes = %v, want %v", heard, want) + } + } +} + +func TestBehaviorNoTwoModesShareARotorList(t *testing.T) { + owner := map[string]touchMode{} + for mode, setup := range touchModes { + seen := map[string]bool{} + for _, unit := range setup.rotor { + if seen[unit.label] { + t.Fatalf("%s lists %q twice", touchMode(mode).label(), unit.label) + } + seen[unit.label] = true + if other, ok := owner[unit.label]; ok { + t.Fatalf("%q is in both %s and %s", unit.label, other.label(), touchMode(mode).label()) + } + owner[unit.label] = touchMode(mode) + } + } +} + +func TestBehaviorSharedGesturesMeanTheSameInEveryMode(t *testing.T) { + nav := newTouchNavigation() + for range touchModeCount { + expect(t, nav, map[touch.Gesture]touchAction{ + g(touch.Tap, 2): {stopSpeech: true}, + g(touch.TripleTap, 2): {key: touchKeyEscape}, + g(touch.FlickRight, 3): {key: touchKeyTab}, + g(touch.FlickLeft, 3): {key: touchKeyShiftTab}, + g(touch.FlickDown, 3): touchCmd(input.ReadAll), + g(touch.FlickUp, 3): touchCmd(input.PresentWindowTitle), + g(touch.Tap, 4): touchCmd(input.PresentLastNotification), + g(touch.DoubleTap, 4): touchCmd(input.ShowNotificationList), + }) + nav.gesture(g(touch.Tap, 3), false) + } +} + +func TestBehaviorDoubleTapActivatesWhatWasLastMoved(t *testing.T) { + nav := newTouchNavigation() + if got := nav.gesture(g(touch.DoubleTap, 1), false).announce; got != "Nothing to activate" { + t.Fatalf("double tap before anything = %q", got) + } + nav.explored() + if action := nav.gesture(g(touch.DoubleTap, 1), false); !action.clickPoint { + t.Fatalf("double tap after exploring must click the point: %+v", action) + } + if action := nav.gesture(g(touch.DoubleTapHold, 1), false); !action.rightClickPoint { + t.Fatalf("double tap and hold after exploring must right click: %+v", action) + } + nav.gesture(g(touch.FlickRight, 3), false) + if got := nav.gesture(g(touch.DoubleTap, 1), false).command; got != input.ObjectActivate { + t.Fatalf("double tap after Tab = %q", got) + } + if got := nav.gesture(g(touch.DoubleTapHold, 1), false).key; got != touchKeyMenu { + t.Fatalf("double tap and hold after Tab must press the menu key, got %d", got) + } + if action := nav.gesture(g(touch.Hold, 4), false); action != (touchAction{}) { + t.Fatalf("unbound gestures must do nothing: %+v", action) + } +} diff --git a/internal/app/touch_test.go b/internal/app/touch_test.go new file mode 100644 index 0000000..3657a6e --- /dev/null +++ b/internal/app/touch_test.go @@ -0,0 +1,121 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later +package app + +import ( + "context" + "log/slog" + "testing" + "time" + + "git.stormux.org/storm/cthulhu/internal/config" +) + +func TestBehaviorTouchActivityQuietsMouseReviewBriefly(t *testing.T) { + var activity touchActivity + if activity.recent(time.Second) { + t.Fatal("no touch yet must not quiet mouse review") + } + activity.mark() + if !activity.recent(time.Second) { + t.Fatal("touch just now must quiet mouse review") + } + activity.last.Store(time.Now().Add(-2 * time.Second).UnixNano()) + if activity.recent(time.Second) { + t.Fatal("old touch must not quiet mouse review") + } + var missing *touchActivity + if missing.recent(time.Second) { + t.Fatal("nil activity must never quiet mouse review") + } +} + +type blankSpeech struct{ said chan string } + +func (speech blankSpeech) Enqueue(request speechRequest) { speech.said <- request.Text } +func (blankSpeech) Interrupt() {} + +type blankBraille struct{} + +func (blankBraille) EnqueueMessage(string) bool { return true } + +func TestBehaviorEmptySpaceSaysBlankOnce(t *testing.T) { + t.Setenv("DISPLAY", "") // no X display: every point has no window under it + settings := config.DefaultSettings() + settings.Reading.EnableTouchScreen = true + live := &liveSettings{} + live.Store(settings) + speech := blankSpeech{said: make(chan string, 8)} + reviewer := &touchReviewer{logger: slog.New(slog.DiscardHandler), speech: speech, braille: blankBraille{}, + live: live, gate: &focusGate{}, points: make(chan touchPoint, 1)} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go reviewer.run(ctx) + expect := func(want string) { + t.Helper() + select { + case got := <-speech.said: + if got != want { + t.Fatalf("said %q, want %q", got, want) + } + case <-time.After(time.Second): + if want != "" { + t.Fatalf("said nothing, want %q", want) + } + } + } + reviewer.request(touchPoint{x: 10, y: 10}) + expect("Blank") + reviewer.request(touchPoint{x: 20, y: 20}) + select { + case got := <-speech.said: + t.Fatalf("moving over more empty space must stay quiet, said %q", got) + case <-time.After(200 * time.Millisecond): + } + reviewer.request(touchPoint{x: 20, y: 20, force: true}) + expect("Blank") +} + +func TestTouchReviewerDropsDisabledAndRetiredRequests(t *testing.T) { + t.Setenv("DISPLAY", "") + settings := config.DefaultSettings() + live := &liveSettings{} + live.Store(settings) + speech := blankSpeech{said: make(chan string, 8)} + reviewer := &touchReviewer{logger: slog.New(slog.DiscardHandler), speech: speech, braille: blankBraille{}, live: live, gate: &focusGate{}, points: make(chan touchPoint, 1)} + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { defer close(done); reviewer.run(ctx) }() + defer func() { cancel(); <-done }() + reviewer.request(touchPoint{force: true}) + select { + case got := <-speech.said: + t.Fatalf("disabled touch said %q", got) + case <-time.After(100 * time.Millisecond): + } + settings.Reading.EnableTouchScreen = true + live.Store(settings) + reviewer.generation.Add(1) + reviewer.points <- touchPoint{force: true, generation: 0} + select { + case got := <-speech.said: + t.Fatalf("retired touch said %q", got) + case <-time.After(100 * time.Millisecond): + } + reviewer.request(touchPoint{force: true}) + select { + case got := <-speech.said: + if got != "Blank" { + t.Fatalf("fresh touch said %q", got) + } + case <-time.After(time.Second): + t.Fatal("fresh touch was lost") + } +} + +func TestWaylandDoesNotOpenTouchDevice(t *testing.T) { + t.Setenv("XDG_SESSION_TYPE", "wayland") + // No reader dependencies: unsupported sessions must return before opening hardware. + runTouchScreen(t.Context(), slog.New(slog.DiscardHandler), nil, nil, nil, nil) +} diff --git a/internal/atspi/mouse_review_native.go b/internal/atspi/mouse_review_native.go index 0a22ad6..4188671 100644 --- a/internal/atspi/mouse_review_native.go +++ b/internal/atspi/mouse_review_native.go @@ -99,6 +99,86 @@ func nativeAccessibleAtPoint(source *C.AtspiAccessible, x, y int) *C.AtspiAccess return child } +// maxPointChildren bounds the fallback scan of one object's children. +const maxPointChildren = 512 + +// nativeChildContainingPoint finds the smallest child containing the point by +// asking each child. Some providers, Chromium tables among them, stop their +// own hit test at a container, so the child under the point is never reached. +func nativeChildContainingPoint(ctx context.Context, source *C.AtspiAccessible, x, y int) *C.AtspiAccessible { + count := min(int(C.atspi_accessible_get_child_count(source, nil)), maxPointChildren) + sourceID := nativeObjectID(source) + var best *C.AtspiAccessible + bestArea := int64(1 << 62) + for i := 0; i < count && ctx.Err() == nil; i++ { + child := C.atspi_accessible_get_child_at_index(source, C.gint(i), nil) + if child == nil { + continue + } + if nativeObjectID(child) != sourceID && nativeContainsPoint(child, x, y) { + if area := nativePointArea(child); best == nil || area < bestArea { + if best != nil { + C.g_object_unref(C.gpointer(best)) + } + best, bestArea = child, area + continue + } + } + C.g_object_unref(C.gpointer(child)) + } + return best +} + +// maxPointSearchDepth and maxPointSearchNodes bound the descendant search. +const ( + maxPointSearchDepth = 3 + maxPointSearchNodes = 1024 +) + +// nativeDescendantContainingPoint searches a few levels below source for the +// smallest object containing the point. GTK notebooks report a page tab's +// extents as only its label, so the page under the finger is a grandchild of +// the tab list that no direct child contains. +func nativeDescendantContainingPoint(ctx context.Context, source *C.AtspiAccessible, x, y int) *C.AtspiAccessible { + type entry struct { + node *C.AtspiAccessible + depth int + } + sourceID := nativeObjectID(source) + queue := []entry{{(*C.AtspiAccessible)(C.g_object_ref(C.gpointer(source))), 0}} + visited := 0 + var best *C.AtspiAccessible + bestArea := int64(1 << 62) + for len(queue) > 0 && visited < maxPointSearchNodes && ctx.Err() == nil { + current := queue[0] + queue = queue[1:] + if current.depth < maxPointSearchDepth { + count := min(int(C.atspi_accessible_get_child_count(current.node, nil)), maxPointChildren) + for i := 0; i < count && visited < maxPointSearchNodes && ctx.Err() == nil; i++ { + child := C.atspi_accessible_get_child_at_index(current.node, C.gint(i), nil) + if child == nil { + continue + } + visited++ + if nativeObjectID(child) != sourceID && nativeContainsPoint(child, x, y) { + if area := nativePointArea(child); best == nil || area < bestArea { + if best != nil { + C.g_object_unref(C.gpointer(best)) + } + best, bestArea = (*C.AtspiAccessible)(C.g_object_ref(C.gpointer(child))), area + } + } + queue = append(queue, entry{child, current.depth + 1}) + } + } + C.g_object_unref(C.gpointer(current.node)) + } + for _, rest := range queue { + C.g_object_unref(C.gpointer(rest.node)) + } + return best +} + func nativePointText(ctx context.Context, source, window *C.AtspiAccessible, x, y int) (word, line string, lineStart, nativeOffset int) { if C.atspi_accessible_get_role(source, nil) == C.ATSPI_ROLE_PASSWORD_TEXT { return "", "", -1, -1 @@ -216,11 +296,19 @@ func (adapter *Adapter) nativeReviewAtPoint(ctx context.Context, x, y, pid int) defer func() { C.g_object_unref(C.gpointer(current)) }() for depth := 0; depth < 24 && ctx.Err() == nil; depth++ { child := nativeAccessibleAtPoint(current, x, y) - if child == nil { - break - } - if nativeObjectID(child) == nativeObjectID(current) || !nativeContainsPoint(child, x, y) { + if child != nil && (nativeObjectID(child) == nativeObjectID(current) || !nativeContainsPoint(child, x, y)) { C.g_object_unref(C.gpointer(child)) + child = nil + } + if child == nil { + // The provider's hit test ended here. Ask the children directly + // before settling on a container such as a table or list. + child = nativeChildContainingPoint(ctx, current, x, y) + } + if child == nil { + child = nativeDescendantContainingPoint(ctx, current, x, y) + } + if child == nil { break } C.g_object_unref(C.gpointer(current)) diff --git a/internal/config/profile_mapping.go b/internal/config/profile_mapping.go index 5a5d0ff..c0c37fd 100644 --- a/internal/config/profile_mapping.go +++ b/internal/config/profile_mapping.go @@ -98,6 +98,7 @@ func profileFromSettings(settings Settings) writableProfile { UseColorNames: boolPointer(settings.Reading.UseColorNames), PresentTooltips: boolPointer(settings.Reading.PresentTooltips), EnableMouseReview: boolPointer(settings.Reading.EnableMouseReview), + EnableTouchScreen: boolPointer(settings.Reading.EnableTouchScreen), SpeakMisspelledIndicator: boolPointer(settings.Reading.SpeakMisspelledIndicator), SpeakContextBlockquote: boolPointer(settings.Reading.SpeakContextBlockquote), SpeakContextList: boolPointer(settings.Reading.SpeakContextList), @@ -372,6 +373,9 @@ func applyProfileReading(settings *Settings, profile writableProfile) { if value := profile.Presentation.Reading.EnableMouseReview; value != nil { settings.Reading.EnableMouseReview = *value } + if value := profile.Presentation.Reading.EnableTouchScreen; value != nil { + settings.Reading.EnableTouchScreen = *value + } if value := profile.Presentation.Reading.SpeakMisspelledIndicator; value != nil { settings.Reading.SpeakMisspelledIndicator = *value } diff --git a/internal/config/schema.go b/internal/config/schema.go index c0f09f3..e2f256c 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -118,6 +118,7 @@ type writableReading struct { UseColorNames *bool `toml:"use-color-names,omitempty"` PresentTooltips *bool `toml:"present-tooltips,omitempty"` EnableMouseReview *bool `toml:"enable-mouse-review,omitempty"` + EnableTouchScreen *bool `toml:"enable-touch-screen,omitempty"` SpeakMisspelledIndicator *bool `toml:"speak-misspelled-indicator,omitempty"` SpeakContextBlockquote *bool `toml:"speak-context-blockquote,omitempty"` SpeakContextList *bool `toml:"speak-context-list,omitempty"` diff --git a/internal/config/settings.go b/internal/config/settings.go index 5e5408e..2d0a63c 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -60,6 +60,7 @@ type ReadingSettings struct { UseColorNames bool PresentTooltips bool EnableMouseReview bool + EnableTouchScreen bool SpeakMisspelledIndicator bool SpeakContextBlockquote bool SpeakContextList bool diff --git a/internal/config/store_test.go b/internal/config/store_test.go index 8ad7032..6800f1c 100644 --- a/internal/config/store_test.go +++ b/internal/config/store_test.go @@ -33,6 +33,7 @@ func TestStoreSaveAndLoadRoundTrip(t *testing.T) { settings.Reading.SayAllContextPanel = false settings.Reading.PresentTooltips = true settings.Reading.EnableMouseReview = true + settings.Reading.EnableTouchScreen = true settings.EnableBraille = true settings.EnableContractedBraille = true settings.BrailleContractionTable = "en-us-g2.ctb" diff --git a/internal/i18n/locale/cthulhu.pot b/internal/i18n/locale/cthulhu.pot index e8c284f..09470aa 100644 --- a/internal/i18n/locale/cthulhu.pot +++ b/internal/i18n/locale/cthulhu.pot @@ -13,14 +13,30 @@ msgstr "" msgid "1 character" msgstr "" +#: internal/app/object_activate.go:45 +msgid "Activation unavailable." +msgstr "" + +#: internal/app/touch.go:135 +msgid "Blank" +msgstr "" + #: screenreader-common/internalui msgid "Copy and cut are unavailable for password fields" msgstr "" +#: internal/app/object_activate.go:69 +msgid "Could not activate." +msgstr "" + #: screenreader-common/internalui msgid "Deleted {0}" msgstr "" +#: internal/app/touch.go:157 +msgid "Desktop" +msgstr "" + #: screenreader-common/internalui msgid "End of text" msgstr "" @@ -37,10 +53,22 @@ msgstr "" msgid "Invalid text" msgstr "" +#: internal/app/object_activate.go:59 +msgid "No action available." +msgstr "" + #: screenreader-common/internalui msgid "No matches" msgstr "" +#: internal/app/touch.go:489 +msgid "Not available" +msgstr "" + +#: internal/app/touch_navigation.go:282 +msgid "Nothing to activate" +msgstr "" + #: screenreader-common/internalui msgid "Only single-line text is accepted" msgstr "" @@ -65,6 +93,14 @@ msgstr "" msgid "Text limit reached" msgstr "" +#: internal/app/touch.go:375 +msgid "Touch screen needs input group access. Add your user to the input group and log in again." +msgstr "" + +#: internal/app/touch.go:160 +msgid "Window" +msgstr "" + #: screenreader-common/internalui screenreader-common/quicksettings/menu.go msgid "checked" msgstr "" @@ -101,6 +137,10 @@ msgstr "" msgid "{0} grid. {1}" msgstr "" +#: internal/app/touch_navigation.go:229 +msgid "{0} has no rotor" +msgstr "" + #: screenreader-common/internalui msgid "{0} is required" msgstr "" diff --git a/internal/i3command/command.go b/internal/i3command/command.go new file mode 100644 index 0000000..017526b --- /dev/null +++ b/internal/i3command/command.go @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package i3command sends window-management commands to i3 on behalf of the +// user, such as touch desktop navigation. It is separate from i3ipc, which +// only observes i3. Each command uses its own short connection. +package i3command + +import ( + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "time" +) + +const ( + runCommand = 0 + maxReply = 1 << 20 + timeout = 2 * time.Second +) + +// Run sends one i3 command, such as "workspace next", and reports failure. +func Run(ctx context.Context, path, command string) error { + if path == "" { + return errors.New("i3 socket unavailable") + } + var dialer net.Dialer + conn, err := dialer.DialContext(ctx, "unix", path) + if err != nil { + return err + } + defer conn.Close() + stop := context.AfterFunc(ctx, func() { conn.Close() }) + defer stop() + deadline := time.Now().Add(timeout) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + if err := conn.SetDeadline(deadline); err != nil { + return err + } + if err := write(conn, runCommand, []byte(command)); err != nil { + return err + } + kind, body, err := read(conn) + if err != nil { + return err + } + if kind != runCommand { + return fmt.Errorf("unexpected i3 reply type %d", kind) + } + var replies []struct { + Success bool `json:"success"` + Error string `json:"error"` + } + if err := json.Unmarshal(body, &replies); err != nil { + return fmt.Errorf("i3 reply: %w", err) + } + if len(replies) == 0 { + return errors.New("empty i3 command reply") + } + for _, reply := range replies { + if !reply.Success { + return fmt.Errorf("i3 %q: %s", command, reply.Error) + } + } + return nil +} + +func write(w io.Writer, kind uint32, body []byte) error { + header := make([]byte, 14, 14+len(body)) + copy(header, "i3-ipc") + binary.NativeEndian.PutUint32(header[6:10], uint32(len(body))) + binary.NativeEndian.PutUint32(header[10:], kind) + _, err := w.Write(append(header, body...)) + return err +} + +func read(r io.Reader) (uint32, []byte, error) { + var header [14]byte + if _, err := io.ReadFull(r, header[:]); err != nil { + return 0, nil, err + } + if string(header[:6]) != "i3-ipc" { + return 0, nil, errors.New("invalid i3 magic") + } + size := binary.NativeEndian.Uint32(header[6:10]) + if size > maxReply { + return 0, nil, errors.New("i3 reply too large") + } + body := make([]byte, size) + if _, err := io.ReadFull(r, body); err != nil { + return 0, nil, err + } + return binary.NativeEndian.Uint32(header[10:]), body, nil +} diff --git a/internal/i3command/command_test.go b/internal/i3command/command_test.go new file mode 100644 index 0000000..22c7c12 --- /dev/null +++ b/internal/i3command/command_test.go @@ -0,0 +1,74 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package i3command + +import ( + "context" + "net" + "path/filepath" + "testing" + "time" +) + +// fakeI3 answers one RUN_COMMAND with reply and reports the command it got. +func fakeI3(t *testing.T, reply string) (string, <-chan string) { + t.Helper() + path := filepath.Join(t.TempDir(), "i3.sock") + listener, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + received := make(chan string, 1) + go func() { + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + kind, body, err := read(conn) + if err != nil || kind != runCommand { + received <- "bad request" + return + } + received <- string(body) + _ = write(conn, runCommand, []byte(reply)) + }() + return path, received +} + +func TestBehaviorRunSendsTheCommandAndAcceptsSuccess(t *testing.T) { + path, received := fakeI3(t, `[{"success":true}]`) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := Run(ctx, path, "workspace next"); err != nil { + t.Fatal(err) + } + if got := <-received; got != "workspace next" { + t.Fatalf("i3 received %q", got) + } +} + +func TestBehaviorRunReportsI3Failure(t *testing.T) { + path, received := fakeI3(t, `[{"success":false,"error":"No window to focus"}]`) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := Run(ctx, path, "focus next"); err == nil { + t.Fatal("a failed i3 command must return an error") + } + if got := <-received; got != "focus next" { + t.Fatalf("i3 received %q", got) + } + if err := Run(ctx, "", "focus next"); err == nil { + t.Fatal("a missing socket must return an error") + } +} + +func TestEmptyReplyIsNotSuccess(t *testing.T) { + path, _ := fakeI3(t, `[]`) + if err := Run(t.Context(), path, "workspace next"); err == nil { + t.Fatal("empty reply accepted") + } +} diff --git a/internal/input/commands.go b/internal/input/commands.go index fe3b026..3aa9071 100644 --- a/internal/input/commands.go +++ b/internal/input/commands.go @@ -130,6 +130,10 @@ const ( ObjectFirstChild Command = "object-first-child" ObjectPreviousSibling Command = "object-previous-sibling" ObjectNextSibling Command = "object-next-sibling" + ObjectNextItem Command = "object-next-item" + ObjectPreviousItem Command = "object-previous-item" + ObjectActivate Command = "object-activate" + ToggleTouchScreen Command = "toggle-touch-screen" ReviewWindowStart Command = "review-window-start" ReviewWindowEnd Command = "review-window-end" ReviewPreviousLine Command = "review-previous-line" @@ -207,42 +211,43 @@ func (state LockState) Text() string { func DefaultCommandBindings(layout KeyboardLayout) CommandBindings { bindings := CommandBindings{ - {Symbol: 'e', Modifiers: controlModifier, CthulhuModifier: true}: EmojiMenu, - {Symbol: 'a', Modifiers: 1, CthulhuModifier: true}: ShowActions, - {Symbol: leftKeySymbol, CthulhuModifier: true}: SelectPreviousSpeechSetting, - {Symbol: rightKeySymbol, CthulhuModifier: true}: SelectNextSpeechSetting, - {Symbol: downKeySymbol, CthulhuModifier: true}: DecreaseSpeechSetting, - {Symbol: upKeySymbol, CthulhuModifier: true}: IncreaseSpeechSetting, - {Symbol: upKeySymbol, Modifiers: 1, CthulhuModifier: true}: PresentCurrentLine, - {Symbol: 's', Modifiers: controlModifier | 1, CthulhuModifier: true}: SaveSpeechSettings, - {Symbol: 't', CthulhuModifier: true}: PresentTime, - {Symbol: 'c', Modifiers: 1, CthulhuModifier: true}: PresentClipboard, - {Symbol: 'h', Modifiers: controlModifier, CthulhuModifier: true}: ShowSpeechHistory, - {Symbol: 'd', Modifiers: 1, CthulhuModifier: true}: ToggleSpeechMonitor, - {Symbol: 's', CthulhuModifier: true}: CycleSpeechMode, - {Symbol: 'u', CthulhuModifier: true}: CycleProgressBarOutput, - {Symbol: 'v', Modifiers: 1, CthulhuModifier: true}: PresentVersion, - {Symbol: 'a', CthulhuModifier: true}: ToggleDocumentMode, - {Symbol: 'h', CthulhuModifier: true}: ToggleLearnMode, - {Symbol: 'z', CthulhuModifier: true}: ToggleCommandBypass, - {Symbol: 'h', Modifiers: 1, CthulhuModifier: true}: DocumentPreviousHeading, - {Symbol: 'k', CthulhuModifier: true, Modifiers: controlModifier}: DocumentNextLink, - {Symbol: 'k', Modifiers: controlModifier | 1, CthulhuModifier: true}: DocumentPreviousLink, - {Symbol: 'q', CthulhuModifier: true}: Quit, - {Symbol: 'q', Modifiers: 5, CthulhuModifier: true}: DisableTentacles, - {Symbol: 'n', CthulhuModifier: true}: PresentLastNotification, - {Symbol: 'n', Modifiers: controlModifier, CthulhuModifier: true}: ShowNotificationList, - {Symbol: ' ', CthulhuModifier: true}: Preferences, - {Symbol: ' ', Modifiers: controlModifier, CthulhuModifier: true}: ApplicationPreferences, - {Symbol: ' ', Modifiers: 1, CthulhuModifier: true}: ApplicationPreferences, - {Symbol: ' ', Modifiers: controlModifier | 1, CthulhuModifier: true}: ChooseApplicationPreferences, - {Symbol: 'f', CthulhuModifier: true}: PresentCharacterAttributes, - {Symbol: upKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectParent, - {Symbol: downKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectFirstChild, - {Symbol: leftKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectPreviousSpeechCategory, - {Symbol: rightKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectNextSpeechCategory, - {Symbol: leftKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectPreviousSibling, - {Symbol: rightKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectNextSibling, + {Symbol: 'e', Modifiers: controlModifier, CthulhuModifier: true}: EmojiMenu, + {Symbol: 'a', Modifiers: 1, CthulhuModifier: true}: ShowActions, + {Symbol: leftKeySymbol, CthulhuModifier: true}: SelectPreviousSpeechSetting, + {Symbol: rightKeySymbol, CthulhuModifier: true}: SelectNextSpeechSetting, + {Symbol: downKeySymbol, CthulhuModifier: true}: DecreaseSpeechSetting, + {Symbol: upKeySymbol, CthulhuModifier: true}: IncreaseSpeechSetting, + {Symbol: upKeySymbol, Modifiers: 1, CthulhuModifier: true}: PresentCurrentLine, + {Symbol: 's', Modifiers: controlModifier | 1, CthulhuModifier: true}: SaveSpeechSettings, + {Symbol: 't', CthulhuModifier: true}: PresentTime, + {Symbol: 't', Modifiers: controlModifier | altModifier, CthulhuModifier: true}: ToggleTouchScreen, + {Symbol: 'c', Modifiers: 1, CthulhuModifier: true}: PresentClipboard, + {Symbol: 'h', Modifiers: controlModifier, CthulhuModifier: true}: ShowSpeechHistory, + {Symbol: 'd', Modifiers: 1, CthulhuModifier: true}: ToggleSpeechMonitor, + {Symbol: 's', CthulhuModifier: true}: CycleSpeechMode, + {Symbol: 'u', CthulhuModifier: true}: CycleProgressBarOutput, + {Symbol: 'v', Modifiers: 1, CthulhuModifier: true}: PresentVersion, + {Symbol: 'a', CthulhuModifier: true}: ToggleDocumentMode, + {Symbol: 'h', CthulhuModifier: true}: ToggleLearnMode, + {Symbol: 'z', CthulhuModifier: true}: ToggleCommandBypass, + {Symbol: 'h', Modifiers: 1, CthulhuModifier: true}: DocumentPreviousHeading, + {Symbol: 'k', CthulhuModifier: true, Modifiers: controlModifier}: DocumentNextLink, + {Symbol: 'k', Modifiers: controlModifier | 1, CthulhuModifier: true}: DocumentPreviousLink, + {Symbol: 'q', CthulhuModifier: true}: Quit, + {Symbol: 'q', Modifiers: 5, CthulhuModifier: true}: DisableTentacles, + {Symbol: 'n', CthulhuModifier: true}: PresentLastNotification, + {Symbol: 'n', Modifiers: controlModifier, CthulhuModifier: true}: ShowNotificationList, + {Symbol: ' ', CthulhuModifier: true}: Preferences, + {Symbol: ' ', Modifiers: controlModifier, CthulhuModifier: true}: ApplicationPreferences, + {Symbol: ' ', Modifiers: 1, CthulhuModifier: true}: ApplicationPreferences, + {Symbol: ' ', Modifiers: controlModifier | 1, CthulhuModifier: true}: ChooseApplicationPreferences, + {Symbol: 'f', CthulhuModifier: true}: PresentCharacterAttributes, + {Symbol: upKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectParent, + {Symbol: downKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: ObjectFirstChild, + {Symbol: leftKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectPreviousSpeechCategory, + {Symbol: rightKeySymbol, Modifiers: controlModifier, CthulhuModifier: true}: SelectNextSpeechCategory, + {Symbol: leftKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectPreviousSibling, + {Symbol: rightKeySymbol, Modifiers: altModifier, CthulhuModifier: true}: ObjectNextSibling, } for index := 0; index < 12; index++ { bindings[CommandChord{Symbol: 0xffbe + uint32(index), CthulhuModifier: true}] = MessageCommand(index, false) diff --git a/internal/platform/evdev/touch.go b/internal/platform/evdev/touch.go new file mode 100644 index 0000000..e2b7ed6 --- /dev/null +++ b/internal/platform/evdev/touch.go @@ -0,0 +1,341 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package evdev reads a touch screen directly from the Linux input layer. +// The device is grabbed with EVIOCGRAB, so while Cthulhu owns it no other +// program, including the X server or a Wayland compositor, sees the touches. +// Reading /dev/input needs membership in the input group or an equivalent +// udev rule. It does not depend on a display server or init system. +package evdev + +import ( + "encoding/binary" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + evSyn = 0x00 + evAbs = 0x03 + + synReport = 0 + synDropped = 3 + + absMTSlot = 0x2f + absMTPositionX = 0x35 + absMTPositionY = 0x36 + absMTTrackingID = 0x39 + absMax = 0x3f + + inputPropDirect = 0x01 + + iocRead = 2 + iocWrite = 1 +) + +func ioc(dir, nr, size uintptr) uintptr { return dir<<30 | size<<16 | 'E'<<8 | nr } + +func ioctl(fd int, request uintptr, arg unsafe.Pointer) error { + if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), request, uintptr(arg)); errno != 0 { + return errno + } + return nil +} + +type absInfo struct{ Value, Minimum, Maximum, Fuzz, Flat, Resolution int32 } + +// Phase values match touch.Begin, touch.Update and touch.End. +const ( + Begin = 0 + Update = 1 + End = 2 + Cancel = 3 // Lost events invalidate the whole gesture. +) + +// Contact is one finger change in screen pixels. +type Contact struct { + Phase int + ID uint32 + X, Y float64 +} + +// Device describes a direct multitouch device such as a touch screen. +type Device struct { + Path string + Name string + MinX, MaxX, MinY, MaxY int32 + Slots int +} + +func bitSet(bits []byte, bit int) bool { + return bit/8 < len(bits) && bits[bit/8]&(1<<(bit%8)) != 0 +} + +func describe(path string) (Device, bool) { + file, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0) + if err != nil { + return Device{}, false + } + defer file.Close() + fd := int(file.Fd()) + device := Device{Path: path} + name := make([]byte, 256) + if ioctl(fd, ioc(iocRead, 0x06, uintptr(len(name))), unsafe.Pointer(&name[0])) == nil { + device.Name = strings.TrimRight(string(name), "\x00") + } + props := make([]byte, 8) + if ioctl(fd, ioc(iocRead, 0x09, uintptr(len(props))), unsafe.Pointer(&props[0])) != nil || + !bitSet(props, inputPropDirect) { + return Device{}, false + } + abs := make([]byte, absMax/8+1) + if ioctl(fd, ioc(iocRead, 0x20+evAbs, uintptr(len(abs))), unsafe.Pointer(&abs[0])) != nil || + !bitSet(abs, absMTSlot) || !bitSet(abs, absMTPositionX) || !bitSet(abs, absMTPositionY) || + !bitSet(abs, absMTTrackingID) { + return Device{}, false + } + read := func(code uintptr) (absInfo, bool) { + var info absInfo + err := ioctl(fd, ioc(iocRead, 0x40+code, unsafe.Sizeof(info)), unsafe.Pointer(&info)) + return info, err == nil + } + x, okX := read(absMTPositionX) + y, okY := read(absMTPositionY) + slots, okSlots := read(absMTSlot) + if !okX || !okY || !okSlots || x.Maximum <= x.Minimum || y.Maximum <= y.Minimum { + return Device{}, false + } + device.MinX, device.MaxX, device.MinY, device.MaxY = x.Minimum, x.Maximum, y.Minimum, y.Maximum + device.Slots = int(slots.Maximum) + 1 + return device, true +} + +// FindTouchScreens lists direct multitouch devices. Unreadable devices are +// skipped; denied reports whether any device could not be opened, which +// usually means the user is not in the input group. +func FindTouchScreens() (devices []Device, denied bool) { + paths, _ := filepath.Glob("/dev/input/event*") + sort.Strings(paths) + for _, path := range paths { + if file, err := os.Open(path); err != nil { + if errors.Is(err, os.ErrPermission) { + denied = true + } + continue + } else { + file.Close() + } + if device, ok := describe(path); ok { + devices = append(devices, device) + } + } + return devices, denied +} + +// TouchScreen owns one grabbed touch device. Use it from one goroutine. +type TouchScreen struct { + Device Device + file *os.File + fd int + tracker *Tracker + buffer []byte + pending []Contact +} + +// Open opens and grabs a touch screen, mapping it onto a screen of the given +// size in pixels. +func Open(device Device, screenWidth, screenHeight int) (*TouchScreen, error) { + file, err := os.OpenFile(device.Path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0) + if err != nil { + return nil, err + } + fd := int(file.Fd()) + if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), ioc(iocWrite, 0x90, 4), 1); err != 0 { + file.Close() + return nil, fmt.Errorf("grab %s: %w", device.Path, err) + } + return &TouchScreen{Device: device, file: file, fd: fd, + tracker: NewTracker(device, screenWidth, screenHeight), buffer: make([]byte, inputEventSize*64)}, nil +} + +const inputEventSize = int(unsafe.Sizeof(syscall.Timeval{})) + 8 + +// Next waits up to timeout for one contact change. failed reports that the +// device went away, for example when it was unplugged. +func (screen *TouchScreen) Next(timeout time.Duration) (contact Contact, ok, failed bool) { + if len(screen.pending) > 0 { + contact, screen.pending = screen.pending[0], screen.pending[1:] + return contact, true, false + } + var set syscall.FdSet + bits := int(unsafe.Sizeof(set.Bits[0])) * 8 + if screen.fd < 0 || screen.fd >= len(set.Bits)*bits { + return Contact{}, false, true + } + set.Bits[screen.fd/bits] |= 1 << (uint(screen.fd) % uint(bits)) + tv := syscall.NsecToTimeval(timeout.Nanoseconds()) + n, err := syscall.Select(screen.fd+1, &set, nil, nil, &tv) + if err != nil { + if errors.Is(err, syscall.EINTR) { + return Contact{}, false, false + } + return Contact{}, false, true + } + if n <= 0 { + return Contact{}, false, false + } + count, err := syscall.Read(screen.fd, screen.buffer) + if err != nil { + if errors.Is(err, syscall.EAGAIN) || errors.Is(err, syscall.EINTR) { + return Contact{}, false, false + } + return Contact{}, false, true + } + if count == 0 { + return Contact{}, false, true + } + for offset := 0; offset+inputEventSize <= count; offset += inputEventSize { + record := screen.buffer[offset+inputEventSize-8 : offset+inputEventSize] + screen.pending = screen.tracker.Event(binary.NativeEndian.Uint16(record), + binary.NativeEndian.Uint16(record[2:]), int32(binary.NativeEndian.Uint32(record[4:])), screen.pending) + } + for _, event := range screen.pending { + if event.Phase == Cancel { + // Reopen after overflow to discard unknown kernel slot state. + screen.pending = nil + return Contact{}, false, true + } + } + if len(screen.pending) == 0 { + return Contact{}, false, false + } + contact, screen.pending = screen.pending[0], screen.pending[1:] + return contact, true, false +} + +// Close releases the grab so other programs see touches again. +func (screen *TouchScreen) Close() { + if screen == nil || screen.file == nil { + return + } + _, _, _ = syscall.Syscall(syscall.SYS_IOCTL, uintptr(screen.fd), ioc(iocWrite, 0x90, 4), 0) + screen.file.Close() + screen.file = nil +} + +// Tracker turns multitouch protocol B events into contact changes. It is +// separate from the device so it can be tested without hardware. +type Tracker struct { + device Device + width, height float64 + slot int + dropped bool + slots []slotState +} + +type slotState struct { + active, began, moved, ended, replaced bool + id, oldID uint32 + x, y int32 +} + +func NewTracker(device Device, screenWidth, screenHeight int) *Tracker { + slots := device.Slots + if slots <= 0 || slots > 64 { + slots = 64 + } + return &Tracker{device: device, width: float64(screenWidth), height: float64(screenHeight), + slots: make([]slotState, slots)} +} + +func (tracker *Tracker) screen(x, y int32) (float64, float64) { + d := tracker.device + sx := float64(x-d.MinX) * tracker.width / float64(d.MaxX-d.MinX+1) + sy := float64(y-d.MinY) * tracker.height / float64(d.MaxY-d.MinY+1) + return sx, sy +} + +// Event handles one input event and appends finished contact changes, which +// are only emitted at SYN_REPORT so each frame is consistent. +func (tracker *Tracker) Event(kind, code uint16, value int32, out []Contact) []Contact { + if tracker.dropped { + if kind == evSyn && code == synReport { + tracker.dropped = false + } + return out + } + switch kind { + case evAbs: + if code == absMTSlot { + tracker.slot = int(value) + return out + } + if tracker.slot < 0 || tracker.slot >= len(tracker.slots) { + return out + } + state := &tracker.slots[tracker.slot] + switch code { + case absMTTrackingID: + if value >= 0 { + // A new contact in a slot that still holds one ends the old one. + if state.active { + state.replaced, state.oldID, state.ended = true, state.id, false + } + state.began, state.id = true, uint32(value) + } else if state.began { + // Landed and lifted within one frame: never report it. + state.began = false + } else if state.active { + state.ended = true + } + case absMTPositionX: + state.x, state.moved = value, true + case absMTPositionY: + state.y, state.moved = value, true + } + case evSyn: + switch code { + case synReport: + out = tracker.flush(out) + case synDropped: + // Never turn incomplete input into taps or activation. + clear(tracker.slots) + tracker.slot, tracker.dropped = 0, true + out = append(out, Contact{Phase: Cancel}) + } + } + return out +} + +func (tracker *Tracker) flush(out []Contact) []Contact { + for index := range tracker.slots { + state := &tracker.slots[index] + x, y := tracker.screen(state.x, state.y) + if state.replaced { + out = append(out, Contact{Phase: End, ID: state.oldID, X: x, Y: y}) + state.active, state.replaced = false, false + } + if state.began { + out = append(out, Contact{Phase: Begin, ID: state.id, X: x, Y: y}) + state.active, state.began, state.moved = true, false, false + } + if state.moved && state.active { + out = append(out, Contact{Phase: Update, ID: state.id, X: x, Y: y}) + } + state.moved = false + if state.ended && state.active { + out = append(out, Contact{Phase: End, ID: state.id, X: x, Y: y}) + state.active = false + } + state.ended = false + } + return out +} diff --git a/internal/platform/evdev/touch_test.go b/internal/platform/evdev/touch_test.go new file mode 100644 index 0000000..801dec5 --- /dev/null +++ b/internal/platform/evdev/touch_test.go @@ -0,0 +1,152 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package evdev + +import ( + "os" + "testing" +) + +// A screen whose raw range is 0..3839 by 0..2399 on a 1920 by 1200 display. +var testDevice = Device{MinX: 0, MaxX: 3839, MinY: 0, MaxY: 2399, Slots: 10} + +type frame struct{ events [][3]int32 } + +func run(t *testing.T, frames ...frame) []Contact { + t.Helper() + tracker := NewTracker(testDevice, 1920, 1200) + var out []Contact + for _, f := range frames { + for _, e := range f.events { + out = tracker.Event(uint16(e[0]), uint16(e[1]), e[2], out) + } + out = tracker.Event(evSyn, synReport, 0, out) + } + return out +} + +func abs(code, value int32) [3]int32 { return [3]int32{evAbs, code, value} } + +func TestBehaviorOneFingerDownMoveUp(t *testing.T) { + got := run(t, + frame{[][3]int32{abs(absMTSlot, 0), abs(absMTTrackingID, 7), abs(absMTPositionX, 2000), abs(absMTPositionY, 1000)}}, + frame{[][3]int32{abs(absMTPositionX, 2100)}}, + frame{[][3]int32{abs(absMTTrackingID, -1)}}, + ) + want := []Contact{{Begin, 7, 1000, 500}, {Update, 7, 1050, 500}, {End, 7, 1050, 500}} + if len(got) != len(want) { + t.Fatalf("got %+v, want %+v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("contact %d: got %+v, want %+v", i, got[i], want[i]) + } + } +} + +func TestBehaviorTwoFingersUseTheirOwnSlots(t *testing.T) { + got := run(t, + frame{[][3]int32{abs(absMTSlot, 0), abs(absMTTrackingID, 1), abs(absMTPositionX, 400), abs(absMTPositionY, 400), + abs(absMTSlot, 1), abs(absMTTrackingID, 2), abs(absMTPositionX, 800), abs(absMTPositionY, 400)}}, + frame{[][3]int32{abs(absMTSlot, 0), abs(absMTTrackingID, -1), abs(absMTSlot, 1), abs(absMTTrackingID, -1)}}, + ) + var begins, ends int + ids := map[uint32]bool{} + for _, c := range got { + ids[c.ID] = true + switch c.Phase { + case Begin: + begins++ + case End: + ends++ + } + } + if begins != 2 || ends != 2 || len(ids) != 2 { + t.Fatalf("want two separate contacts, got %+v", got) + } +} + +func TestBehaviorReusedSlotEndsTheOldContactFirst(t *testing.T) { + got := run(t, + frame{[][3]int32{abs(absMTSlot, 0), abs(absMTTrackingID, 5), abs(absMTPositionX, 100), abs(absMTPositionY, 100)}}, + frame{[][3]int32{abs(absMTTrackingID, 6), abs(absMTPositionX, 300)}}, + ) + if len(got) != 3 || got[1].Phase != End || got[1].ID != 5 || got[2].Phase != Begin || got[2].ID != 6 { + t.Fatalf("want begin 5, end 5, begin 6, got %+v", got) + } +} + +func TestBehaviorTouchWithinOneFrameIsNotReported(t *testing.T) { + got := run(t, frame{[][3]int32{abs(absMTTrackingID, 9), abs(absMTPositionX, 10), abs(absMTTrackingID, -1)}}) + if len(got) != 0 { + t.Fatalf("want nothing, got %+v", got) + } +} + +func TestBehaviorDroppedEventsCancelEveryContact(t *testing.T) { + tracker := NewTracker(testDevice, 1920, 1200) + var out []Contact + for _, e := range [][3]int32{abs(absMTSlot, 0), abs(absMTTrackingID, 1), abs(absMTSlot, 1), abs(absMTTrackingID, 2)} { + out = tracker.Event(uint16(e[0]), uint16(e[1]), e[2], out) + } + out = tracker.Event(evSyn, synReport, 0, out) + out = tracker.Event(evSyn, synDropped, 0, out[:0]) + if len(out) != 1 || out[0].Phase != Cancel { + t.Fatalf("want gesture cancelled, got %+v", out) + } + out = tracker.Event(evSyn, synReport, 0, out[:0]) + if len(out) != 0 { + t.Fatalf("nothing may remain after a drop, got %+v", out) + } +} + +func TestBehaviorIoctlNumbersMatchLinux(t *testing.T) { + if got := ioc(iocWrite, 0x90, 4); got != 0x40044590 { + t.Fatalf("EVIOCGRAB = %#x", got) + } + if got := ioc(iocRead, 0x40+absMTPositionX, 24); got != 0x80184575 { + t.Fatalf("EVIOCGABS(ABS_MT_POSITION_X) = %#x", got) + } +} + +// Reads the real touch screen's description, without grabbing it. +func TestNativeFindTouchScreens(t *testing.T) { + if os.Getenv("CTHULHU_NATIVE_EVDEV") != "1" { + t.Skip("requires a touch screen and input group access") + } + devices, denied := FindTouchScreens() + t.Logf("devices=%+v denied=%v", devices, denied) + if len(devices) == 0 { + t.Fatal("no touch screen found") + } +} + +func TestDroppedFrameIgnoresEventsUntilReport(t *testing.T) { + tracker := NewTracker(testDevice, 1920, 1200) + tracker.Event(evSyn, synDropped, 0, nil) + tracker.Event(evAbs, absMTTrackingID, 42, nil) + if got := tracker.Event(evSyn, synReport, 0, nil); len(got) != 0 { + t.Fatalf("incomplete frame emitted %+v", got) + } + tracker.Event(evAbs, absMTTrackingID, 43, nil) + if got := tracker.Event(evSyn, synReport, 0, nil); len(got) != 1 || got[0].ID != 43 { + t.Fatalf("fresh frame = %+v", got) + } +} + +func TestInvalidSlotDoesNotModifyPreviousFinger(t *testing.T) { + got := run(t, frame{[][3]int32{abs(absMTTrackingID, 7), abs(absMTPositionX, 200)}}, + frame{[][3]int32{abs(absMTSlot, 100), abs(absMTTrackingID, -1), abs(absMTPositionX, 3000)}}) + if len(got) != 1 || got[0].Phase != Begin { + t.Fatalf("invalid slot changed valid finger: %+v", got) + } +} + +func TestHighDescriptorFailsWithoutPanic(t *testing.T) { + screen := &TouchScreen{fd: 100000} + if _, _, failed := screen.Next(0); !failed { + t.Fatal("unsupported descriptor must fail") + } +} diff --git a/internal/platform/xorg/touch.go b/internal/platform/xorg/touch.go new file mode 100644 index 0000000..d830add --- /dev/null +++ b/internal/platform/xorg/touch.go @@ -0,0 +1,108 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package xorg + +/* +#cgo pkg-config: x11 xtst xres +#include "touch_native.h" +*/ +import "C" + +// WindowLocator finds the client under a screen point and performs touch +// activation clicks on its own X connection. Use it from one goroutine and +// close it after that goroutine stops. +type WindowLocator struct { + display *C.Display + xres C.int +} + +func OpenWindowLocator() *WindowLocator { + display := C.cthulhu_window_locator_open() + if display == nil { + return nil + } + return &WindowLocator{display: display, xres: C.cthulhu_xres_client_pids_supported(display)} +} + +// ScreenSize reports the X screen size in pixels. +func (locator *WindowLocator) ScreenSize() (width, height int) { + if locator == nil || locator.display == nil { + return 0, 0 + } + var w, h C.int + C.cthulhu_screen_size(locator.display, &w, &h) + return int(w), int(h) +} + +// WindowAt reports the client process and window under a screen point. +func (locator *WindowLocator) WindowAt(x, y int) (pid int, window uint64) { + if locator == nil || locator.display == nil { + return 0, 0 + } + var native C.ulong + pid = int(C.cthulhu_window_locator_pid(locator.display, locator.xres, C.int(x), C.int(y), &native)) + return pid, uint64(native) +} + +// WindowTitle reports a window's title, or "" when it has none. +func (locator *WindowLocator) WindowTitle(window uint64) string { + if locator == nil || locator.display == nil || window == 0 { + return "" + } + var title [512]C.char + if C.cthulhu_window_title(locator.display, C.ulong(window), &title[0], C.int(len(title))) == 0 { + return "" + } + return C.GoString(&title[0]) +} + +// Click presses and releases a mouse button (1 left, 3 right, 4 and 5 the +// wheel) at a point and returns the pointer to where it was. +func (locator *WindowLocator) Click(x, y, button int) bool { + if locator == nil || locator.display == nil || button < 1 || button > 5 { + return false + } + return C.cthulhu_touch_click(locator.display, C.int(x), C.int(y), C.int(button)) != 0 +} + +// Scroll turns the mouse wheel at a point: positive steps scroll down. +func (locator *WindowLocator) Scroll(x, y, steps int) bool { + button := 5 + if steps < 0 { + button, steps = 4, -steps + } + for range steps { + if !locator.Click(x, y, button) { + return false + } + } + return true +} + +// Touch desktop keys. Values are X keysyms. +const ( + KeyTab = 0xff09 + KeyEscape = 0xff1b + KeyMenu = 0xff67 +) + +// Key presses and releases one key, with Shift held when shift is set. +func (locator *WindowLocator) Key(keysym uint32, shift bool) bool { + if locator == nil || locator.display == nil { + return false + } + value := C.int(0) + if shift { + value = 1 + } + return C.cthulhu_touch_key(locator.display, C.ulong(keysym), value) != 0 +} + +func (locator *WindowLocator) Close() { + if locator != nil && locator.display != nil { + C.cthulhu_window_locator_close(locator.display) + locator.display = nil + } +} diff --git a/internal/platform/xorg/touch_native.c b/internal/platform/xorg/touch_native.c new file mode 100644 index 0000000..3e21741 --- /dev/null +++ b/internal/platform/xorg/touch_native.c @@ -0,0 +1,157 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// X11 helpers for touch screen support. Touch input itself is read from the +// Linux input layer; X11 only finds the client under a point and performs +// activation clicks. + +#include "touch_native.h" +#include "commands_native.h" +#include +#include +#include +#include + +Display *cthulhu_window_locator_open(void) { return XOpenDisplay(NULL); } + +void cthulhu_window_locator_close(Display *display) { + if (display) XCloseDisplay(display); +} + +void cthulhu_screen_size(Display *display, int *width, int *height) { + *width = DisplayWidth(display, DefaultScreen(display)); + *height = DisplayHeight(display, DefaultScreen(display)); +} + +// Walk down from the root to the deepest window at the point and report the +// nearest _NET_WM_PID, falling back to XRes for the client owning the window. +int cthulhu_window_locator_pid(Display *display, int xres, int x, int y, unsigned long *window) { + Window root = DefaultRootWindow(display); + int pid = 0; + Window found = None, current = root, child = None; + Atom pidAtom = XInternAtom(display, "_NET_WM_PID", False); + cthulhu_x11_begin_read(display); + for (int depth = 0; depth < 32; depth++) { + int childX, childY; + if (!XTranslateCoordinates(display, root, current, x, y, &childX, &childY, &child) || + child == None) break; + current = child; + Atom type = None; int format = 0; unsigned long items = 0, after = 0; + unsigned char *data = NULL; + if (XGetWindowProperty(display, current, pidAtom, 0, 1, False, XA_CARDINAL, &type, + &format, &items, &after, &data) == Success && + data && type == XA_CARDINAL && format == 32 && items == 1) { + pid = (int)((unsigned long *)data)[0]; + found = current; + } + if (data) XFree(data); + } + if (cthulhu_x11_end_read(display)) pid = 0; + // The XRes helpers take the X11 guard themselves and the guard is not + // recursive, so they must run only after it is released above. + if (pid <= 0 && current != root && xres) { + pid = cthulhu_xres_client_pid(display, current); + found = current; + } + if (window) *window = pid > 0 ? found : None; + return pid > 0 ? pid : 0; +} + +static int cthulhu_window_title_once(Display *display, Window window, char *title, int size) { + Atom netName = XInternAtom(display, "_NET_WM_NAME", False); + Atom utf8 = XInternAtom(display, "UTF8_STRING", False); + Atom type = None; int format = 0; unsigned long items = 0, after = 0; + unsigned char *data = NULL; + if (XGetWindowProperty(display, window, netName, 0, 256, False, utf8, &type, &format, + &items, &after, &data) == Success && data && type == utf8 && format == 8) { + snprintf(title, size, "%s", (char *)data); + } + if (data) XFree(data); + if (!title[0]) { + char *name = NULL; + if (XFetchName(display, window, &name) && name) { + snprintf(title, size, "%s", name); + XFree(name); + } + } + return title[0] != 0; +} + +// Copy a window's title into title, preferring the UTF-8 _NET_WM_NAME. An +// inner window without a title takes the nearest titled ancestor's. +int cthulhu_window_title(Display *display, unsigned long window, char *title, int size) { + if (!window || size < 1) return 0; + title[0] = 0; + Window root = DefaultRootWindow(display), current = (Window)window; + cthulhu_x11_begin_read(display); + for (int depth = 0; depth < 16 && current != None && current != root; depth++) { + if (cthulhu_window_title_once(display, current, title, size)) break; + Window queryRoot, parent = None, *children = NULL; + unsigned int count = 0; + if (!XQueryTree(display, current, &queryRoot, &parent, &children, &count)) break; + if (children) XFree(children); + current = parent; + } + if (cthulhu_x11_end_read(display)) title[0] = 0; + return title[0] != 0; +} + +// Press and release one key, optionally with Shift, for touch desktop +// gestures such as Tab and Escape. +int cthulhu_touch_key(Display *display, unsigned long keysym, int shift) { + int event, error, major, minor; + if (!XTestQueryExtension(display, &event, &error, &major, &minor)) return 0; + KeyCode code = XKeysymToKeycode(display, (KeySym)keysym); + KeyCode shiftCode = XKeysymToKeycode(display, XK_Shift_L); + if (!code || (shift && !shiftCode)) return 0; + cthulhu_x11_begin_read(display); + char keys[32]; + XQueryKeymap(display, keys); + // Do not release a physical key or modifier the user is already holding. + if (keys[code / 8] & (1 << (code % 8))) { + cthulhu_x11_end_read(display); + return 0; + } + KeyCode rightShift = XKeysymToKeycode(display, XK_Shift_R); + int ownShift = shift && !(keys[shiftCode / 8] & (1 << (shiftCode % 8))) && + !(rightShift && (keys[rightShift / 8] & (1 << (rightShift % 8)))); + int ok = 1; + if (ownShift) ok = XTestFakeKeyEvent(display, shiftCode, True, CurrentTime); + if (ok) { + int pressed = XTestFakeKeyEvent(display, code, True, CurrentTime); + int released = XTestFakeKeyEvent(display, code, False, CurrentTime); + ok = pressed && released; + } + if (ownShift) XTestFakeKeyEvent(display, shiftCode, False, CurrentTime); + XSync(display, False); + if (cthulhu_x11_end_read(display)) ok = 0; + return ok; +} + +// Activate by clicking at a point, then put the pointer back so mouse review +// and the user's pointer position are undisturbed. +int cthulhu_touch_click(Display *display, int x, int y, int button) { + int event, error, major, minor; + if (!XTestQueryExtension(display, &event, &error, &major, &minor)) return 0; + Window root = DefaultRootWindow(display), queryRoot, child; + int pointerX = 0, pointerY = 0, winX, winY; + unsigned int mask; + int width, height; + cthulhu_screen_size(display, &width, &height); + if (x < 0 || y < 0 || x >= width || y >= height) return 0; + cthulhu_x11_begin_read(display); + int known = XQueryPointer(display, root, &queryRoot, &child, &pointerX, &pointerY, + &winX, &winY, &mask); + int ok = XTestFakeMotionEvent(display, -1, x, y, CurrentTime); + XSync(display, False); + if (ok) { + int pressed = XTestFakeButtonEvent(display, button, True, CurrentTime); + XSync(display, False); + int released = XTestFakeButtonEvent(display, button, False, CurrentTime); + ok = pressed && released; + } + if (known) XTestFakeMotionEvent(display, -1, pointerX, pointerY, CurrentTime); + if (cthulhu_x11_end_read(display)) ok = 0; + return ok; +} diff --git a/internal/platform/xorg/touch_native.h b/internal/platform/xorg/touch_native.h new file mode 100644 index 0000000..4326532 --- /dev/null +++ b/internal/platform/xorg/touch_native.h @@ -0,0 +1,20 @@ +#ifndef CTHULHU_TOUCH_NATIVE_H +#define CTHULHU_TOUCH_NATIVE_H + +#include + +Display *cthulhu_window_locator_open(void); +void cthulhu_window_locator_close(Display *display); +void cthulhu_screen_size(Display *display, int *width, int *height); +int cthulhu_xres_client_pids_supported(Display *display); +// Takes and releases the X11 guard; the caller must not hold it. +int cthulhu_window_locator_pid(Display *display, int xres, int x, int y, unsigned long *window); +// Takes and releases the X11 guard; the caller must not hold it. +int cthulhu_touch_click(Display *display, int x, int y, int button); +// Takes and releases the X11 guard; the caller must not hold it. +int cthulhu_touch_key(Display *display, unsigned long keysym, int shift); + +// Takes and releases the X11 guard; the caller must not hold it. +int cthulhu_window_title(Display *display, unsigned long window, char *title, int size); + +#endif diff --git a/internal/platform/xorg/touch_native_test.go b/internal/platform/xorg/touch_native_test.go new file mode 100644 index 0000000..c965847 --- /dev/null +++ b/internal/platform/xorg/touch_native_test.go @@ -0,0 +1,111 @@ +package xorg + +import ( + "context" + "os" + "os/exec" + "strconv" + "strings" + "testing" + "time" +) + +// A client window without _NET_WM_PID sends the lookup to the XRes fallback. +// That fallback used to take the X11 guard while the lookup already held it. +// The guard is not recursive, so the lookup hung and every other X11 reader in +// the process hung behind it, silencing the screen reader. +func TestNativeWindowLocatorFallbackReleasesGuard(t *testing.T) { + if os.Getenv("CTHULHU_NATIVE_X11") != "1" { + t.Skip("requires isolated X11 display") + } + for _, tool := range []string{"xterm", "xdotool", "xprop"} { + if _, err := exec.LookPath(tool); err != nil { + t.Skipf("requires %s", tool) + } + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + client := exec.CommandContext(ctx, "xterm", "-T", "Touch fixture", "-geometry", "40x10+100+100", "-class", "CthulhuTouchFixture") + if err := client.Start(); err != nil { + t.Fatal(err) + } + defer func() { _ = client.Process.Kill(); _ = client.Wait() }() + out, err := exec.CommandContext(ctx, "xdotool", "search", "--sync", "--class", "CthulhuTouchFixture").Output() + if err != nil { + t.Fatalf("fixture window: %v", err) + } + window := strings.Fields(string(out))[0] + if err := exec.CommandContext(ctx, "xprop", "-id", window, "-remove", "_NET_WM_PID").Run(); err != nil { + t.Fatalf("remove _NET_WM_PID: %v", err) + } + + locator := OpenWindowLocator() + if locator == nil { + t.Fatal("window locator unavailable") + } + defer locator.Close() + pointer := OpenPointerReader() + if pointer == nil { + t.Fatal("pointer reader unavailable") + } + defer pointer.Close() + + type result struct { + pid int + title string + } + done := make(chan result, 1) + go func() { + pid, window := locator.WindowAt(140, 130) + title := locator.WindowTitle(window) + // Another guarded reader must still get the guard afterwards. + pointer.Read() + done <- result{pid, title} + }() + select { + case got := <-done: + if locator.xres != 0 && got.pid != client.Process.Pid { + t.Fatalf("XRes fallback found pid %d, want xterm %d", got.pid, client.Process.Pid) + } + if got.title == "" { + t.Fatal("the window under the point has no title; the nearest titled ancestor was not found") + } + t.Logf("xres=%d pid=%s title=%q", locator.xres, strconv.Itoa(got.pid), got.title) + case <-time.After(3 * time.Second): + t.Fatal("window lookup left the X11 guard held") + } +} + +func TestNativeTouchKeyPreservesHeldKeys(t *testing.T) { + if os.Getenv("CTHULHU_NATIVE_X11") != "1" { + t.Skip("requires isolated X11 display") + } + target, err := openRemoteKeyTarget() + if err != nil { + t.Fatal(err) + } + defer target.close() + locator := OpenWindowLocator() + if locator == nil { + t.Fatal("no locator") + } + defer locator.Close() + for _, name := range []string{"Shift_L", "Shift_R", "Tab"} { + code, err := target.backend.Resolve(name) + if err != nil { + t.Fatal(err) + } + if err := target.backend.Set(code, true); err != nil { + t.Fatal(err) + } + ok := locator.Key(KeyTab, true) + held, err := target.backend.Held(code) + target.backend.Set(code, false) + if err != nil || !held { + t.Fatalf("touch released held %s: %v", name, err) + } + if ok == (name == "Tab") { + t.Fatalf("key result for held %s = %v", name, ok) + } + } +} diff --git a/internal/preferences/native_reading.c b/internal/preferences/native_reading.c index 7f4012a..599b1eb 100644 --- a/internal/preferences/native_reading.c +++ b/internal/preferences/native_reading.c @@ -71,6 +71,8 @@ static const struct { const char *id; const char *label; const char *description "Reads tooltip text when the application displays it."}, {"enable_mouse_review", "Speak object under mouse", "Reads the object under the mouse pointer as you move the mouse."}, + {"enable_touch_screen", "Use the touch screen with gestures", + "Cthulhu takes over the touch screen. Drag a finger to hear what is under it, double tap to activate, and tap with two fingers to stop speech. Touches no longer go straight to applications while this is on."}, {"say_all_context_blockquote", "Announce block quotes in Say All", "Announces entry into and exit from block quotes during continuous reading with Say All. This is separate from navigation announcements."}, {"say_all_context_list", "Announce lists in Say All", diff --git a/internal/preferences/reading.go b/internal/preferences/reading.go index f038652..1bcc4dd 100644 --- a/internal/preferences/reading.go +++ b/internal/preferences/reading.go @@ -60,6 +60,7 @@ func readingChecks(values *Values) []struct { {"use_color_names", &values.Reading.UseColorNames}, {"present_tooltips", &values.Reading.PresentTooltips}, {"enable_mouse_review", &values.Reading.EnableMouseReview}, + {"enable_touch_screen", &values.Reading.EnableTouchScreen}, {"speak_misspelled_indicator", &values.Reading.SpeakMisspelledIndicator}, {"speak_context_blockquote", &values.Reading.SpeakContextBlockquote}, {"speak_context_list", &values.Reading.SpeakContextList}, diff --git a/internal/review/cursor.go b/internal/review/cursor.go index 54f4760..8e15ec0 100644 --- a/internal/review/cursor.go +++ b/internal/review/cursor.go @@ -38,6 +38,10 @@ const ( FirstChild PreviousSibling NextSibling + // NextItem and PreviousItem walk the window in reading order, skipping + // unnamed containers, like TalkBack's linear navigation. + NextItem + PreviousItem ) func (direction Direction) String() string { @@ -50,6 +54,10 @@ func (direction Direction) String() string { return "previous-sibling" case NextSibling: return "next-sibling" + case NextItem: + return "next-item" + case PreviousItem: + return "previous-item" default: return fmt.Sprintf("direction(%d)", direction) } @@ -144,6 +152,10 @@ func (cursor *Cursor) Move(direction Direction) (position Position, moved bool, next, ok, err = cursor.tree.PreviousSibling(cursor.current) case NextSibling: next, ok, err = cursor.tree.NextSibling(cursor.current) + case NextItem: + next, ok, err = cursor.itemLocked(true) + case PreviousItem: + next, ok, err = cursor.itemLocked(false) default: return Position{}, false, fmt.Errorf("%w: %d", ErrInvalidDirection, direction) } diff --git a/internal/review/items.go b/internal/review/items.go new file mode 100644 index 0000000..259c369 --- /dev/null +++ b/internal/review/items.go @@ -0,0 +1,128 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package review + +import ( + "strings" + + "git.stormux.org/storm/cthulhu/internal/atspi" +) + +// maxItemSteps bounds one item move, so a huge or malformed tree can never +// keep the review worker busy. +const maxItemSteps = 4000 + +// Unnamed layout containers are not items: item navigation and touch +// exploration skip them, as TalkBack and VoiceOver do. Named ones, such as a +// named landmark or toolbar, are items. +var itemSkippedRoles = map[string]bool{ + "section": true, "panel": true, "landmark": true, "filler": true, "grouping": true, + "layered pane": true, "scroll pane": true, "split pane": true, "viewport": true, + "tool bar": true, "internal frame": true, "redundant object": true, "unknown": true, +} + +// ItemSkips reports whether item navigation passes over an object. +func ItemSkips(snapshot atspi.Snapshot) bool { + return itemSkippedRoles[snapshot.Role] && strings.TrimSpace(snapshot.Name) == "" +} + +// topLevelLocked reports whether reference is a window: its parent is an +// application or it has no parent. Item navigation never leaves a window. +func (cursor *Cursor) topLevelLocked(reference atspi.ObjectReference) (bool, error) { + parent, ok, err := cursor.tree.Parent(reference) + if err != nil || !ok { + return true, err + } + snapshot, err := cursor.tree.Resolve(parent) + if err != nil { + return true, err + } + return snapshot.Role == "application" || snapshot.Role == "desktop frame", nil +} + +// adjacentLocked returns the next or previous object in reading order, which +// is a depth-first walk of the window. +func (cursor *Cursor) adjacentLocked(reference atspi.ObjectReference, forward bool) (atspi.ObjectReference, bool, error) { + tree := cursor.tree + if forward { + if child, ok, err := tree.FirstChild(reference); err != nil || ok { + return child, ok, err + } + for node, depth := reference, 0; depth < maxItemSteps; depth++ { + top, err := cursor.topLevelLocked(node) + if err != nil || top { + return atspi.ObjectReference{}, false, err + } + if sibling, ok, err := tree.NextSibling(node); err != nil || ok { + return sibling, ok, err + } + parent, ok, err := tree.Parent(node) + if err != nil || !ok { + return atspi.ObjectReference{}, false, err + } + node = parent + } + return atspi.ObjectReference{}, false, nil + } + top, err := cursor.topLevelLocked(reference) + if err != nil || top { + return atspi.ObjectReference{}, false, err + } + sibling, ok, err := tree.PreviousSibling(reference) + if err != nil { + return atspi.ObjectReference{}, false, err + } + if !ok { + return tree.Parent(reference) + } + // The previous item is the last object inside the previous sibling. + for node, depth := sibling, 0; depth < maxItemSteps; depth++ { + child, ok, err := tree.LastChild(node) + if err != nil { + return atspi.ObjectReference{}, false, err + } + if !ok { + return node, true, nil + } + node = child + } + return sibling, true, nil +} + +// itemLocked finds the next or previous item, skipping unnamed containers. +func (cursor *Cursor) itemLocked(forward bool) (atspi.ObjectReference, bool, error) { + current := cursor.current + for step := 0; step < maxItemSteps; step++ { + next, ok, err := cursor.adjacentLocked(current, forward) + if err != nil || !ok { + return atspi.ObjectReference{}, false, err + } + snapshot, err := cursor.tree.Resolve(next) + if err != nil { + return atspi.ObjectReference{}, false, err + } + if !ItemSkips(snapshot) { + return next, true, nil + } + current = next + } + return atspi.ObjectReference{}, false, nil +} + +// Set moves the cursor to an object in its tree without a focus change, for +// example the object a finger explored on the touch screen. +func (cursor *Cursor) Set(id atspi.ObjectID) error { + cursor.mu.Lock() + defer cursor.mu.Unlock() + reference, err := cursor.tree.Reference(id) + if err != nil { + return err + } + if _, err := cursor.tree.Resolve(reference); err != nil { + return err + } + cursor.setCurrentLocked(reference) + return nil +} diff --git a/internal/review/items_test.go b/internal/review/items_test.go new file mode 100644 index 0000000..85c1cd5 --- /dev/null +++ b/internal/review/items_test.go @@ -0,0 +1,172 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package review + +import ( + "testing" + "time" + + "git.stormux.org/storm/cthulhu/internal/atspi" +) + +func roleNode(path, name, role string, children ...string) atspi.TreeNode { + snapshot := atspi.NewSnapshot(path, name, role, "", "") + snapshot.BusName = ":1.42" + ids := make([]atspi.ObjectID, len(children)) + for i, child := range children { + ids[i] = objectID(child) + } + return atspi.TreeNode{Snapshot: snapshot, Children: ids} +} + +// application +// +// frame "Window" +// section (unnamed) +// link "One" +// paragraph "Two" +// link "Inner" +// panel (unnamed) +// push button "Three" +// frame "Other" +// push button "Elsewhere" +func itemTree(t *testing.T) *atspi.AccessibleTree { + t.Helper() + tree, err := atspi.NewAccessibleTree(objectID("/app"), []atspi.TreeNode{ + roleNode("/app", "Browser", "application", "/window", "/other"), + roleNode("/window", "Window", "frame", "/section", "/panel"), + roleNode("/section", "", "section", "/one", "/two"), + roleNode("/one", "One", "link"), + roleNode("/two", "Two", "paragraph", "/inner"), + roleNode("/inner", "Inner", "link"), + roleNode("/panel", "", "panel", "/three"), + roleNode("/three", "Three", "push button"), + roleNode("/other", "Other", "frame", "/elsewhere"), + roleNode("/elsewhere", "Elsewhere", "push button"), + }) + if err != nil { + t.Fatal(err) + } + return tree +} + +func walk(t *testing.T, cursor *Cursor, direction Direction) []string { + t.Helper() + var names []string + for range 20 { + position, moved, err := cursor.Move(direction) + if err != nil { + t.Fatal(err) + } + if !moved { + return names + } + names = append(names, position.Current.Name) + } + t.Fatal("item navigation did not stop at the window edge") + return nil +} + +func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestBehaviorNextItemReadsTheWindowInOrderAndStopsAtItsEnd(t *testing.T) { + cursor, err := NewCursor(itemTree(t)) + if err != nil { + t.Fatal(err) + } + if _, err := cursor.SyncFocus(objectID("/one")); err != nil { + t.Fatal(err) + } + if got, want := walk(t, cursor, NextItem), []string{"Two", "Inner", "Three"}; !equal(got, want) { + t.Fatalf("next items = %v, want %v", got, want) + } + position, _ := cursor.Current() + if position.Current.Name != "Three" { + t.Fatalf("a failed move must stay on the last item, got %q", position.Current.Name) + } +} + +func TestBehaviorPreviousItemWalksBackToTheWindow(t *testing.T) { + cursor, err := NewCursor(itemTree(t)) + if err != nil { + t.Fatal(err) + } + if _, err := cursor.SyncFocus(objectID("/three")); err != nil { + t.Fatal(err) + } + if got, want := walk(t, cursor, PreviousItem), []string{"Inner", "Two", "One", "Window"}; !equal(got, want) { + t.Fatalf("previous items = %v, want %v", got, want) + } +} + +func TestBehaviorSetMovesReviewWithoutFocus(t *testing.T) { + cursor, err := NewCursor(itemTree(t)) + if err != nil { + t.Fatal(err) + } + if _, err := cursor.SyncFocus(objectID("/one")); err != nil { + t.Fatal(err) + } + if err := cursor.Set(objectID("/inner")); err != nil { + t.Fatal(err) + } + position, moved, err := cursor.Move(NextItem) + if err != nil || !moved || position.Current.Name != "Three" { + t.Fatalf("next item after set = %q, moved %v, error %v", position.Current.Name, moved, err) + } + // The same focus again must not pull review back from the touched object. + if position, err := cursor.SyncFocus(objectID("/one")); err != nil || position.Current.Name != "Three" { + t.Fatalf("unchanged focus moved review to %q, error %v", position.Current.Name, err) + } + if err := cursor.Set(objectID("/missing")); err == nil { + t.Fatal("setting an object outside the tree must fail") + } +} + +func TestBehaviorItemSkipsOnlyUnnamedContainers(t *testing.T) { + for _, tc := range []struct { + role, name string + skip bool + }{ + {"section", "", true}, {"panel", " ", true}, {"landmark", "", true}, {"tool bar", "", true}, + {"tool bar", "Bookmarks", false}, {"landmark", "Main", false}, + {"link", "", false}, {"push button", "", false}, {"entry", "", false}, + } { + if got := ItemSkips(atspi.Snapshot{Role: tc.role, Name: tc.name}); got != tc.skip { + t.Errorf("role %q name %q: skip=%v, want %v", tc.role, tc.name, got, tc.skip) + } + } +} + +// A touch user may never produce a focus event. Touching an object must still +// give item navigation a starting point. +func TestBehaviorReviewObjectWorksWithoutAnyFocus(t *testing.T) { + capturer := &fakeCapturer{calls: make(chan captureCall, 1)} + worker, cancel := startWorker(t, capturer, time.Second) + defer cancel() + tree := itemTree(t) + if err := worker.ReviewObject(objectID("/one")); err != nil { + t.Fatal(err) + } + call := <-capturer.calls + call.result <- captureResult{tree: tree} + if err := worker.Move(NextItem); err != nil { + t.Fatal(err) + } + result := waitResult(t, worker) + if result.Err != nil || !result.Moved || result.Position.Current.Name != "Two" { + t.Fatalf("next item without focus = %q, moved %v, error %v", result.Position.Current.Name, result.Moved, result.Err) + } +} diff --git a/internal/review/object_worker.go b/internal/review/object_worker.go index 5fe1c72..58c23ec 100644 --- a/internal/review/object_worker.go +++ b/internal/review/object_worker.go @@ -110,3 +110,58 @@ func (worker *Worker) captureCursor(ctx context.Context, cursor *Cursor) (*Curso } return cursor, nil } + +// ReviewObject moves object review to an object without speaking, for example +// the object a finger explored on the touch screen, so item navigation +// continues from there. It is queued in order with navigation. +func (worker *Worker) ReviewObject(id atspi.ObjectID) error { + if !id.Valid() { + return errors.New("review object: invalid identity") + } + select { + case worker.requests <- request{reviewObject: id}: + return nil + default: + return ErrRequestQueueFull + } +} + +// reviewObject places the cursor on id. A missing object recaptures the tree +// once, because the object may have appeared after the last capture. It +// works without a known focus: a touch user may never produce a focus event, +// so the touched object itself becomes the review position. +func (worker *Worker) reviewObject(ctx context.Context, cursor *Cursor, id atspi.ObjectID) (*Cursor, bool) { + cursor, err := worker.syncLatestFocus(ctx, cursor, true) + if err != nil { + return cursor, false + } + if cursor != nil && cursor.Set(id) == nil { + return cursor, true + } + recovered, err := worker.captureTree(ctx, cursor) + if err != nil { + return cursor, false + } + return recovered, recovered.Set(id) == nil +} + +// captureTree captures the desktop for a cursor, synchronizing it to focus +// only when a focus is known. +func (worker *Worker) captureTree(ctx context.Context, cursor *Cursor) (*Cursor, error) { + if worker.focus().Valid() { + return worker.captureCursor(ctx, cursor) + } + captureContext, cancelCapture := context.WithTimeout(ctx, worker.captureTimeout) + tree, err := worker.capturer.CaptureDesktop(captureContext) + cancelCapture() + if err != nil { + return nil, fmt.Errorf("capture object review tree: %w", err) + } + if tree == nil { + return nil, errors.New("capture object review tree: nil tree") + } + if cursor != nil && cursor.tree == tree { + return cursor, nil + } + return NewCursor(tree) +} diff --git a/internal/review/worker.go b/internal/review/worker.go index 106ef34..086676e 100644 --- a/internal/review/worker.go +++ b/internal/review/worker.go @@ -256,7 +256,7 @@ func (worker *Worker) ClearFocus() { // Move queues a semantic navigation request without waiting for AT-SPI. func (worker *Worker) Move(direction Direction) error { - if direction < Parent || direction > NextSibling { + if direction < Parent || direction > PreviousItem { return fmt.Errorf("%w: %d", ErrInvalidDirection, direction) } select { @@ -358,6 +358,18 @@ func (worker *Worker) run(ctx context.Context, done chan<- struct{}) { request.interest.result <- interestReply{interest, err} continue } + if request.reviewObject.Valid() { + if next, ok := worker.reviewObject(ctx, cursor, request.reviewObject); ok { + cursor = next + explicitInterest = objectInterest + worker.stateMutex.Lock() + interestFocus, interestRevision = worker.latestFocus, worker.focusRevision + worker.stateMutex.Unlock() + } else if next != nil { + cursor = next + } + continue + } if (request.whereAmI || request.currentLine || request.brailleRoute != nil || request.nativeCaret || request.readAll != nil || request.line || request.listSelection != nil || request.target != 0 || request.caretCommand != 0 || request.activate || request.fragment != "" || request.unit != 0) && request.documentEpoch != documentEpoch { if request.brailleRoute != nil { request.brailleRoute.done <- atspi.ErrStaleObject diff --git a/internal/review/worker_contract.go b/internal/review/worker_contract.go index 6f2e07b..c93c996 100644 --- a/internal/review/worker_contract.go +++ b/internal/review/worker_contract.go @@ -124,6 +124,7 @@ type request struct { listSelection *documentListSelection brailleRoute *documentBrailleRequest interest *interestRequest + reviewObject atspi.ObjectID nativeCaret bool nativeCaretFocus atspi.ObjectID nativeCaretOffset int diff --git a/internal/touch/recognizer.go b/internal/touch/recognizer.go new file mode 100644 index 0000000..293ed42 --- /dev/null +++ b/internal/touch/recognizer.go @@ -0,0 +1,406 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package touch turns raw touch screen contacts into screen reader gestures. +// It owns no native resources: callers feed timestamped contacts and call +// Tick so timers such as the multi-tap window can expire without new input. +package touch + +import ( + "math" + "time" +) + +type Phase int + +const ( + Begin Phase = iota + Update + End +) + +// Event is one contact change. At is a monotonic offset chosen by the caller. +type Event struct { + Phase Phase + ID uint32 + X, Y float64 + At time.Duration +} + +type Kind int + +const ( + None Kind = iota + Tap + DoubleTap + TripleTap + Hold + DoubleTapHold + FlickRight + FlickLeft + FlickUp + FlickDown + RotateClockwise + RotateCounterclockwise + Drag + Unclear +) + +var kindNames = [...]string{"none", "tap", "double tap", "triple tap", "hold", "double tap and hold", + "flick right", "flick left", "flick up", "flick down", "rotate clockwise", + "rotate counterclockwise", "drag", "unclear"} + +func (kind Kind) String() string { + if kind < 0 || int(kind) >= len(kindNames) { + return "unknown" + } + return kindNames[kind] +} + +// Gesture is a completed gesture. X and Y are where the first finger landed. +type Gesture struct { + Kind Kind + Fingers int + X, Y float64 +} + +type OutputType int + +const ( + GestureOutput OutputType = iota + // ExploreOutput reports the exploring finger's position while it moves. + ExploreOutput + // ExploreEndOutput reports that the exploring finger lifted. + ExploreEndOutput +) + +type Output struct { + Type OutputType + Gesture Gesture + X, Y float64 +} + +type Config struct { + TapDistance float64 // Path below this is a tap or hold. + FlickDistance float64 // Net movement at least this is a flick. + TapTime time.Duration // One finger; each extra finger adds TapTimePerFinger. + FlickTime time.Duration // One finger; each extra finger adds FlickTimePerFinger. + HoldTime time.Duration + MultiTapWindow time.Duration + // ExploreDelay is how long one still-down finger waits before exploring, + // so quick flicks and taps never speak the object under the finger first. + ExploreDelay time.Duration + TapTimePerFinger time.Duration + FlickTimePerFinger time.Duration + RotateDegrees float64 +} + +// DefaultConfig scales distances to the screen. The values were tuned on a +// 1920 pixel wide touch screen with a spoken gesture trainer. +func DefaultConfig(screenWidth int) Config { + width := float64(screenWidth) + if width <= 0 { + width = 1920 + } + return Config{ + TapDistance: width * 0.02, + FlickDistance: width * 0.05, + TapTime: 300 * time.Millisecond, + FlickTime: 450 * time.Millisecond, + HoldTime: 600 * time.Millisecond, + MultiTapWindow: 350 * time.Millisecond, + ExploreDelay: 200 * time.Millisecond, + TapTimePerFinger: 75 * time.Millisecond, + FlickTimePerFinger: 100 * time.Millisecond, + RotateDegrees: 35, + } +} + +// maxContacts bounds per-gesture state. Bouncing fingers and palms can add +// more contacts than fingers, so this is well above ten. +const maxContacts = 64 + +type contact struct { + id uint32 + order int + down bool + x0, y0, x, y, path float64 +} + +type Recognizer struct { + config Config + + contacts []contact + active int + maxFingers int + inProgress bool + start time.Duration + exploring bool + holdFired bool + followsTap bool // This touch began inside the multi-tap window of a pending tap. + + pendingTaps int + pendingFingers int + pendingUntil time.Duration + pending Gesture +} + +func New(config Config) *Recognizer { + return &Recognizer{config: config, contacts: make([]contact, 0, 16)} +} + +// Reset forgets every contact and pending tap, for example after the touch +// screen grab is released. +func (r *Recognizer) Reset() { + config := r.config + contacts := r.contacts[:0] + *r = Recognizer{config: config, contacts: contacts} +} + +// Exploring reports whether one finger is currently exploring. +func (r *Recognizer) Exploring() bool { return r.exploring } + +func (r *Recognizer) find(id uint32) *contact { + for index := range r.contacts { + if r.contacts[index].down && r.contacts[index].id == id { + return &r.contacts[index] + } + } + return nil +} + +func (r *Recognizer) reusableSlot() int { + for index := range r.contacts { + if !r.contacts[index].down && r.contacts[index].order >= 2 { + return index + } + } + return -1 +} + +func (r *Recognizer) first() *contact { + for index := range r.contacts { + if r.contacts[index].order == 0 { + return &r.contacts[index] + } + } + return nil +} + +func (r *Recognizer) Feed(event Event) []Output { + var out []Output + switch event.Phase { + case Begin: + if r.pendingTaps > 0 && !r.inProgress && event.At > r.pendingUntil { + out = r.flushPending(out) + } + if !r.inProgress { + r.contacts = r.contacts[:0] + r.active, r.maxFingers, r.exploring, r.holdFired = 0, 0, false, false + r.inProgress, r.start = true, event.At + r.followsTap = r.pendingTaps > 0 && event.At <= r.pendingUntil + } + if r.find(event.ID) != nil { + return out + } + added := contact{id: event.ID, order: len(r.contacts), down: true, + x0: event.X, y0: event.Y, x: event.X, y: event.Y} + if len(r.contacts) < maxContacts { + r.contacts = append(r.contacts, added) + } else if slot := r.reusableSlot(); slot >= 0 { + // Every contact must be tracked so its lift is counted. Reuse a + // lifted contact, keeping the first two for position and rotation. + added.order = r.contacts[slot].order + r.contacts[slot] = added + } else { + return out + } + r.active++ + if r.active > r.maxFingers { + r.maxFingers = r.active + } + case Update: + c := r.find(event.ID) + if c == nil { + return out + } + c.path += math.Hypot(event.X-c.x, event.Y-c.y) + c.x, c.y = event.X, event.Y + if r.exploring && c.order == 0 { + out = append(out, Output{Type: ExploreOutput, X: c.x, Y: c.y}) + } + // A finger that moves slowly away from the tap position, right after a + // tap, explores instead of waiting to become a double tap and hold. + if !r.exploring && r.followsTap && r.maxFingers == 1 && c.path >= r.config.TapDistance && + event.At-r.start >= r.config.ExploreDelay { + out = r.startExplore(out, c) + } + case End: + c := r.find(event.ID) + if c == nil { + return out + } + c.down = false + r.active-- + if r.active <= 0 { + out = r.finish(event.At, out) + } + } + return out +} + +// Tick runs timers. Call it regularly, for example every 30 milliseconds. +func (r *Recognizer) Tick(now time.Duration) []Output { + var out []Output + if r.inProgress && !r.exploring && !r.holdFired && r.active == 1 && r.maxFingers == 1 { + elapsed := now - r.start + c := r.first() + if c != nil && c.down { + if r.followsTap { + if elapsed >= r.config.HoldTime && c.path < r.config.TapDistance { + r.holdFired = true + r.pendingTaps = 0 + out = append(out, Output{Type: GestureOutput, + Gesture: Gesture{Kind: DoubleTapHold, Fingers: 1, X: c.x0, Y: c.y0}}) + } + } else if elapsed >= r.config.ExploreDelay { + out = r.startExplore(out, c) + } + } + } + if r.pendingTaps > 0 && !r.inProgress && now > r.pendingUntil { + out = r.flushPending(out) + } + return out +} + +func (r *Recognizer) startExplore(out []Output, c *contact) []Output { + if r.pendingTaps > 0 { + out = r.flushPending(out) + } + r.exploring, r.followsTap = true, false + return append(out, Output{Type: ExploreOutput, X: c.x, Y: c.y}) +} + +func (r *Recognizer) flushPending(out []Output) []Output { + gesture := r.pending + switch r.pendingTaps { + case 2: + gesture.Kind = DoubleTap + default: + gesture.Kind = Tap + } + r.pendingTaps = 0 + return append(out, Output{Type: GestureOutput, Gesture: gesture}) +} + +func (r *Recognizer) finish(at time.Duration, out []Output) []Output { + r.inProgress = false + if r.exploring { + r.exploring = false + c := r.first() + output := Output{Type: ExploreEndOutput} + if c != nil { + output.X, output.Y = c.x, c.y + } + return append(out, output) + } + if r.holdFired { + return out + } + gesture := r.classify(at) + follows := r.followsTap && gesture.Fingers == r.pendingFingers + if follows && gesture.Kind == Tap { + r.pendingTaps++ + r.pendingUntil = at + r.config.MultiTapWindow + if r.pendingTaps == 3 { + r.pendingTaps = 0 + gesture.X, gesture.Y = r.pending.X, r.pending.Y + gesture.Kind = TripleTap + out = append(out, Output{Type: GestureOutput, Gesture: gesture}) + } + return out + } + if follows && gesture.Kind == Hold && r.pendingTaps == 1 { + r.pendingTaps = 0 + gesture.Kind = DoubleTapHold + return append(out, Output{Type: GestureOutput, Gesture: gesture}) + } + if r.pendingTaps > 0 { + out = r.flushPending(out) + } + if gesture.Kind == Tap { + r.pending, r.pendingTaps, r.pendingFingers = gesture, 1, gesture.Fingers + r.pendingUntil = at + r.config.MultiTapWindow + return out + } + return append(out, Output{Type: GestureOutput, Gesture: gesture}) +} + +func (r *Recognizer) classify(at time.Duration) Gesture { + gesture := Gesture{Kind: Unclear, Fingers: r.maxFingers} + var dx, dy, path float64 + for _, c := range r.contacts { + dx += c.x - c.x0 + dy += c.y - c.y0 + path += c.path + } + if n := float64(len(r.contacts)); n > 0 { + dx, dy, path = dx/n, dy/n, path/n + } + if c := r.first(); c != nil { + gesture.X, gesture.Y = c.x0, c.y0 + } + // Extra fingers land and lift less together, but cap the allowance so a + // many finger hold never counts as a tap. + extra := time.Duration(min(max(gesture.Fingers-1, 0), 3)) + tapTime := r.config.TapTime + extra*r.config.TapTimePerFinger + flickTime := r.config.FlickTime + extra*r.config.FlickTimePerFinger + elapsed := at - r.start + distance := math.Hypot(dx, dy) + + if gesture.Fingers == 2 && len(r.contacts) >= 2 { + a, b := r.contacts[0], r.contacts[1] + turn := math.Atan2(b.y-a.y, b.x-a.x) - math.Atan2(b.y0-a.y0, b.x0-a.x0) + for turn > math.Pi { + turn -= 2 * math.Pi + } + for turn < -math.Pi { + turn += 2 * math.Pi + } + degrees := turn * 180 / math.Pi + // Screen y grows downward, so a positive turn looks clockwise. + if math.Abs(degrees) >= r.config.RotateDegrees && distance < r.config.FlickDistance*1.5 { + if degrees > 0 { + gesture.Kind = RotateClockwise + } else { + gesture.Kind = RotateCounterclockwise + } + return gesture + } + } + switch { + case path < r.config.TapDistance: + if elapsed < tapTime { + gesture.Kind = Tap + } else if elapsed >= r.config.HoldTime { + gesture.Kind = Hold + } + case distance >= r.config.FlickDistance && elapsed < flickTime: + if math.Abs(dx) > math.Abs(dy) { + if dx > 0 { + gesture.Kind = FlickRight + } else { + gesture.Kind = FlickLeft + } + } else if dy > 0 { + gesture.Kind = FlickDown + } else { + gesture.Kind = FlickUp + } + case elapsed >= flickTime: + gesture.Kind = Drag + } + return gesture +} diff --git a/internal/touch/recognizer_test.go b/internal/touch/recognizer_test.go new file mode 100644 index 0000000..4b56127 --- /dev/null +++ b/internal/touch/recognizer_test.go @@ -0,0 +1,226 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package touch + +import ( + "math" + "testing" + "time" +) + +const ms = time.Millisecond + +// player feeds scripted contacts and ticks every 10 ms like the live loop. +type player struct { + t *testing.T + r *Recognizer + now time.Duration + out []Output +} + +func newPlayer(t *testing.T) *player { + return &player{t: t, r: New(DefaultConfig(1920))} +} + +func (p *player) wait(d time.Duration) { + for end := p.now + d; p.now < end; { + p.now += 10 * ms + p.out = append(p.out, p.r.Tick(p.now)...) + } +} + +func (p *player) feed(phase Phase, id uint32, x, y float64) { + p.out = append(p.out, p.r.Feed(Event{Phase: phase, ID: id, X: x, Y: y, At: p.now})...) +} + +// stroke moves fingers from their start points by dx, dy over d, then lifts. +func (p *player) stroke(fingers int, x, y, dx, dy float64, d time.Duration) { + for f := 0; f < fingers; f++ { + p.feed(Begin, uint32(100+f), x+float64(f)*80, y) + } + steps := max(int(d/(10*ms)), 1) + for s := 1; s <= steps; s++ { + p.wait(10 * ms) + for f := 0; f < fingers; f++ { + p.feed(Update, uint32(100+f), x+float64(f)*80+dx*float64(s)/float64(steps), y+dy*float64(s)/float64(steps)) + } + } + for f := 0; f < fingers; f++ { + p.feed(End, uint32(100+f), 0, 0) + } +} + +func (p *player) tap(fingers int) { p.stroke(fingers, 500, 500, 0, 0, 50*ms) } + +func (p *player) gestures() []Gesture { + var list []Gesture + for _, o := range p.out { + if o.Type == GestureOutput { + list = append(list, o.Gesture) + } + } + return list +} + +func (p *player) expectOnly(kind Kind, fingers int) { + p.t.Helper() + p.wait(500 * ms) + got := p.gestures() + if len(got) != 1 || got[0].Kind != kind || got[0].Fingers != fingers { + p.t.Fatalf("want one %d finger %s, got %+v", fingers, kind, got) + } +} + +func TestBehaviorTapsWaitForTheMultiTapWindow(t *testing.T) { + for _, tc := range []struct { + taps, fingers int + kind Kind + }{ + {1, 1, Tap}, {2, 1, DoubleTap}, {3, 1, TripleTap}, + {1, 2, Tap}, {2, 2, DoubleTap}, {3, 2, TripleTap}, + {1, 3, Tap}, {2, 3, DoubleTap}, {1, 4, Tap}, + } { + p := newPlayer(t) + for i := 0; i < tc.taps; i++ { + if i > 0 { + p.wait(120 * ms) + } + p.tap(tc.fingers) + } + p.expectOnly(tc.kind, tc.fingers) + } +} + +func TestBehaviorFlicksInEveryDirection(t *testing.T) { + for _, tc := range []struct { + dx, dy float64 + kind Kind + }{{400, 0, FlickRight}, {-400, 0, FlickLeft}, {0, -400, FlickUp}, {0, 400, FlickDown}} { + for fingers := 1; fingers <= 4; fingers++ { + p := newPlayer(t) + p.stroke(fingers, 800, 600, tc.dx, tc.dy, 100*ms) + p.expectOnly(tc.kind, fingers) + } + } +} + +func TestBehaviorOneFingerHoldExploresInsteadOfGesturing(t *testing.T) { + p := newPlayer(t) + p.feed(Begin, 1, 300, 300) + p.wait(250 * ms) + if !p.r.Exploring() { + t.Fatal("finger held past the explore delay should explore") + } + p.feed(Update, 1, 600, 300) + p.feed(End, 1, 0, 0) + p.wait(500 * ms) + var explores, ends int + for _, o := range p.out { + switch o.Type { + case ExploreOutput: + explores++ + case ExploreEndOutput: + ends++ + } + } + if explores != 2 || ends != 1 || len(p.gestures()) != 0 { + t.Fatalf("want 2 explore positions, 1 end and no gesture, got %+v", p.out) + } +} + +func TestBehaviorQuickFlickNeverExplores(t *testing.T) { + p := newPlayer(t) + p.stroke(1, 800, 600, 400, 0, 120*ms) + p.wait(500 * ms) + for _, o := range p.out { + if o.Type == ExploreOutput { + t.Fatalf("a quick flick must not speak what is under the finger: %+v", p.out) + } + } +} + +func TestBehaviorDoubleTapAndHoldFiresWhileStillDown(t *testing.T) { + p := newPlayer(t) + p.tap(1) + p.wait(100 * ms) + p.feed(Begin, 7, 500, 500) + p.wait(700 * ms) + got := p.gestures() + if len(got) != 1 || got[0].Kind != DoubleTapHold { + t.Fatalf("want double tap and hold before lifting, got %+v", got) + } + p.feed(End, 7, 0, 0) + p.wait(500 * ms) + if len(p.gestures()) != 1 { + t.Fatalf("lifting after double tap and hold must add nothing, got %+v", p.gestures()) + } +} + +func TestBehaviorMultiFingerHold(t *testing.T) { + p := newPlayer(t) + p.stroke(2, 500, 500, 0, 0, 900*ms) + p.expectOnly(Hold, 2) +} + +func TestBehaviorTwoFingerRotation(t *testing.T) { + for _, tc := range []struct { + degrees float64 + kind Kind + }{{60, RotateClockwise}, {-60, RotateCounterclockwise}} { + p := newPlayer(t) + cx, cy, radius := 900.0, 600.0, 100.0 + p.feed(Begin, 1, cx-radius, cy) + p.feed(Begin, 2, cx+radius, cy) + for s := 1; s <= 12; s++ { + p.wait(10 * ms) + a := tc.degrees * float64(s) / 12 * math.Pi / 180 + p.feed(Update, 1, cx-radius*math.Cos(a), cy-radius*math.Sin(a)) + p.feed(Update, 2, cx+radius*math.Cos(a), cy+radius*math.Sin(a)) + } + p.feed(End, 1, 0, 0) + p.feed(End, 2, 0, 0) + p.expectOnly(tc.kind, 2) + } +} + +func TestBehaviorTenFingersAndBouncingContactsStayBounded(t *testing.T) { + p := newPlayer(t) + for id := uint32(1); id <= 10; id++ { + p.feed(Begin, id, float64(id)*100, 500) + } + // Bounces: a finger briefly lifts and lands again as a new contact. Far + // more contacts than the per-gesture bound must not lose any lift. + current := [10]uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + next := uint32(11) + for bounce := 0; bounce < 80; bounce++ { + finger := bounce % 10 + p.feed(End, current[finger], 0, 0) + p.feed(Begin, next, float64(finger+1)*100, 500) + current[finger] = next + next++ + } + p.wait(800 * ms) + for _, id := range current { + p.feed(End, id, 0, 0) + } + p.wait(500 * ms) + if p.r.inProgress || p.r.active != 0 { + t.Fatalf("gesture must finish when every finger lifts, active=%d", p.r.active) + } + got := p.gestures() + if len(got) != 1 || got[0].Fingers != 10 || got[0].Kind != Hold { + t.Fatalf("want one 10 finger hold, got %+v", got) + } +} + +func TestBehaviorResetDropsPendingTap(t *testing.T) { + p := newPlayer(t) + p.tap(1) + p.r.Reset() + p.wait(500 * ms) + if len(p.gestures()) != 0 { + t.Fatalf("reset must drop the pending tap, got %+v", p.gestures()) + } +} diff --git a/internal/version/version.go b/internal/version/version.go index e58ec71..82e974c 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -21,7 +21,7 @@ import "strings" const Name = "Cthulhu" -const Version = "2026.11.19" +const Version = "2026.11.24" const Channel = "testing" var Build = Version