More capabilities for tentacles, for an upcoming one
This commit is contained in:
1 parent
ffc5107112
commit
a34d7e70c8
53 files changed
+2670
-57
No files matched your search
@@ -0,0 +1,44 @@
|
||||
# Application-scoped Tentacle commands
|
||||
|
||||
Protocol 1.1 optionally negotiates the `application-bindings` API. It is an API,
|
||||
not an automation permission, and requires neither presentation nor interaction.
|
||||
The Go and Python SDKs expose the `application` command field. Older readers
|
||||
reject packages requesting the unsupported API before starting them.
|
||||
|
||||
A command may declare `application: "Example App"` and propose global bindings
|
||||
within that application. The selector is an exact X11 WM_CLASS instance or class,
|
||||
containing 1–127 bytes of nonempty printable UTF-8. Titles and wildcard patterns
|
||||
are never interpreted. Scope declarations require the negotiated API; protocol
|
||||
1.0 and ungranted declarations cannot opt in silently.
|
||||
|
||||
Local development specs opt in with `SessionEvents: true` and
|
||||
`ApplicationBindings: true`. Native package manifests include `session-events`
|
||||
and `application-bindings` in their API list and protocol minor 1. Registry entries
|
||||
persist the API opt-in separately from install permissions.
|
||||
|
||||
Application shortcuts use passive grabs on the matching client window, leaving
|
||||
the desktop root window available to other shortcut owners. Core global commands,
|
||||
explicit user assignments and earlier Tentacles retain priority. Unmodified
|
||||
browser defaults apply outside the selected application. An ancestor/global X11
|
||||
shortcut owner may still take priority over a client-window shortcut.
|
||||
|
||||
The input owner refreshes application context on its bounded focus poll after
|
||||
held chords release. Activation can take up to one poll interval (100 ms).
|
||||
Inactive application bindings introduce no per-chord native metadata queries.
|
||||
Native admission rechecks actual focus and class, while the ordinary browse/OCR
|
||||
source checks retain their own anchors. Changing application bindings never
|
||||
retargets an existing OCR result to a different window.
|
||||
|
||||
Unavailable or conflicting client grabs disable only the optional application
|
||||
bindings. All client grabs are removed after a partial failure, core controls
|
||||
remain owned, and shortcut help marks the application commands unavailable.
|
||||
Re-entering the application or changing keyboard configuration retries them.
|
||||
Destroying a client window is an expected lifecycle event.
|
||||
|
||||
The Python/Go 1.0 and ordinary 1.1 contracts remain unchanged. Existing unscoped
|
||||
Tentacle shortcuts retain the prior OCR input-retirement policy. Application
|
||||
commands have no mouse or OCR automation authority unless they separately declare
|
||||
and receive a separate automation permission.
|
||||
|
||||
X11 is supported. Native Wayland application shortcut registration is unavailable.
|
||||
These selectors provide scope, not application authentication or a sandbox.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Opt-in application automation
|
||||
|
||||
This extension builds on `application-bindings`. Protocol 1.1 negotiates an
|
||||
additional `automation` API and install permission. It requires presentation,
|
||||
interaction and application bindings, but none of those permissions imply
|
||||
this new grant. Existing installations do not acquire automation authority.
|
||||
Older readers reject the unsupported API/permission during package validation.
|
||||
|
||||
An application command additionally declares `automation: true`. The host
|
||||
checks the declaration against the explicit install grant before activation.
|
||||
Returning an automation result from an ordinary interactive command grants no
|
||||
authority. The Go SDK exports `Automation`, `AutomationAction` and
|
||||
`Command.Automation`; Python uses the matching command flag and result dictionary.
|
||||
|
||||
Local development specs opt in with `SessionEvents`, `ApplicationBindings`,
|
||||
`Presentation`, `Interaction`, and `Automation` all true. Package manifests include
|
||||
`commands`, `session-events`, `presentation`, `interaction`, `application-bindings`
|
||||
and `automation` APIs, with `presentation`, `interaction`, and `automation`
|
||||
capabilities. Registry entries retain the automation grant across restart.
|
||||
Install confirmation names mouse/OCR control separately from forms/clipboard access.
|
||||
|
||||
A terminal interaction may return:
|
||||
|
||||
```json
|
||||
{"automation":{"actions":[{"kind":"move","x":5000,"y":5000},{"kind":"click","button":3,"modifier":"shift","milliseconds":20},{"kind":"delay","milliseconds":100},{"kind":"move","x":10000,"y":0}]},"done":true}
|
||||
```
|
||||
|
||||
It cannot combine with forms, continuations, clipboard/source requests, reader
|
||||
settings, remote requests, protected speech, or background leases. Up to 16 actions
|
||||
are admitted, with at most 2,000 ms of aggregate requested waits and a five-second
|
||||
worker deadline. The Tentacle owns shortcut choices and explicit action timing.
|
||||
|
||||
| Kind | Fields | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `move` | `x`, `y`, each 0–10000 | Move relative to the captured client rectangle, rounded and clamped inside it |
|
||||
| `click` | `button`: 1 or 3; optional `modifier`: `shift` or `control`; `milliseconds`: 0–1000 | Click at the pointer, holding the button for the requested duration |
|
||||
| `drag` | `x`, `y`, each 0–10000; `milliseconds`: 0–1000 | Left-button drag, waiting for the requested duration before and after motion |
|
||||
| `scroll` | nonzero `steps`: −100 to 100; `milliseconds`: 0–1000 | Wheel up/down, waiting for the requested duration between steps |
|
||||
| `delay` | `milliseconds`: 1–1000 | Cancellable wait |
|
||||
| `ocr-route` | none | First action only: route to the current recognized word |
|
||||
| `ocr-dismiss` | none | Retire OCR internally; send no Escape to the application |
|
||||
| `ocr-scan` | none | Last action only: start a window OCR scan with an X server timestamp cutoff |
|
||||
| `tone` | none | Optional reader feedback; playback failure does not block input |
|
||||
|
||||
Unrelated fields are rejected. The reader captures the application window,
|
||||
foreground epoch and client bounds before invoking the child, checks them between
|
||||
effects, and uses the secure-input gate at every injected step. It waits for
|
||||
captured chord release before injecting. Physical keys (including modifiers still
|
||||
held after the captured keys release) or mouse buttons cause refusal.
|
||||
It retires the old OCR result before mouse effects.
|
||||
|
||||
OCR routing retains a private capture snapshot and checks fresh pixels after
|
||||
shortcut release, immediately before routing. Native focus and frozen bounds
|
||||
protect the following route-to-click interval; normal hover highlights do not
|
||||
invalidate the click. Missing, clipboard, changed or unmapped results are refused.
|
||||
No OCR text or native handles reach the child.
|
||||
|
||||
Waits belong to cancellable Go code. Native steps atomically check class, focus
|
||||
and geometry before input; no wait holds the X server or secure-input mutex.
|
||||
Cleanup releases every synthetic button/modifier after cancellation, focus changes,
|
||||
locks or errors. Process revocation cancels the joined interaction worker. Commands
|
||||
are declined while an interaction is occupied rather than queued indefinitely.
|
||||
|
||||
X11 is supported; native Wayland automation is unavailable. The API provides
|
||||
reader-owned lifecycle checks, not an account sandbox or application authentication.
|
||||
Live application behavior, audible feedback and physical input need acceptance
|
||||
separate from protocol and private-display tests.
|
||||
@@ -297,6 +297,10 @@ func Run(ctx context.Context, options Options) error {
|
||||
tentacles.requests = make(chan tentacleManagementCall, 16)
|
||||
tentacles.snapshot.Message = "Loading tentacle configuration."
|
||||
}
|
||||
tentacles.application, _ = commands.(tentacleApplication)
|
||||
tentacles.automation, _ = commands.(tentacleAutomation)
|
||||
tentacles.ocr = ocrSession
|
||||
tentacles.feedback = speechMessages.beep
|
||||
tentacles.output = &tentacleOutput{speech: speechMessages, braille: brailleOutput, gate: focusGate, live: live}
|
||||
focusGate.tentacleOutput = tentacles.output
|
||||
focusGate.remotePolicy = tentacle.NewRemotePolicy()
|
||||
|
||||
@@ -142,6 +142,17 @@ func (session *ocrSession) Handle(event input.CommandEvent) bool {
|
||||
session.presentSpellingLocked(position, unit, flatReviewSpeech(event.Command))
|
||||
return true
|
||||
}
|
||||
// Application commands may need the current OCR target. Their automation
|
||||
// worker validates and retires it before releasing review input.
|
||||
if strings.HasPrefix(string(event.Command), "tentacle/") && session.tentacleBindings != nil && session.applicationWindow != nil {
|
||||
for _, binding := range session.tentacleBindings() {
|
||||
if binding.Command == event.Command && binding.Application != "" && binding.Layout == input.KeyboardLayout(session.settings().KeyboardLayout) {
|
||||
if window, err := session.applicationWindow(binding.Application); err == nil && window == session.job.foreground.Client.Window {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ordinary reader commands restore their existing source/routing first.
|
||||
session.retireLocked()
|
||||
return false
|
||||
@@ -176,6 +187,12 @@ func (session *ocrSession) Input(event input.Event) {
|
||||
symbolName := event.Name
|
||||
// XRecord uses Xlib's keypad names; shortcut labels use the page names.
|
||||
switch symbolName {
|
||||
case "slash":
|
||||
symbolName = "/"
|
||||
case "backslash":
|
||||
symbolName = "\\"
|
||||
case "grave":
|
||||
symbolName = "`"
|
||||
case "KP_Next":
|
||||
symbolName = "KP_Page_Down"
|
||||
case "KP_Prior":
|
||||
@@ -215,6 +232,33 @@ func (session *ocrSession) Input(event input.Event) {
|
||||
session.retireLocked()
|
||||
return
|
||||
}
|
||||
if session.tentacleBindings != nil {
|
||||
var matched []input.BindingOverride
|
||||
classes := map[string]bool{}
|
||||
for _, binding := range session.tentacleBindings() {
|
||||
if binding.Application == "" {
|
||||
continue
|
||||
}
|
||||
if binding.Application != "" {
|
||||
match, known := classes[binding.Application]
|
||||
if !known && session.applicationWindow != nil {
|
||||
window, err := session.applicationWindow(binding.Application)
|
||||
match = err == nil && window == session.job.foreground.Client.Window
|
||||
classes[binding.Application] = match
|
||||
}
|
||||
if !match {
|
||||
continue
|
||||
}
|
||||
}
|
||||
matched = append(matched, binding)
|
||||
}
|
||||
merged := input.MergeTentacleBindings(settings.KeyBindings, matched)
|
||||
bindings, err = input.ResolveCommandBindings(input.KeyboardLayout(settings.KeyboardLayout), false, merged)
|
||||
if err != nil {
|
||||
session.retireLocked()
|
||||
return
|
||||
}
|
||||
}
|
||||
if session.cursor == nil {
|
||||
bindings = input.OCRPendingBindings(bindings)
|
||||
} else {
|
||||
|
||||
@@ -70,6 +70,8 @@ type ocrJob struct {
|
||||
// Retirement cancels synchronously; the worker joins children and releases native
|
||||
// input before admitting the next job. No native work runs on an input/event loop.
|
||||
type ocrSession struct {
|
||||
tentacleBindings func() []input.BindingOverride
|
||||
applicationWindow func(string) (uint64, error)
|
||||
window atspi.ObjectID
|
||||
mu sync.Mutex
|
||||
logger *slog.Logger
|
||||
@@ -120,6 +122,14 @@ func newOcrSession(logger *slog.Logger, commands commandListener, adapter Adapte
|
||||
capture: ocr.NewCapturer(executable), engine: ocr.NewEngine(), copier: xclipOCRCopier{}, copyRequests: make(chan ocrCopyRequest, 1),
|
||||
activateRequests: make(chan ocrActivateRequest, 1), confirmer: ocrDialogConfirmer{executable: executable},
|
||||
wake: make(chan struct{}, 1), failures: make(chan error, 1), held: make(map[string]bool), selectionAnchor: -1}
|
||||
if bindings, ok := commands.(interface {
|
||||
TentacleBindings() []input.BindingOverride
|
||||
}); ok {
|
||||
session.tentacleBindings = bindings.TentacleBindings
|
||||
}
|
||||
if application, ok := commands.(interface{ ApplicationWindow(string) (uint64, error) }); ok {
|
||||
session.applicationWindow = application.ApplicationWindow
|
||||
}
|
||||
session.keys, _ = commands.(ocrKeyOwner)
|
||||
session.clicker, _ = commands.(ocrClicker)
|
||||
session.geometry, _ = adapter.(ocrGeometrySource)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package app
|
||||
|
||||
// Application metadata is independent of the mouse/OCR automation permission.
|
||||
type tentacleApplication interface {
|
||||
ApplicationWindow(string) (uint64, error)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/ocr"
|
||||
)
|
||||
|
||||
type windowOnlyApplication struct{}
|
||||
|
||||
func (windowOnlyApplication) ApplicationWindow(string) (uint64, error) { return 42, nil }
|
||||
func TestApplicationOnlyCommandDoesNotRequireAutomation(t *testing.T) {
|
||||
runtime, bindings, marker := readerTentacleFixture(t, "called", false)
|
||||
if err := runtime.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chord, _ := input.ParseCommandChord("F9")
|
||||
waitTentacle(t, func() bool { return runtime.Describe(chord, input.DesktopKeyboardLayout, false) != "" })
|
||||
command := bindings.TentacleBindings()[0].Command
|
||||
runtime.mutex.Lock()
|
||||
registered := runtime.commands[command]
|
||||
registered.application = "example"
|
||||
runtime.commands[command] = registered
|
||||
runtime.application = windowOnlyApplication{}
|
||||
runtime.mutex.Unlock()
|
||||
if !runtime.Invoke(context.Background(), command) {
|
||||
t.Fatal("application command not handled")
|
||||
}
|
||||
waitTentacle(t, func() bool { _, err := os.Stat(marker); return err == nil })
|
||||
}
|
||||
|
||||
func TestOCRRetainsApplicationShortcutObservations(t *testing.T) {
|
||||
for _, matching := range []bool{false, true} {
|
||||
session, keys, _, engine, _ := ocrTestSession(t)
|
||||
session.tentacleBindings = func() []input.BindingOverride {
|
||||
return []input.BindingOverride{{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "ck3", Command: "tentacle/test/click", Keys: []string{"/"}}}
|
||||
}
|
||||
session.applicationWindow = func(string) (uint64, error) {
|
||||
if matching {
|
||||
return 42, nil
|
||||
}
|
||||
return 99, nil
|
||||
}
|
||||
session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100})
|
||||
ocrTestReceive(t, keys.calls)
|
||||
session.Input(input.Event{Name: "slash", Pressed: true, Timestamp: 101})
|
||||
session.mu.Lock()
|
||||
active := session.cancel != nil
|
||||
session.mu.Unlock()
|
||||
if active != matching {
|
||||
t.Fatalf("matching=%v active=%v", matching, active)
|
||||
}
|
||||
engine.results <- ocr.Result{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOCRUnscopedTentacleKeepsLegacyRetirement(t *testing.T) {
|
||||
session, keys, _, engine, _ := ocrTestSession(t)
|
||||
session.tentacleBindings = func() []input.BindingOverride {
|
||||
return []input.BindingOverride{{Layout: input.DesktopKeyboardLayout, Scope: "global", Command: "tentacle/test/unscoped", Keys: []string{"/"}}}
|
||||
}
|
||||
session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100})
|
||||
ocrTestReceive(t, keys.calls)
|
||||
session.Input(input.Event{Name: "slash", Pressed: true, Timestamp: 101})
|
||||
session.mu.Lock()
|
||||
active := session.cancel != nil
|
||||
session.mu.Unlock()
|
||||
engine.results <- ocr.Result{}
|
||||
if active {
|
||||
t.Fatal("unscoped Tentacle changed legacy OCR retirement")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOCRDispatchRetiresCommandsOutsideCurrentApplication(t *testing.T) {
|
||||
for _, mode := range []string{"unscoped", "other-window", "other-layout", "reader"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
session, keys, _, engine, _ := ocrTestSession(t)
|
||||
binding := input.BindingOverride{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "ck3", Command: "tentacle/test/click", Keys: []string{"/"}}
|
||||
if mode == "unscoped" {
|
||||
binding.Application = ""
|
||||
}
|
||||
if mode == "other-layout" {
|
||||
binding.Layout = input.LaptopKeyboardLayout
|
||||
}
|
||||
session.tentacleBindings = func() []input.BindingOverride { return []input.BindingOverride{binding} }
|
||||
session.applicationWindow = func(string) (uint64, error) {
|
||||
if mode == "other-window" {
|
||||
return 99, nil
|
||||
}
|
||||
return 42, nil
|
||||
}
|
||||
command := binding.Command
|
||||
if mode == "reader" {
|
||||
command = input.PresentWindowTitle
|
||||
}
|
||||
session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100})
|
||||
ocrTestReceive(t, keys.calls)
|
||||
if session.Handle(input.CommandEvent{Command: command, Timestamp: 101}) {
|
||||
t.Fatal("OCR swallowed an ordinary command")
|
||||
}
|
||||
session.mu.Lock()
|
||||
active := session.cancel != nil
|
||||
session.mu.Unlock()
|
||||
engine.results <- ocr.Result{}
|
||||
if active {
|
||||
t.Fatal("command outside the current application retained OCR")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"time"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/ocr"
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
)
|
||||
|
||||
type tentacleAutomation interface {
|
||||
tentacleApplication
|
||||
ApplicationBounds(string, uint64) (image.Rectangle, error)
|
||||
AutomationTimestamp(context.Context, uint64, string) (uint32, error)
|
||||
SetOCRReview(context.Context, bool) error
|
||||
AutomationAction(context.Context, uint64, string, image.Rectangle, tentaclewire.AutomationAction) error
|
||||
MoveAutomationPointer(context.Context, uint64, string, image.Rectangle, image.Point) error
|
||||
}
|
||||
|
||||
func (runtime *tentacleRuntime) automationCurrent(ctx context.Context, command tentacleCommand) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if runtime.automation == nil || command.window == 0 || !tentaclewire.ValidApplication(command.application) || runtime.output == nil || runtime.output.gate == nil || runtime.output.gate.Locked() || runtime.output.gate.Suspended() {
|
||||
return errors.New("application automation unavailable")
|
||||
}
|
||||
window, err := runtime.automation.ApplicationWindow(command.application)
|
||||
if err != nil || window != command.window {
|
||||
return errors.New("application focus changed")
|
||||
}
|
||||
if !command.bounds.Empty() {
|
||||
bounds, err := runtime.automation.ApplicationBounds(command.application, command.window)
|
||||
if err != nil || bounds != command.bounds {
|
||||
return errors.New("application geometry changed")
|
||||
}
|
||||
}
|
||||
if command.foreground.Epoch != 0 && runtime.ocr != nil && runtime.ocr.foreground != nil && runtime.ocr.foreground.Foreground() != command.foreground {
|
||||
return errors.New("application foreground changed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Runs on the joined interaction worker, never on the input consumer. A command
|
||||
// keeps its original foreground identity across child RPC and every delayed step.
|
||||
func (runtime *tentacleRuntime) runAutomation(ctx context.Context, command tentacleCommand, request tentaclewire.Automation) error {
|
||||
if !command.automationAllowed || !tentaclewire.ValidAutomation(request) {
|
||||
return errors.New("invalid automation")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := runtime.automationCurrent(ctx, command); err != nil {
|
||||
return err
|
||||
}
|
||||
if command.bounds.Empty() {
|
||||
bounds, err := runtime.automation.ApplicationBounds(command.application, command.window)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
command.bounds = bounds
|
||||
}
|
||||
var target ocrAutomationTarget
|
||||
for i, a := range request.Actions {
|
||||
if a.Kind == "ocr-route" {
|
||||
if i != 0 || runtime.ocr == nil {
|
||||
return errors.New("OCR target unavailable")
|
||||
}
|
||||
var err error
|
||||
target, err = runtime.ocr.prepareAutomationTarget(ctx, command.window)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if runtime.ocr != nil {
|
||||
runtime.ocr.Retire()
|
||||
}
|
||||
// Acknowledged by the native owner only after the complete shortcut releases.
|
||||
if err := runtime.automation.SetOCRReview(ctx, false); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range request.Actions {
|
||||
if err := runtime.automationCurrent(ctx, command); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
switch a.Kind {
|
||||
case "tone":
|
||||
// Feedback failure must not prevent the requested application action.
|
||||
if runtime.feedback != nil {
|
||||
_ = runtime.feedback(ctx)
|
||||
} else {
|
||||
_ = runtime.automation.AutomationAction(ctx, command.window, command.application, command.bounds, a)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
case "ocr-route":
|
||||
if err = target.validate(ctx); err == nil {
|
||||
err = runtime.automation.MoveAutomationPointer(ctx, command.window, command.application, command.bounds, target.point)
|
||||
}
|
||||
case "ocr-dismiss": // Already retired synchronously before input release.
|
||||
case "ocr-scan":
|
||||
if runtime.ocr == nil {
|
||||
return errors.New("OCR unavailable")
|
||||
}
|
||||
stamp, stampErr := runtime.automation.AutomationTimestamp(ctx, command.window, command.application)
|
||||
if stampErr != nil {
|
||||
return stampErr
|
||||
}
|
||||
err = runtime.ocr.ScanAutomation(command.window, stamp)
|
||||
case "delay":
|
||||
timer := time.NewTimer(time.Duration(a.Milliseconds) * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
default:
|
||||
err = runtime.automation.AutomationAction(ctx, command.window, command.application, command.bounds, a)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AutomationTarget copies only the cursor position and validates fresh pixels.
|
||||
// It never exports OCR text or an unrestricted reader command interface.
|
||||
type ocrAutomationTarget struct {
|
||||
point image.Point
|
||||
session *ocrSession
|
||||
request ocrActivateRequest
|
||||
}
|
||||
|
||||
func (target ocrAutomationTarget) validate(ctx context.Context) error {
|
||||
return target.session.validateActivation(ctx, target.request)
|
||||
}
|
||||
func (session *ocrSession) AutomationTarget(ctx context.Context, window uint64) (image.Point, error) {
|
||||
target, err := session.prepareAutomationTarget(ctx, window)
|
||||
return target.point, err
|
||||
}
|
||||
func (session *ocrSession) prepareAutomationTarget(ctx context.Context, window uint64) (ocrAutomationTarget, error) {
|
||||
session.mu.Lock()
|
||||
if session.cursor == nil || session.refreshing || session.refreshFailed || session.activating || !session.currentLocked(session.job) || session.job.kind == ocr.ClipboardSource || session.job.foreground.Client.Window != window {
|
||||
session.mu.Unlock()
|
||||
return ocrAutomationTarget{}, errors.New("OCR target unavailable; refresh the result")
|
||||
}
|
||||
word, ok := session.cursor.CurrentWord()
|
||||
request := ocrActivateRequest{job: session.job, word: word, capture: session.pixels}
|
||||
session.mu.Unlock()
|
||||
if !ok {
|
||||
return ocrAutomationTarget{}, errors.New("move to a recognized word")
|
||||
}
|
||||
if err := session.validateActivation(ctx, request); err != nil {
|
||||
return ocrAutomationTarget{}, err
|
||||
}
|
||||
session.mu.Lock()
|
||||
defer session.mu.Unlock()
|
||||
if !session.currentLocked(request.job) {
|
||||
return ocrAutomationTarget{}, ocr.ErrSourceChanged
|
||||
}
|
||||
bounds, ok := request.capture.Transform.ScreenRectangle(word.Bounds)
|
||||
if !ok {
|
||||
return ocrAutomationTarget{}, errors.New("OCR word has no screen position")
|
||||
}
|
||||
return ocrAutomationTarget{point: image.Pt(bounds.Min.X+(bounds.Dx()-1)/2, bounds.Min.Y+(bounds.Dy()-1)/2), session: session, request: request}, nil
|
||||
}
|
||||
|
||||
func (session *ocrSession) ScanAutomation(window uint64, timestamp uint32) error {
|
||||
session.mu.Lock()
|
||||
defer session.mu.Unlock()
|
||||
if session.foreground == nil || session.foreground.Foreground().Client.Window != window || session.ctx == nil || session.ctx.Err() != nil || session.gate.Locked() || session.gate.Suspended() {
|
||||
return errors.New("OCR foreground unavailable")
|
||||
}
|
||||
session.requestLocked(ocr.WindowSource, timestamp)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/ocr"
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
)
|
||||
|
||||
type automationRecorder struct {
|
||||
window uint64
|
||||
calls []string
|
||||
changeAfter string
|
||||
onRelease func()
|
||||
onRoute func()
|
||||
bounds image.Rectangle
|
||||
resizeAfter string
|
||||
}
|
||||
|
||||
func (r *automationRecorder) AutomationTimestamp(context.Context, uint64, string) (uint32, error) {
|
||||
return 200, nil
|
||||
}
|
||||
func (r *automationRecorder) ApplicationWindow(_ string) (uint64, error) {
|
||||
if r.window == 0 {
|
||||
return 0, errors.New("lost focus")
|
||||
}
|
||||
return r.window, nil
|
||||
}
|
||||
func (r *automationRecorder) SetOCRReview(_ context.Context, _ bool) error {
|
||||
r.calls = append(r.calls, "release")
|
||||
if r.onRelease != nil {
|
||||
r.onRelease()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *automationRecorder) AutomationAction(_ context.Context, _ uint64, _ string, _ image.Rectangle, a tentaclewire.AutomationAction) error {
|
||||
r.calls = append(r.calls, a.Kind)
|
||||
if a.Kind == r.resizeAfter {
|
||||
r.bounds = image.Rect(0, 0, 960, 540)
|
||||
}
|
||||
if a.Kind == r.changeAfter {
|
||||
r.window = 0
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *automationRecorder) MoveAutomationPointer(_ context.Context, _ uint64, _ string, _ image.Rectangle, _ image.Point) error {
|
||||
r.calls = append(r.calls, "route")
|
||||
if r.onRoute != nil {
|
||||
r.onRoute()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestTentacleAutomationFocusAndOrder(t *testing.T) {
|
||||
sequence := tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{{Kind: "move", X: 5000, Y: 5000}, {Kind: "click", Button: 3, Modifier: "shift"}, {Kind: "move", X: 10000}}}
|
||||
for _, lost := range []bool{false, true} {
|
||||
r := &automationRecorder{window: 42}
|
||||
if lost {
|
||||
r.changeAfter = "click"
|
||||
}
|
||||
runtime := &tentacleRuntime{automation: r, output: &tentacleOutput{gate: newFocusGate(nil)}}
|
||||
err := runtime.runAutomation(context.Background(), tentacleCommand{automationAllowed: true, application: "ck3", window: 42}, sequence)
|
||||
want := []string{"release", "move", "click", "move"}
|
||||
if lost {
|
||||
want = want[:3]
|
||||
}
|
||||
if !reflect.DeepEqual(r.calls, want) || ((err != nil) != lost) {
|
||||
t.Fatalf("lost=%v calls=%v err=%v", lost, r.calls, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestTentacleAutomationRequiresApplicationAndCancellation(t *testing.T) {
|
||||
for _, cancelled := range []bool{false, true} {
|
||||
r := &automationRecorder{window: 42}
|
||||
runtime := &tentacleRuntime{automation: r, output: &tentacleOutput{gate: newFocusGate(nil)}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
command := tentacleCommand{automationAllowed: true, window: 42}
|
||||
if cancelled {
|
||||
command.application = "ck3"
|
||||
cancel()
|
||||
}
|
||||
if err := runtime.runAutomation(ctx, command, tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{{Kind: "click", Button: 1}}}); err == nil {
|
||||
t.Fatal("accepted unavailable automation")
|
||||
}
|
||||
if len(r.calls) != 0 {
|
||||
t.Fatalf("side effects: %v", r.calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOCRAutomationTargetRejectsMissingResult(t *testing.T) {
|
||||
session, _, _, _, _ := ocrTestSession(t)
|
||||
if _, err := session.AutomationTarget(context.Background(), 42); err == nil {
|
||||
t.Fatal("routed without OCR result")
|
||||
}
|
||||
if err := session.ScanAutomation(99, 0); err == nil {
|
||||
t.Fatal("scanned wrong window")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOCRAutomationTargetChecksPixelsAndMapping(t *testing.T) {
|
||||
for _, mode := range []string{"current", "stale", "release", "hover", "dispatch"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
session, keys, capture, engine, output := ocrTestSession(t)
|
||||
paint := byte(20)
|
||||
capture.produce = func(ctx context.Context, request ocr.CaptureRequest) (ocr.Capture, error) {
|
||||
pixels := image.NewRGBA(image.Rect(0, 0, 100, 50))
|
||||
pixels.Pix[0] = paint
|
||||
bounds := image.Rect(10, 20, 110, 70)
|
||||
return ocr.Capture{CaptureHeader: ocr.CaptureHeader{Request: request, RootBounds: image.Rect(0, 0, 200, 200), SourceBounds: bounds, ScreenBounds: bounds, SourceWindow: request.Foreground}, Pixels: pixels, Transform: ocr.Transform{ImageContent: pixels.Bounds(), ScreenBounds: bounds, HasScreenMapping: true}}, ctx.Err()
|
||||
}
|
||||
session.Handle(input.CommandEvent{Command: input.OCRWindow, Timestamp: 100})
|
||||
ocrTestReceive(t, keys.calls)
|
||||
ocrTestReceive(t, capture.calls)
|
||||
ocrTestReceive(t, engine.calls)
|
||||
engine.results <- ocr.Result{Text: "go", Width: 100, Height: 50, Words: []ocr.Word{{Text: "go", Bounds: image.Rect(10, 10, 30, 20), Span: ocr.Span{Start: 0, End: 2}}}}
|
||||
ocrTestReceive(t, keys.calls)
|
||||
ocrTestReceive(t, output.speech)
|
||||
ocrTestReceive(t, output.frames)
|
||||
if mode == "stale" {
|
||||
paint = 30
|
||||
}
|
||||
point, err := session.AutomationTarget(context.Background(), 42)
|
||||
|
||||
if mode == "release" || mode == "hover" || mode == "dispatch" {
|
||||
backend := &automationRecorder{window: 42}
|
||||
if mode == "dispatch" {
|
||||
session.tentacleBindings = func() []input.BindingOverride {
|
||||
return []input.BindingOverride{{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "ck3", Command: "tentacle/ck3/quick-left", Keys: []string{"/"}}}
|
||||
}
|
||||
session.applicationWindow = backend.ApplicationWindow
|
||||
session.Input(input.Event{Name: "slash", Pressed: true, Timestamp: 101})
|
||||
if session.Handle(input.CommandEvent{Command: "tentacle/ck3/quick-left", Timestamp: 101}) {
|
||||
t.Fatal("OCR swallowed the application command")
|
||||
}
|
||||
}
|
||||
if mode == "release" {
|
||||
backend.onRelease = func() { paint = 30 }
|
||||
} else if mode == "hover" {
|
||||
backend.onRoute = func() { paint = 30 }
|
||||
}
|
||||
runtime := &tentacleRuntime{automation: backend, ocr: session, output: &tentacleOutput{gate: newFocusGate(nil)}}
|
||||
err := runtime.runAutomation(context.Background(), tentacleCommand{automationAllowed: true, application: "ck3", window: 42}, tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{{Kind: "ocr-route"}, {Kind: "click", Button: 1}}})
|
||||
want := []string{"release"}
|
||||
if mode == "hover" || mode == "dispatch" {
|
||||
want = append(want, "route", "click")
|
||||
}
|
||||
if (err != nil) != (mode == "release") || !reflect.DeepEqual(backend.calls, want) {
|
||||
t.Fatalf("%s: calls=%v err=%v", mode, backend.calls, err)
|
||||
}
|
||||
}
|
||||
if mode == "stale" {
|
||||
if err == nil {
|
||||
t.Fatal("stale pixels accepted")
|
||||
}
|
||||
} else if err != nil || point != image.Pt(29, 34) {
|
||||
t.Fatalf("point %v: %v", point, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOCRAutomationScanIgnoresDelayedEarlierInput(t *testing.T) {
|
||||
session, keys, _, engine, _ := ocrTestSession(t)
|
||||
if err := session.ScanAutomation(42, 200); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ocrTestReceive(t, keys.calls)
|
||||
session.Input(input.Event{Name: "q", Pressed: true, Timestamp: 199})
|
||||
session.mu.Lock()
|
||||
active := session.cancel != nil
|
||||
cutoff := session.cutoff
|
||||
session.mu.Unlock()
|
||||
if !active || cutoff != 200 {
|
||||
t.Fatalf("delayed input retired scan: active=%v cutoff=%d", active, cutoff)
|
||||
}
|
||||
engine.results <- ocr.Result{}
|
||||
}
|
||||
|
||||
func TestAutomationSoundFailureDoesNotBlockMouse(t *testing.T) {
|
||||
backend := &automationRecorder{window: 42}
|
||||
runtime := &tentacleRuntime{automation: backend, output: &tentacleOutput{gate: newFocusGate(nil)}, feedback: func(context.Context) error { return errors.New("no sound sink") }}
|
||||
err := runtime.runAutomation(context.Background(), tentacleCommand{automationAllowed: true, application: "ck3", window: 42}, tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{{Kind: "tone"}, {Kind: "move", X: 10000}}})
|
||||
if err != nil || !reflect.DeepEqual(backend.calls, []string{"release", "move"}) {
|
||||
t.Fatalf("optional sound blocked action: calls=%v err=%v", backend.calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationShortcutHelpRespectsFocus(t *testing.T) {
|
||||
runtime, bindings, _ := readerTentacleFixture(t, "called", false)
|
||||
if err := runtime.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f9, _ := input.ParseCommandChord("F9")
|
||||
waitTentacle(t, func() bool { return runtime.Describe(f9, input.DesktopKeyboardLayout, false) != "" })
|
||||
bindings.mutex.Lock()
|
||||
for i := range bindings.bindings {
|
||||
bindings.bindings[i].Application = "ck3"
|
||||
}
|
||||
bindings.mutex.Unlock()
|
||||
runtime.mutex.Lock()
|
||||
runtime.automation = &automationRecorder{}
|
||||
runtime.application = runtime.automation
|
||||
runtime.mutex.Unlock()
|
||||
if got := runtime.Describe(f9, input.DesktopKeyboardLayout, false); got != "" {
|
||||
t.Fatal("game shortcut described outside game:", got)
|
||||
}
|
||||
rows := runtime.ShortcutRows(input.DesktopKeyboardLayout)
|
||||
if len(rows) != 1 || rows[0].Group != "Tentacles for ck3" {
|
||||
t.Fatalf("scope missing from shortcut list: %+v", rows)
|
||||
}
|
||||
runtime.mutex.Lock()
|
||||
runtime.automation = &automationRecorder{window: 42}
|
||||
runtime.application = runtime.automation
|
||||
runtime.mutex.Unlock()
|
||||
if got := runtime.Describe(f9, input.DesktopKeyboardLayout, false); got == "" {
|
||||
t.Fatal("missing game description")
|
||||
}
|
||||
}
|
||||
|
||||
func (r *automationRecorder) ApplicationBounds(string, uint64) (image.Rectangle, error) {
|
||||
if r.bounds.Empty() {
|
||||
return image.Rect(0, 0, 1920, 1080), nil
|
||||
}
|
||||
return r.bounds, nil
|
||||
}
|
||||
func TestAutomationStopsAfterWindowResize(t *testing.T) {
|
||||
backend := &automationRecorder{window: 42, resizeAfter: "move"}
|
||||
runtime := &tentacleRuntime{automation: backend, output: &tentacleOutput{gate: newFocusGate(nil)}}
|
||||
err := runtime.runAutomation(context.Background(), tentacleCommand{automationAllowed: true, application: "ck3", window: 42}, tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{{Kind: "move", X: 5000, Y: 5000}, {Kind: "click", Button: 1}}})
|
||||
if err == nil || !reflect.DeepEqual(backend.calls, []string{"release", "move"}) {
|
||||
t.Fatalf("resized window clicked: calls=%v err=%v", backend.calls, err)
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,19 @@ func (runtime *tentacleRuntime) interact(ctx context.Context, command tentacleCo
|
||||
if runtime.output.gate.Locked() || runtime.output.gate.Suspended() {
|
||||
return
|
||||
}
|
||||
if value.Automation != nil {
|
||||
if err := runtime.runAutomation(ctx, command, *value.Automation); err != nil {
|
||||
runtime.logger.Debug("application automation failed", "error", err)
|
||||
if ctx.Err() == nil && runtime.automation != nil {
|
||||
if window, focusErr := runtime.automation.ApplicationWindow(command.application); focusErr == nil && window == command.window {
|
||||
runtime.report("Application command unavailable. Check application focus and refresh OCR before clicking.")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
runtime.output.Present(runtime.output.Capture(command.session.OutputContext()), value.Presentation, "tentacle/"+command.id)
|
||||
return
|
||||
}
|
||||
if value.RemoteBackground != nil {
|
||||
lease := *value.RemoteBackground
|
||||
lifetime, leaseErr := command.session.RemoteLeaseContext(lease)
|
||||
|
||||
@@ -3,12 +3,14 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/atspi"
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
"git.stormux.org/storm/cthulhu/internal/remoteinput"
|
||||
"git.stormux.org/storm/cthulhu/internal/shortcutui"
|
||||
@@ -22,6 +24,11 @@ type tentacleInput interface {
|
||||
}
|
||||
|
||||
type tentacleCommand struct {
|
||||
automationAllowed bool
|
||||
application string
|
||||
window uint64
|
||||
bounds image.Rectangle
|
||||
foreground atspi.ForegroundState
|
||||
session *tentacle.Session
|
||||
entryID string
|
||||
id, title, description string
|
||||
@@ -35,6 +42,10 @@ type tentacleCommand struct {
|
||||
// native publication; mutex protects dispatch snapshots and immediate disable.
|
||||
// Only explicitly granted presentation commands reach the core output owner.
|
||||
type tentacleRuntime struct {
|
||||
application tentacleApplication
|
||||
feedback func(context.Context) error
|
||||
automation tentacleAutomation
|
||||
ocr *ocrSession
|
||||
remotePolicy *tentacle.RemotePolicy
|
||||
remoteInput *remoteinput.Supervisor // Retained for the reader lifetime.
|
||||
remoteInputHelper string // Private fixture seam; production uses the reader's directory.
|
||||
@@ -270,7 +281,7 @@ func (runtime *tentacleRuntime) bind(ctx context.Context, sessions []*tentacle.S
|
||||
if binding.Layout == "laptop" {
|
||||
layout = input.LaptopKeyboardLayout
|
||||
}
|
||||
bindings = append(bindings, input.BindingOverride{Layout: layout, Scope: binding.Scope,
|
||||
bindings = append(bindings, input.BindingOverride{Layout: layout, Scope: binding.Scope, Application: command.Application,
|
||||
Command: input.Command("tentacle/" + session.Identity() + "/" + command.ID), Keys: []string{binding.Key}})
|
||||
}
|
||||
}
|
||||
@@ -292,8 +303,8 @@ func (runtime *tentacleRuntime) publishCommands(sessions []*tentacle.Session) {
|
||||
for _, command := range session.Commands() {
|
||||
runtime.commands[input.Command("tentacle/"+session.Identity()+"/"+command.ID)] = tentacleCommand{
|
||||
session: session, entryID: session.TentacleID(), id: command.ID, title: command.Title,
|
||||
description: command.Description, presentation: command.Presentation,
|
||||
interactive: command.Interaction, settings: command.Settings, reader: command.Reader,
|
||||
description: command.Description, presentation: command.Presentation, application: command.Application,
|
||||
interactive: command.Interaction, settings: command.Settings, reader: command.Reader, automationAllowed: command.Automation,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,6 +330,29 @@ func (runtime *tentacleRuntime) Invoke(ctx context.Context, command input.Comman
|
||||
|
||||
// Caller holds runtime.mutex so shutdown cannot race worker admission.
|
||||
func (runtime *tentacleRuntime) invokeLocked(ctx context.Context, command input.Command, registered tentacleCommand) error {
|
||||
if registered.application != "" {
|
||||
if runtime.application == nil {
|
||||
return errors.New("application shortcuts unavailable")
|
||||
}
|
||||
window, err := runtime.application.ApplicationWindow(registered.application)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
registered.window = window
|
||||
if registered.automationAllowed {
|
||||
if runtime.automation == nil {
|
||||
return errors.New("application automation unavailable")
|
||||
}
|
||||
bounds, err := runtime.automation.ApplicationBounds(registered.application, window)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
registered.bounds = bounds
|
||||
if runtime.ocr != nil && runtime.ocr.foreground != nil {
|
||||
registered.foreground = runtime.ocr.foreground.Foreground()
|
||||
}
|
||||
}
|
||||
}
|
||||
select {
|
||||
case runtime.resultSlots <- struct{}{}:
|
||||
default:
|
||||
@@ -377,6 +411,17 @@ func (runtime *tentacleRuntime) Describe(chord input.CommandChord, layout input.
|
||||
if binding.Layout != layout || binding.Scope == "browse" && !browse {
|
||||
continue
|
||||
}
|
||||
if binding.Application != "" {
|
||||
if availability, ok := runtime.input.(interface{ ApplicationBindingsAvailable() bool }); ok && !availability.ApplicationBindingsAvailable() {
|
||||
continue
|
||||
}
|
||||
if runtime.application == nil {
|
||||
continue
|
||||
}
|
||||
if window, err := runtime.application.ApplicationWindow(binding.Application); err != nil || window == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
bound, _ := input.ParseCommandChord(binding.Keys[0])
|
||||
registered, ok := runtime.commands[binding.Command]
|
||||
if bound != chord || !ok {
|
||||
@@ -418,6 +463,12 @@ func (runtime *tentacleRuntime) ShortcutRows(layout input.KeyboardLayout) []shor
|
||||
if binding.Scope == "browse" {
|
||||
group = "Tentacles in browse mode"
|
||||
}
|
||||
if binding.Application != "" {
|
||||
group = "Tentacles for " + binding.Application
|
||||
if availability, ok := runtime.input.(interface{ ApplicationBindingsAvailable() bool }); ok && !availability.ApplicationBindingsAvailable() {
|
||||
label += " (unavailable)"
|
||||
}
|
||||
}
|
||||
rows = append(rows, shortcutui.Row{Group: group, Label: label, Keys: binding.Keys[0]})
|
||||
}
|
||||
return rows
|
||||
|
||||
@@ -18,6 +18,7 @@ type BindingOverride struct {
|
||||
Scope string `toml:"scope"`
|
||||
Command Command `toml:"command"`
|
||||
Keys []string `toml:"keys"`
|
||||
Application string `toml:"-"` // Runtime Tentacle selector; never persisted.
|
||||
}
|
||||
|
||||
type BindingRow struct {
|
||||
@@ -102,6 +103,7 @@ func CommandLabel(command Command) string {
|
||||
func ResolveCommandBindings(layout KeyboardLayout, browse bool, overrides []BindingOverride) (CommandBindings, error) {
|
||||
global := bindingDefaults(layout, "global")
|
||||
document := bindingDefaults(layout, "browse")
|
||||
applicationKeys := make(map[CommandChord]bool)
|
||||
for _, override := range overrides {
|
||||
if override.Layout != layout {
|
||||
continue
|
||||
@@ -146,9 +148,15 @@ func ResolveCommandBindings(layout KeyboardLayout, browse bool, overrides []Bind
|
||||
return nil, fmt.Errorf("%s conflicts with %s", key, CommandLabel(previous))
|
||||
}
|
||||
bindings[chord] = override.Command
|
||||
if override.Application != "" {
|
||||
applicationKeys[chord] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for chord, command := range document {
|
||||
if applicationKeys[chord] {
|
||||
continue
|
||||
}
|
||||
if previous := global[chord]; previous != "" {
|
||||
return nil, fmt.Errorf("%s conflicts with %s in browse mode", FormatCommandChord(chord), CommandLabel(previous))
|
||||
}
|
||||
|
||||
@@ -26,9 +26,9 @@ func TestBindingDefaultsRoundTrip(t *testing.T) {
|
||||
|
||||
func TestBindingOverridesScopesLayoutsAndDisable(t *testing.T) {
|
||||
overrides := []BindingOverride{
|
||||
{DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+Ctrl+F8", "Alt+F9"}},
|
||||
{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"F6"}},
|
||||
{DesktopKeyboardLayout, "global", Quit, []string{}},
|
||||
{DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+Ctrl+F8", "Alt+F9"}, ""},
|
||||
{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"F6"}, ""},
|
||||
{DesktopKeyboardLayout, "global", Quit, []string{}, ""},
|
||||
}
|
||||
if err := ValidateBindingOverrides(overrides); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -72,15 +72,15 @@ func TestBindingOverridesScopesLayoutsAndDisable(t *testing.T) {
|
||||
|
||||
func TestBindingValidation(t *testing.T) {
|
||||
for _, overrides := range [][]BindingOverride{
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+q"}}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"h"}}},
|
||||
{{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"Cthulhu+q"}}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"F8", "f8"}}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"Insert"}}},
|
||||
{{DesktopKeyboardLayout, "global", Command("unknown"), []string{"F8"}}},
|
||||
{{KeyboardLayout(0), "global", Preferences, []string{"F8"}}},
|
||||
{{DesktopKeyboardLayout, "unknown", Preferences, []string{"F8"}}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, nil}, {DesktopKeyboardLayout, "global", Preferences, nil}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+q"}, ""}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"h"}, ""}},
|
||||
{{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"Cthulhu+q"}, ""}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"F8", "f8"}, ""}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, []string{"Insert"}, ""}},
|
||||
{{DesktopKeyboardLayout, "global", Command("unknown"), []string{"F8"}, ""}},
|
||||
{{KeyboardLayout(0), "global", Preferences, []string{"F8"}, ""}},
|
||||
{{DesktopKeyboardLayout, "unknown", Preferences, []string{"F8"}, ""}},
|
||||
{{DesktopKeyboardLayout, "global", Preferences, nil, ""}, {DesktopKeyboardLayout, "global", Preferences, nil, ""}},
|
||||
} {
|
||||
if err := ValidateBindingOverrides(overrides); err == nil {
|
||||
t.Fatalf("accepted %+v", overrides)
|
||||
@@ -91,18 +91,18 @@ func TestBindingValidation(t *testing.T) {
|
||||
t.Fatalf("accepted %q", key)
|
||||
}
|
||||
}
|
||||
swaps := []BindingOverride{{DesktopKeyboardLayout, "global", Quit, []string{"Cthulhu+Space"}}, {DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+q"}}}
|
||||
swaps := []BindingOverride{{DesktopKeyboardLayout, "global", Quit, []string{"Cthulhu+Space"}, ""}, {DesktopKeyboardLayout, "global", Preferences, []string{"Cthulhu+q"}, ""}}
|
||||
if err := ValidateBindingOverrides(swaps); err != nil {
|
||||
t.Fatalf("swap: %v", err)
|
||||
}
|
||||
unbound := []BindingOverride{{DesktopKeyboardLayout, "global", PresentDate, []string{"F8"}}}
|
||||
unbound := []BindingOverride{{DesktopKeyboardLayout, "global", PresentDate, []string{"F8"}, ""}}
|
||||
if err := ValidateBindingOverrides(unbound); err != nil {
|
||||
t.Fatalf("unbound command: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomBindingRouterBalancedReleaseAndMultiPress(t *testing.T) {
|
||||
overrides := []BindingOverride{{DesktopKeyboardLayout, "global", PresentTime, []string{"Cthulhu+Ctrl+Alt+F8"}}}
|
||||
overrides := []BindingOverride{{DesktopKeyboardLayout, "global", PresentTime, []string{"Cthulhu+Ctrl+Alt+F8"}, ""}}
|
||||
bindings, err := ResolveCommandBindings(DesktopKeyboardLayout, true, overrides)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -3,6 +3,8 @@ package input
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Tentacle bindings are runtime registrations, never persisted core overrides.
|
||||
@@ -12,7 +14,7 @@ func ValidateTentacleBindings(bindings []BindingOverride) error {
|
||||
return fmt.Errorf("too many tentacle bindings")
|
||||
}
|
||||
for _, binding := range bindings {
|
||||
if !strings.HasPrefix(string(binding.Command), "tentacle/") || len(binding.Command) > 400 ||
|
||||
if binding.Application != "" && (!ValidApplication(binding.Application) || binding.Scope != "global") || !strings.HasPrefix(string(binding.Command), "tentacle/") || len(binding.Command) > 400 ||
|
||||
(binding.Layout != DesktopKeyboardLayout && binding.Layout != LaptopKeyboardLayout) ||
|
||||
(binding.Scope != "global" && binding.Scope != "browse") || len(binding.Keys) != 1 {
|
||||
return fmt.Errorf("invalid tentacle binding")
|
||||
@@ -30,17 +32,65 @@ func MergeTentacleBindings(core, suggestions []BindingOverride) []BindingOverrid
|
||||
result := CloneBindingOverrides(core)
|
||||
for _, layout := range []KeyboardLayout{DesktopKeyboardLayout, LaptopKeyboardLayout} {
|
||||
occupied, _ := ResolveCommandBindings(layout, true, core)
|
||||
applicationOccupied := ApplicationOccupiedBindings(layout, core)
|
||||
for _, suggestion := range suggestions {
|
||||
if suggestion.Layout != layout {
|
||||
continue
|
||||
}
|
||||
chord, _ := ParseCommandChord(suggestion.Keys[0])
|
||||
if occupied[chord] != "" {
|
||||
blocked := occupied[chord]
|
||||
if suggestion.Application != "" {
|
||||
blocked = applicationOccupied[chord]
|
||||
}
|
||||
if blocked != "" {
|
||||
continue
|
||||
}
|
||||
occupied[chord] = suggestion.Command
|
||||
applicationOccupied[chord] = suggestion.Command
|
||||
result = append(result, CloneBindingOverrides([]BindingOverride{suggestion})[0])
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ValidApplication accepts an exact WM_CLASS string, never a pattern or title.
|
||||
func ValidApplication(value string) bool {
|
||||
if len(value) == 0 || len(value) > 127 || !utf8.ValidString(value) || strings.TrimSpace(value) == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range value {
|
||||
if !unicode.IsPrint(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ApplicationBindings retains application shortcuts in temporary OCR review.
|
||||
// The native owner checks the selector before admitting a physical chord.
|
||||
func ApplicationBindings(bindings CommandBindings, layout KeyboardLayout, overrides []BindingOverride) CommandBindings {
|
||||
for _, binding := range overrides {
|
||||
if binding.Layout == layout && binding.Application != "" {
|
||||
for _, key := range binding.Keys {
|
||||
chord, _ := ParseCommandChord(key)
|
||||
bindings[chord] = binding.Command
|
||||
}
|
||||
}
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
// ApplicationOccupiedBindings reserves global commands and explicit user
|
||||
// assignments. Unmodified browser defaults apply outside the named application.
|
||||
func ApplicationOccupiedBindings(layout KeyboardLayout, core []BindingOverride) CommandBindings {
|
||||
occupied, _ := ResolveCommandBindings(layout, false, core)
|
||||
for _, binding := range core {
|
||||
if binding.Layout == layout && binding.Scope == "browse" {
|
||||
for _, key := range binding.Keys {
|
||||
chord, _ := ParseCommandChord(key)
|
||||
occupied[chord] = binding.Command
|
||||
}
|
||||
}
|
||||
}
|
||||
return occupied
|
||||
}
|
||||
@@ -19,15 +19,15 @@ func TestTentacleWormholeShortcutAvailableOnBothLayouts(t *testing.T) {
|
||||
|
||||
func TestTentacleBindingsCoreWinsAcrossScopesAndRemapping(t *testing.T) {
|
||||
suggestions := []BindingOverride{
|
||||
{DesktopKeyboardLayout, "global", "tentacle/a/one", []string{"F9"}},
|
||||
{DesktopKeyboardLayout, "browse", "tentacle/b/two", []string{"F9"}},
|
||||
{DesktopKeyboardLayout, "global", "tentacle/a/quit", []string{"Cthulhu+q"}},
|
||||
{LaptopKeyboardLayout, "global", "tentacle/b/two", []string{"F9"}},
|
||||
{DesktopKeyboardLayout, "global", "tentacle/a/one", []string{"F9"}, ""},
|
||||
{DesktopKeyboardLayout, "browse", "tentacle/b/two", []string{"F9"}, ""},
|
||||
{DesktopKeyboardLayout, "global", "tentacle/a/quit", []string{"Cthulhu+q"}, ""},
|
||||
{LaptopKeyboardLayout, "global", "tentacle/b/two", []string{"F9"}, ""},
|
||||
}
|
||||
if err := ValidateTentacleBindings(suggestions); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, core := range [][]BindingOverride{nil, {{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"F9"}}}} {
|
||||
for _, core := range [][]BindingOverride{nil, {{DesktopKeyboardLayout, "browse", DocumentNextHeading, []string{"F9"}, ""}}} {
|
||||
merged := MergeTentacleBindings(core, suggestions)
|
||||
bindings, err := ResolveCommandBindings(DesktopKeyboardLayout, true, merged)
|
||||
if err != nil {
|
||||
@@ -53,10 +53,60 @@ func TestTentacleBindingsCoreWinsAcrossScopesAndRemapping(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTentacleBindingsRejectCoreIdentity(t *testing.T) {
|
||||
if ValidateTentacleBindings([]BindingOverride{{DesktopKeyboardLayout, "global", Quit, []string{"F9"}}}) == nil {
|
||||
if ValidateTentacleBindings([]BindingOverride{{DesktopKeyboardLayout, "global", Quit, []string{"F9"}, ""}}) == nil {
|
||||
t.Fatal("accepted core identity")
|
||||
}
|
||||
if ValidateBindingOverrides([]BindingOverride{{DesktopKeyboardLayout, "global", "tentacle/a/one", []string{"F9"}}}) == nil {
|
||||
if ValidateBindingOverrides([]BindingOverride{{DesktopKeyboardLayout, "global", "tentacle/a/one", []string{"F9"}, ""}}) == nil {
|
||||
t.Fatal("persisted runtime registration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationBindingsOverrideOCRSelectionOnly(t *testing.T) {
|
||||
binding := BindingOverride{Layout: DesktopKeyboardLayout, Scope: "global", Application: "ck3", Command: "tentacle/test/scroll", Keys: []string{"Shift+Up"}}
|
||||
if err := ValidateTentacleBindings([]BindingOverride{binding}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := OCRCommandBindings(DefaultCommandBindings(DesktopKeyboardLayout))
|
||||
result := ApplicationBindings(base, DesktopKeyboardLayout, []BindingOverride{binding})
|
||||
chord, _ := ParseCommandChord("Shift+Up")
|
||||
if result[chord] != binding.Command {
|
||||
t.Fatalf("scroll binding: %s", result[chord])
|
||||
}
|
||||
binding.Application = "bad\x00class"
|
||||
if ValidateTentacleBindings([]BindingOverride{binding}) == nil {
|
||||
t.Fatal("accepted control character")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationShortcutsCanUseDefaultBrowserKeys(t *testing.T) {
|
||||
suggestion := BindingOverride{Layout: DesktopKeyboardLayout, Scope: "global", Application: "ck3", Command: "tentacle/test/center", Keys: []string{"Shift+1"}}
|
||||
merged := MergeTentacleBindings(nil, []BindingOverride{suggestion})
|
||||
if len(merged) != 1 {
|
||||
t.Fatal("browser heading default blocked game shortcut")
|
||||
}
|
||||
bindings, err := ResolveCommandBindings(DesktopKeyboardLayout, true, merged)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chord, _ := ParseCommandChord("Shift+1")
|
||||
if bindings[chord] != suggestion.Command {
|
||||
t.Fatal("game shortcut not resolved")
|
||||
}
|
||||
override := BindingOverride{Layout: DesktopKeyboardLayout, Scope: "browse", Command: DocumentPreviousHeadingAtLevel1, Keys: []string{"Shift+1"}}
|
||||
if got := MergeTentacleBindings([]BindingOverride{override}, []BindingOverride{suggestion}); len(got) != 1 {
|
||||
t.Fatal("application shadowed explicit reader override")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationSelectorsAreExactPrintableStrings(t *testing.T) {
|
||||
for _, value := range []string{"Example App", "пример", "literal*class"} {
|
||||
if !ValidApplication(value) {
|
||||
t.Errorf("valid class rejected: %q", value)
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"", " \t", "bad\x00class", string([]byte{0xff})} {
|
||||
if ValidApplication(value) {
|
||||
t.Errorf("invalid class accepted: %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "commands_native.h"
|
||||
#include <X11/Xutil.h>
|
||||
#include <string.h>
|
||||
// Match identifiers, never a title substring.
|
||||
int cthulhu_application_matches_unchecked(Display *display, Window window,
|
||||
const char *application) {
|
||||
if (!window || !application || !*application)
|
||||
return 0;
|
||||
XClassHint hint = {0};
|
||||
int ok = XGetClassHint(display, window, &hint) &&
|
||||
((hint.res_name && !strcmp(hint.res_name, application)) ||
|
||||
(hint.res_class && !strcmp(hint.res_class, application)));
|
||||
Window focus;
|
||||
int revert;
|
||||
XGetInputFocus(display, &focus, &revert);
|
||||
int focused = 0;
|
||||
for (int i = 0; i < 64 && focus && focus != PointerRoot; i++) {
|
||||
if (focus == window) {
|
||||
focused = 1;
|
||||
break;
|
||||
}
|
||||
Window root, parent, *children = NULL;
|
||||
unsigned count;
|
||||
if (!XQueryTree(display, focus, &root, &parent, &children, &count))
|
||||
break;
|
||||
if (children)
|
||||
XFree(children);
|
||||
if (parent == focus)
|
||||
break;
|
||||
focus = parent;
|
||||
}
|
||||
if (hint.res_name)
|
||||
XFree(hint.res_name);
|
||||
if (hint.res_class)
|
||||
XFree(hint.res_class);
|
||||
return ok && focused;
|
||||
}
|
||||
|
||||
int cthulhu_application_matches(Display *display, Window window, const char *application) {
|
||||
cthulhu_x11_begin_read(display);
|
||||
int ok = cthulhu_application_matches_unchecked(display, window, application);
|
||||
return !cthulhu_x11_end_read(display) && ok;
|
||||
}
|
||||
|
||||
unsigned long cthulhu_application_window(const char *application) {
|
||||
Display *display = XOpenDisplay(NULL);
|
||||
if (!display)
|
||||
return 0;
|
||||
Foreground fg = read_foreground(display);
|
||||
unsigned long result =
|
||||
fg.known && cthulhu_application_matches(display, fg.window, application) ? fg.window : 0;
|
||||
XCloseDisplay(display);
|
||||
return result;
|
||||
}
|
||||
|
||||
Foreground cthulhu_application_foreground(const char *application) {
|
||||
Foreground result = {0};
|
||||
Display *display = XOpenDisplay(NULL);
|
||||
if (!display)
|
||||
return result;
|
||||
Foreground fg = read_foreground(display);
|
||||
if (fg.known && cthulhu_application_matches(display, fg.window, application))
|
||||
result = fg;
|
||||
XCloseDisplay(display);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package xorg
|
||||
|
||||
/*
|
||||
#include "commands_native.h"
|
||||
#include <stdlib.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"unsafe"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
)
|
||||
|
||||
func (listener *CommandListener) ApplicationWindow(application string) (uint64, error) {
|
||||
if !input.ValidApplication(application) || listener.secure.Load() || !listener.ApplicationBindingsAvailable() {
|
||||
return 0, errors.New("application unavailable")
|
||||
}
|
||||
name := C.CString(application)
|
||||
defer C.free(unsafe.Pointer(name))
|
||||
window := uint64(C.cthulhu_application_window(name))
|
||||
if window == 0 {
|
||||
return 0, errors.New("application is not focused")
|
||||
}
|
||||
return window, nil
|
||||
}
|
||||
|
||||
// ApplicationBounds captures the client rectangle for the whole command.
|
||||
func (listener *CommandListener) ApplicationBounds(application string, window uint64) (image.Rectangle, error) {
|
||||
if !input.ValidApplication(application) || window == 0 || listener.secure.Load() {
|
||||
return image.Rectangle{}, errors.New("application unavailable")
|
||||
}
|
||||
name := C.CString(application)
|
||||
defer C.free(unsafe.Pointer(name))
|
||||
source := C.cthulhu_application_foreground(name)
|
||||
if uint64(source.window) != window || source.width <= 0 || source.height <= 0 {
|
||||
return image.Rectangle{}, errors.New("application source changed")
|
||||
}
|
||||
return image.Rect(int(source.x), int(source.y), int(source.x+source.width), int(source.y+source.height)), nil
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package xorg
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
)
|
||||
|
||||
func TestNativeApplicationShortcutScope(t *testing.T) {
|
||||
if os.Getenv("CTHULHU_NATIVE_X11") != "1" {
|
||||
t.Skip("private X11 required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
fixture := exec.CommandContext(ctx, "/usr/bin/python3", "-u", "../../../tests/application_fixture.py")
|
||||
in, _ := fixture.StdinPipe()
|
||||
out, _ := fixture.StdoutPipe()
|
||||
fixture.Stderr = os.Stderr
|
||||
if err := fixture.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { in.Close(); fixture.Wait() }()
|
||||
scanner := bufio.NewScanner(out)
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("fixture startup")
|
||||
}
|
||||
var info struct{ Window uint64 }
|
||||
json.Unmarshal(scanner.Bytes(), &info)
|
||||
listener := NewCommands([]string{"Insert"}, input.DesktopKeyboardLayout)
|
||||
bindings := []input.BindingOverride{
|
||||
{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/dismiss", Keys: []string{"Ctrl+D"}},
|
||||
{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/scroll", Keys: []string{"Shift+Up"}},
|
||||
}
|
||||
bindings = append(bindings, input.BindingOverride{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/example", Keys: []string{"Shift+1"}})
|
||||
for _, binding := range append([]input.BindingOverride(nil), bindings...) {
|
||||
binding.Layout = input.LaptopKeyboardLayout
|
||||
bindings = append(bindings, binding)
|
||||
}
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := listener.Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Stop(context.Background())
|
||||
if got := len(listener.TentacleBindings()); got != 6 {
|
||||
t.Fatalf("registered %d of 6 example bindings", got)
|
||||
}
|
||||
send := func(key string) {
|
||||
t.Helper()
|
||||
if err := exec.CommandContext(ctx, "xdotool", "key", key).Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
receive := func(want input.Command) {
|
||||
t.Helper()
|
||||
select {
|
||||
case event := <-listener.Commands():
|
||||
if event.Command != want {
|
||||
t.Fatalf("got %s want %s", event.Command, want)
|
||||
}
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal(err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing command", want)
|
||||
}
|
||||
}
|
||||
setClass := func(value string) {
|
||||
t.Helper()
|
||||
in.Write([]byte(value + "\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("class update")
|
||||
}
|
||||
}
|
||||
send("ctrl+d")
|
||||
receive("tentacle/test/dismiss")
|
||||
setClass("other")
|
||||
send("ctrl+d")
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case event := <-listener.Commands():
|
||||
t.Fatalf("command outside application: %+v", event)
|
||||
default:
|
||||
}
|
||||
in.Write([]byte("events\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("events")
|
||||
}
|
||||
var report struct {
|
||||
Keys []struct {
|
||||
Symbol uint32
|
||||
Pressed bool
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(scanner.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := false
|
||||
for _, key := range report.Keys {
|
||||
if key.Symbol == 'd' && key.Pressed {
|
||||
seen = true
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
t.Fatal("non-application Ctrl+D was swallowed")
|
||||
}
|
||||
setClass("example-app")
|
||||
if err := listener.SetOCRContext(ctx, info.Window, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
send("shift+Up")
|
||||
receive("tentacle/test/scroll")
|
||||
setClass("other")
|
||||
send("shift+Up")
|
||||
receive(input.OCRPreviousLine)
|
||||
if err := listener.SetOCRReview(ctx, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener.SetBrowseNavigation(true)
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
send("shift+1")
|
||||
receive(input.DocumentPreviousHeadingAtLevel1)
|
||||
listener.SetNativeButtonFocus(true)
|
||||
bindings = append(bindings, input.BindingOverride{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/enter", Keys: []string{"Return"}})
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
send("Return")
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case event := <-listener.Commands():
|
||||
t.Fatalf("native-button Return should pass through: %+v", event)
|
||||
default:
|
||||
}
|
||||
listener.SetBrowseNavigation(false)
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in.Write([]byte("grab-client\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("client shortcut owner did not start")
|
||||
}
|
||||
setClass("example-app")
|
||||
for listener.ApplicationBindingsAvailable() {
|
||||
select {
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal("optional application conflict stopped the reader", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("conflict not detected")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
send("Insert+q")
|
||||
receive(input.Quit)
|
||||
|
||||
in.Write([]byte("ungrab-client\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("client release failed")
|
||||
}
|
||||
setClass("other")
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setClass("example-app")
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for !listener.ApplicationBindingsAvailable() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("application shortcuts did not recover")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
listener.SetCommandGrabs(false)
|
||||
for listener.commandsApplied.Load() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("command suspension failed")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
in.Write([]byte("grab-client\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("client conflict setup failed")
|
||||
}
|
||||
listener.SetCommandGrabs(true)
|
||||
for listener.ApplicationBindingsAvailable() {
|
||||
select {
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal("optional re-enable conflict stopped reader", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("re-enable conflict not detected")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
send("Insert+q")
|
||||
receive(input.Quit)
|
||||
if err := listener.SetOCRContext(ctx, info.Window, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in.Write([]byte("focus-other\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("focus transition failed")
|
||||
}
|
||||
for listener.OCRReviewEnabled() {
|
||||
select {
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal(err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("application refresh replaced OCR source anchor")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
receive(input.OCRDismiss)
|
||||
send("Up")
|
||||
send("Escape")
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case event := <-listener.Commands():
|
||||
t.Fatalf("OCR key leaked after focus change: %+v", event)
|
||||
default:
|
||||
}
|
||||
|
||||
unsupported := input.BindingOverride{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "other", Command: "tentacle/test/unsupported", Keys: []string{"~"}}
|
||||
if err := listener.SetTentacleBindings(ctx, append(bindings, unsupported)); err != nil {
|
||||
t.Fatal("optional unsupported symbol broke core input", err)
|
||||
}
|
||||
for listener.ApplicationBindingsAvailable() {
|
||||
select {
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal(err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("unsupported application symbol not disabled")
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
send("Insert+q")
|
||||
receive(input.Quit)
|
||||
|
||||
}
|
||||
|
||||
func TestNativeApplicationDoesNotReserveRootShortcut(t *testing.T) {
|
||||
if os.Getenv("CTHULHU_NATIVE_X11") != "1" {
|
||||
t.Skip("private X11 required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
fixture := exec.CommandContext(ctx, "/usr/bin/python3", "-u", "../../../tests/application_fixture.py")
|
||||
in, _ := fixture.StdinPipe()
|
||||
out, _ := fixture.StdoutPipe()
|
||||
fixture.Stderr = os.Stderr
|
||||
if err := fixture.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { in.Close(); fixture.Wait() }()
|
||||
scanner := bufio.NewScanner(out)
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("fixture startup")
|
||||
}
|
||||
var info struct{ Window uint64 }
|
||||
json.Unmarshal(scanner.Bytes(), &info)
|
||||
listener := NewCommands([]string{"Insert"}, input.DesktopKeyboardLayout)
|
||||
bindings := []input.BindingOverride{
|
||||
{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/dismiss", Keys: []string{"Ctrl+D"}},
|
||||
{Layout: input.DesktopKeyboardLayout, Scope: "global", Application: "example-app", Command: "tentacle/test/scroll", Keys: []string{"Shift+Up"}},
|
||||
}
|
||||
in.Write([]byte("grab-root\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("root shortcut owner did not start")
|
||||
}
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := listener.Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Stop(context.Background())
|
||||
|
||||
in.Write([]byte("destroy\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("client destroy failed")
|
||||
}
|
||||
if err := listener.SetTentacleBindings(ctx, bindings); err != nil {
|
||||
t.Fatal("client destruction broke core grabs", err)
|
||||
}
|
||||
if err := exec.CommandContext(ctx, "xdotool", "key", "Insert+q").Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case event := <-listener.Commands():
|
||||
if event.Command != input.Quit {
|
||||
t.Fatal(event)
|
||||
}
|
||||
case err := <-listener.Failures():
|
||||
t.Fatal(err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("core shortcut lost after client destruction")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#include "automation_native.h"
|
||||
#include <X11/Xatom.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/extensions/XTest.h>
|
||||
#include <X11/keysym.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// One bounded native operation per step. Go owns waits and cancellation;
|
||||
// cleanup owns every synthetic release even after focus or lock changes.
|
||||
struct CthulhuAutomation {
|
||||
Display *display;
|
||||
Foreground source;
|
||||
char application[128];
|
||||
int button;
|
||||
KeyCode modifier;
|
||||
};
|
||||
|
||||
static int automation_idle(CthulhuAutomation *device) {
|
||||
char keys[32];
|
||||
XQueryKeymap(device->display, keys);
|
||||
if (device->modifier)
|
||||
keys[device->modifier / 8] &= ~(1U << (device->modifier % 8));
|
||||
int held = 0;
|
||||
for (int i = 0; i < 32; i++)
|
||||
held |= keys[i];
|
||||
Window root, child;
|
||||
int px, py, wx, wy;
|
||||
unsigned mask;
|
||||
if (!XQueryPointer(device->display, DefaultRootWindow(device->display), &root, &child, &px, &py,
|
||||
&wx, &wy, &mask))
|
||||
return 0;
|
||||
unsigned owned = device->button ? (Button1Mask << (device->button - 1)) : 0;
|
||||
return !held &&
|
||||
!(mask &
|
||||
((Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask) & ~owned));
|
||||
}
|
||||
|
||||
CthulhuAutomation *cthulhu_automation_begin(unsigned long window, const char *application,
|
||||
int operation, int x, int y, int width, int height) {
|
||||
Display *display = XOpenDisplay(NULL);
|
||||
if (!display)
|
||||
return NULL;
|
||||
Foreground fg = read_foreground(display);
|
||||
int base, error, major, minor;
|
||||
CthulhuAutomation *device = calloc(1, sizeof(*device));
|
||||
if (!device) {
|
||||
XCloseDisplay(display);
|
||||
return NULL;
|
||||
}
|
||||
device->display = display;
|
||||
device->source = fg;
|
||||
if (!application || strlen(application) >= sizeof(device->application) || !window ||
|
||||
!fg.known || fg.window != window || fg.width <= 0 || fg.height <= 0 || fg.x != x ||
|
||||
fg.y != y || fg.width != width || fg.height != height ||
|
||||
!cthulhu_application_matches(display, window, application) || !automation_idle(device) ||
|
||||
!XTestQueryExtension(display, &base, &error, &major, &minor))
|
||||
goto fail;
|
||||
strcpy(device->application, application);
|
||||
if (operation == 2 || operation == 3 || operation == 4) {
|
||||
Window root, child;
|
||||
int px, py, wx, wy;
|
||||
unsigned mask;
|
||||
if (!XQueryPointer(display, DefaultRootWindow(display), &root, &child, &px, &py, &wx, &wy,
|
||||
&mask) ||
|
||||
px < fg.x || px >= fg.x + fg.width || py < fg.y || py >= fg.y + fg.height)
|
||||
goto fail;
|
||||
}
|
||||
return device;
|
||||
fail:
|
||||
XCloseDisplay(display);
|
||||
free(device);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int cthulhu_automation_step(CthulhuAutomation *device, int operation, int x, int y, int button,
|
||||
int modifier) {
|
||||
Display *display = device->display;
|
||||
// Prevent another client changing focus/geometry between validation and effect.
|
||||
// No sleep or Go callback occurs while the X server is held.
|
||||
cthulhu_x11_begin_read(display);
|
||||
XGrabServer(display);
|
||||
Foreground source = device->source;
|
||||
XWindowAttributes attributes;
|
||||
Window child;
|
||||
int origin_x = 0, origin_y = 0;
|
||||
int ok = XGetWindowAttributes(display, source.window, &attributes) &&
|
||||
attributes.map_state == IsViewable &&
|
||||
XTranslateCoordinates(display, source.window, DefaultRootWindow(display), 0, 0,
|
||||
&origin_x, &origin_y, &child) &&
|
||||
origin_x == source.x && origin_y == source.y && attributes.width == source.width &&
|
||||
attributes.height == source.height &&
|
||||
cthulhu_application_matches_unchecked(display, source.window, device->application) &&
|
||||
automation_idle(device);
|
||||
if (ok && (operation == 1 || operation == 6)) {
|
||||
if (operation == 1) {
|
||||
x = source.x + (int)(((long long)source.width * x + 5000) / 10000);
|
||||
y = source.y + (int)(((long long)source.height * y + 5000) / 10000);
|
||||
if (x >= source.x + source.width)
|
||||
x = source.x + source.width - 1;
|
||||
if (y >= source.y + source.height)
|
||||
y = source.y + source.height - 1;
|
||||
}
|
||||
if (x < source.x || x >= source.x + source.width || y < source.y ||
|
||||
y >= source.y + source.height || x < 0 || y < 0 ||
|
||||
x >= DisplayWidth(display, DefaultScreen(display)) ||
|
||||
y >= DisplayHeight(display, DefaultScreen(display)))
|
||||
ok = 0;
|
||||
if (ok)
|
||||
ok = XTestFakeMotionEvent(display, -1, x, y, CurrentTime);
|
||||
} else if (ok && operation == 2) {
|
||||
KeyCode code = modifier == 1 ? XKeysymToKeycode(display, XK_Shift_L)
|
||||
: modifier == 4 ? XKeysymToKeycode(display, XK_Control_L)
|
||||
: 0;
|
||||
if ((button != 1 && button != 3) || device->button || (modifier && !code))
|
||||
ok = 0;
|
||||
if (ok && code) {
|
||||
ok = XTestFakeKeyEvent(display, code, True, CurrentTime);
|
||||
if (ok)
|
||||
device->modifier = code;
|
||||
}
|
||||
if (ok) {
|
||||
ok = XTestFakeButtonEvent(display, button, True, CurrentTime);
|
||||
if (ok)
|
||||
device->button = button;
|
||||
}
|
||||
} else if (ok && operation == 4) {
|
||||
if (button != 4 && button != 5)
|
||||
ok = 0;
|
||||
if (ok) {
|
||||
int pressed = XTestFakeButtonEvent(display, button, True, CurrentTime);
|
||||
int released = XTestFakeButtonEvent(display, button, False, CurrentTime);
|
||||
ok = pressed && released;
|
||||
}
|
||||
} else if (ok && operation == 5) {
|
||||
XBell(display, 0);
|
||||
} else
|
||||
ok = 0;
|
||||
XUngrabServer(display);
|
||||
return !cthulhu_x11_end_read(display) && ok;
|
||||
}
|
||||
|
||||
void cthulhu_automation_end(CthulhuAutomation *device) {
|
||||
if (!device)
|
||||
return;
|
||||
if (device->button)
|
||||
XTestFakeButtonEvent(device->display, device->button, False, CurrentTime);
|
||||
if (device->modifier)
|
||||
XTestFakeKeyEvent(device->display, device->modifier, False, CurrentTime);
|
||||
XSync(device->display, False);
|
||||
XCloseDisplay(device->display);
|
||||
free(device);
|
||||
}
|
||||
|
||||
unsigned long cthulhu_automation_time(unsigned long window, const char *application) {
|
||||
Display *display = XOpenDisplay(NULL);
|
||||
if (!display)
|
||||
return 0;
|
||||
Foreground fg = read_foreground(display);
|
||||
if (fg.window != window || !cthulhu_application_matches(display, window, application)) {
|
||||
XCloseDisplay(display);
|
||||
return 0;
|
||||
}
|
||||
XSetWindowAttributes attributes = {0};
|
||||
attributes.event_mask = PropertyChangeMask;
|
||||
Window probe = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 1, 1, 0, 0, InputOnly,
|
||||
CopyFromParent, CWEventMask, &attributes);
|
||||
unsigned char value = 0;
|
||||
XChangeProperty(display, probe, XInternAtom(display, "_CTHULHU_AUTOMATION_TIME", False),
|
||||
XA_INTEGER, 8, PropModeReplace, &value, 1);
|
||||
XEvent event;
|
||||
XWindowEvent(display, probe, PropertyChangeMask, &event);
|
||||
unsigned long timestamp = event.xproperty.time;
|
||||
XDestroyWindow(display, probe);
|
||||
XCloseDisplay(display);
|
||||
return timestamp;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package xorg
|
||||
|
||||
/*
|
||||
#include "automation_native.h"
|
||||
#include <stdlib.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
)
|
||||
|
||||
func (listener *CommandListener) AutomationAction(ctx context.Context, window uint64, application string, bounds image.Rectangle, a tentaclewire.AutomationAction) error {
|
||||
if !tentaclewire.ValidAutomation(tentaclewire.Automation{Actions: []tentaclewire.AutomationAction{a}}) {
|
||||
return errors.New("invalid automation action")
|
||||
}
|
||||
op := map[string]int{"move": 1, "click": 2, "drag": 3, "scroll": 4, "tone": 5}[a.Kind]
|
||||
if op == 0 {
|
||||
return errors.New("unsupported native action")
|
||||
}
|
||||
return listener.automationNative(ctx, window, application, bounds, op, a.X, a.Y, a.Button, map[string]int{"shift": 1, "control": 4}[a.Modifier], a.Steps, a.Milliseconds)
|
||||
}
|
||||
|
||||
func (listener *CommandListener) MoveAutomationPointer(ctx context.Context, window uint64, application string, bounds image.Rectangle, point image.Point) error {
|
||||
return listener.automationNative(ctx, window, application, bounds, 6, point.X, point.Y, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
func (listener *CommandListener) automationNative(ctx context.Context, window uint64, application string, bounds image.Rectangle, op, x, y, button, modifier, steps, milliseconds int) error {
|
||||
if !tentaclewire.ValidApplication(application) || window == 0 || bounds.Empty() {
|
||||
return errors.New("invalid application")
|
||||
}
|
||||
name := C.CString(application)
|
||||
defer C.free(unsafe.Pointer(name))
|
||||
listener.secureMutex.Lock()
|
||||
if ctx.Err() != nil || listener.secure.Load() || listener.ocrApplied.Load() {
|
||||
listener.secureMutex.Unlock()
|
||||
return errors.New("automation input unavailable")
|
||||
}
|
||||
device := C.cthulhu_automation_begin(C.ulong(window), name, C.int(op), C.int(bounds.Min.X), C.int(bounds.Min.Y), C.int(bounds.Dx()), C.int(bounds.Dy()))
|
||||
listener.secureMutex.Unlock()
|
||||
if device == nil {
|
||||
return errors.New("automation source changed or physical input is held")
|
||||
}
|
||||
defer func() { listener.secureMutex.Lock(); C.cthulhu_automation_end(device); listener.secureMutex.Unlock() }()
|
||||
step := func(operation, x, y, button, modifier int) error {
|
||||
listener.secureMutex.Lock()
|
||||
defer listener.secureMutex.Unlock()
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if listener.secure.Load() || listener.ocrApplied.Load() {
|
||||
return errors.New("automation input unavailable")
|
||||
}
|
||||
if C.cthulhu_automation_step(device, C.int(operation), C.int(x), C.int(y), C.int(button), C.int(modifier)) == 0 {
|
||||
return errors.New("automation source changed or physical input is held")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
switch op {
|
||||
case 1, 5, 6:
|
||||
return step(op, x, y, 0, 0)
|
||||
case 2:
|
||||
if err := step(2, 0, 0, button, modifier); err != nil {
|
||||
return err
|
||||
}
|
||||
return automationWait(ctx, time.Duration(milliseconds)*time.Millisecond)
|
||||
case 3:
|
||||
if err := step(2, 0, 0, 1, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := automationWait(ctx, time.Duration(milliseconds)*time.Millisecond); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step(1, x, y, 0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
return automationWait(ctx, time.Duration(milliseconds)*time.Millisecond)
|
||||
case 4:
|
||||
wheel := 4
|
||||
if steps < 0 {
|
||||
steps = -steps
|
||||
wheel = 5
|
||||
}
|
||||
for i := 0; i < steps; i++ {
|
||||
if err := step(4, 0, 0, wheel, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if i+1 < steps {
|
||||
if err := automationWait(ctx, time.Duration(milliseconds)*time.Millisecond); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("unsupported native action")
|
||||
}
|
||||
|
||||
// AutomationTimestamp fences XRecord observations from before a new OCR scan.
|
||||
func (listener *CommandListener) AutomationTimestamp(ctx context.Context, window uint64, application string) (uint32, error) {
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
if !tentaclewire.ValidApplication(application) || window == 0 || listener.secure.Load() {
|
||||
return 0, errors.New("application unavailable")
|
||||
}
|
||||
name := C.CString(application)
|
||||
defer C.free(unsafe.Pointer(name))
|
||||
timestamp := uint32(C.cthulhu_automation_time(C.ulong(window), name))
|
||||
if timestamp == 0 {
|
||||
return 0, errors.New("OCR scan timestamp unavailable")
|
||||
}
|
||||
return timestamp, nil
|
||||
}
|
||||
|
||||
func automationWait(ctx context.Context, duration time.Duration) error {
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#ifndef CTHULHU_AUTOMATION_NATIVE_H
|
||||
#define CTHULHU_AUTOMATION_NATIVE_H
|
||||
#include "commands_native.h"
|
||||
typedef struct CthulhuAutomation CthulhuAutomation;
|
||||
CthulhuAutomation *cthulhu_automation_begin(unsigned long window, const char *application,
|
||||
int operation, int x, int y, int width, int height);
|
||||
int cthulhu_automation_step(CthulhuAutomation *device, int operation, int x, int y, int button,
|
||||
int modifier);
|
||||
void cthulhu_automation_end(CthulhuAutomation *device);
|
||||
|
||||
unsigned long cthulhu_automation_time(unsigned long window, const char *application);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,118 @@
|
||||
package xorg
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"os"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/tentaclewire"
|
||||
)
|
||||
|
||||
func TestNativeApplicationAutomation(t *testing.T) {
|
||||
if os.Getenv("CTHULHU_NATIVE_X11") != "1" {
|
||||
t.Skip("private X11 required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
fixture := exec.CommandContext(ctx, "/usr/bin/python3", "-u", "../../../tests/application_fixture.py")
|
||||
in, _ := fixture.StdinPipe()
|
||||
out, _ := fixture.StdoutPipe()
|
||||
fixture.Stderr = os.Stderr
|
||||
if err := fixture.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { in.Close(); fixture.Wait() }()
|
||||
scanner := bufio.NewScanner(out)
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("fixture startup")
|
||||
}
|
||||
var info struct{ Window uint64 }
|
||||
if err := json.Unmarshal(scanner.Bytes(), &info); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener := NewCommands([]string{"Insert"}, 0)
|
||||
if _, err := listener.ApplicationWindow("other"); err == nil {
|
||||
t.Fatal("matched other class")
|
||||
}
|
||||
bounds := image.Rect(20, 20, 260, 160)
|
||||
window, err := listener.ApplicationWindow("example-app")
|
||||
if err != nil || window != info.Window {
|
||||
t.Fatalf("window %d: %v", window, err)
|
||||
}
|
||||
act := func(a tentaclewire.AutomationAction) {
|
||||
t.Helper()
|
||||
if err := listener.AutomationAction(ctx, window, "example-app", bounds, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
stamp, err := listener.AutomationTimestamp(ctx, window, "example-app")
|
||||
if err != nil || stamp == 0 {
|
||||
t.Fatalf("timestamp %d: %v", stamp, err)
|
||||
}
|
||||
act(tentaclewire.AutomationAction{Kind: "move", X: 5000, Y: 5000})
|
||||
act(tentaclewire.AutomationAction{Kind: "click", Button: 3, Modifier: "shift"})
|
||||
if err := listener.AutomationAction(ctx, window+1, "example-app", bounds, tentaclewire.AutomationAction{Kind: "click", Button: 1}); err == nil {
|
||||
t.Fatal("clicked wrong window")
|
||||
}
|
||||
actualBounds, err := listener.ApplicationBounds("example-app", window)
|
||||
if err != nil || actualBounds != bounds {
|
||||
t.Fatalf("client bounds %v: %v", actualBounds, err)
|
||||
}
|
||||
if err := listener.AutomationAction(ctx, window, "example-app", bounds.Add(image.Pt(1, 0)), tentaclewire.AutomationAction{Kind: "click", Button: 1}); err == nil {
|
||||
t.Fatal("clicked after geometry mismatch")
|
||||
}
|
||||
|
||||
in.Write([]byte("events\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("events missing")
|
||||
}
|
||||
var result struct {
|
||||
Events []struct {
|
||||
Pressed bool
|
||||
Button, X, Y, State int
|
||||
}
|
||||
Mask int
|
||||
}
|
||||
if err := json.Unmarshal(scanner.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Events) != 2 || result.Events[0].Button != 3 || result.Events[0].X != 140 || result.Events[0].Y != 90 || result.Events[0].State&1 == 0 || result.Mask&0x700 != 0 {
|
||||
t.Fatalf("events %+v", result)
|
||||
}
|
||||
actionCtx, stopAction := context.WithCancel(ctx)
|
||||
completed := make(chan error, 1)
|
||||
go func() {
|
||||
completed <- listener.AutomationAction(actionCtx, window, "example-app", bounds, tentaclewire.AutomationAction{Kind: "drag", X: 7500, Y: 7500, Milliseconds: 150})
|
||||
}()
|
||||
in.Write([]byte("wait-press\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("drag press missing")
|
||||
}
|
||||
stopAction()
|
||||
if err := <-completed; err == nil {
|
||||
t.Fatal("cancelled drag completed")
|
||||
}
|
||||
in.Write([]byte("events\n"))
|
||||
if !scanner.Scan() {
|
||||
t.Fatal("cleanup events missing")
|
||||
}
|
||||
var cleanup struct {
|
||||
Mask int
|
||||
Pointer []int
|
||||
}
|
||||
if err := json.Unmarshal(scanner.Bytes(), &cleanup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cleanup.Mask&0x700 != 0 || len(cleanup.Pointer) != 2 || cleanup.Pointer[0] != 140 || cleanup.Pointer[1] != 90 {
|
||||
t.Fatalf("cancel did not stop drag: %+v", cleanup)
|
||||
}
|
||||
listener.secure.Store(true)
|
||||
if err := listener.AutomationAction(ctx, window, "example-app", bounds, tentaclewire.AutomationAction{Kind: "move"}); err == nil {
|
||||
t.Fatal("secure input accepted")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type CommandListener struct {
|
||||
browseApplied atomic.Bool
|
||||
bypass atomic.Bool
|
||||
bypassApplied atomic.Bool
|
||||
applicationUnavailable atomic.Bool
|
||||
nativeButtonFocus atomic.Bool
|
||||
nativeButtonApplied atomic.Bool
|
||||
grabActive atomic.Bool
|
||||
@@ -123,3 +124,9 @@ func (listener *CommandListener) Failures() <-chan error { return listener.failu
|
||||
func (listener *CommandListener) FocusChanges() <-chan FocusState {
|
||||
return listener.focusChanges
|
||||
}
|
||||
|
||||
// ApplicationBindingsAvailable reports whether the current application's
|
||||
// optional shortcuts could be installed. Core command ownership is independent.
|
||||
func (listener *CommandListener) ApplicationBindingsAvailable() bool {
|
||||
return !listener.applicationUnavailable.Load()
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package xorg
|
||||
|
||||
/*
|
||||
#include "commands_native.h"
|
||||
#include <stdlib.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/input"
|
||||
)
|
||||
|
||||
// Cache the matching client for optional, application-scoped command bindings.
|
||||
type applicationBindingContext struct {
|
||||
overrides []input.BindingOverride
|
||||
window uint64
|
||||
signature string
|
||||
}
|
||||
|
||||
func readApplicationBindingContext(device *C.CommandDevice, overrides []input.BindingOverride) applicationBindingContext {
|
||||
result := applicationBindingContext{}
|
||||
hasApplications := false
|
||||
for _, binding := range overrides {
|
||||
if binding.Application != "" {
|
||||
hasApplications = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasApplications {
|
||||
result.overrides = overrides
|
||||
return result
|
||||
}
|
||||
foreground := C.read_foreground(device.display)
|
||||
matched := map[string]bool{}
|
||||
var names []string
|
||||
for _, binding := range overrides {
|
||||
if binding.Application != "" {
|
||||
match, known := matched[binding.Application]
|
||||
if !known {
|
||||
name := C.CString(binding.Application)
|
||||
match = foreground.known != 0 && C.cthulhu_application_matches(device.display, foreground.window, name) != 0
|
||||
C.free(unsafe.Pointer(name))
|
||||
matched[binding.Application] = match
|
||||
if match {
|
||||
names = append(names, binding.Application)
|
||||
}
|
||||
}
|
||||
if !match {
|
||||
continue
|
||||
}
|
||||
}
|
||||
result.overrides = append(result.overrides, binding)
|
||||
}
|
||||
if len(names) > 0 {
|
||||
result.window = uint64(foreground.window)
|
||||
result.signature = strconv.FormatUint(result.window, 10) + "\x00" + strings.Join(names, "\x00")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (owner *commandOwner) applicationOverrides() []input.BindingOverride {
|
||||
if !owner.hasApplicationBindings() {
|
||||
return owner.overrides
|
||||
}
|
||||
if owner.applicationActive && owner.device.applicationBindingsBlocked == 0 {
|
||||
return readApplicationBindingContext(owner.device, owner.overrides).overrides
|
||||
}
|
||||
var result []input.BindingOverride
|
||||
for _, binding := range owner.overrides {
|
||||
if binding.Application == "" {
|
||||
result = append(result, binding)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Focus-scoped grabs are refreshed on the existing bounded input-owner poll.
|
||||
// Inactive applications incur no per-chord native queries or binding rebuilds.
|
||||
func (owner *commandOwner) configureApplicationBindings() error {
|
||||
anchor := owner.device.browseWindow
|
||||
if owner.ocrReview {
|
||||
defer func() { owner.device.browseWindow = anchor }()
|
||||
}
|
||||
return configureContextBindings(owner.device, owner.layout, owner.modifiers, owner.overrides, owner.listener.browse.Load(), owner.ocrReview, owner.ocrPending)
|
||||
}
|
||||
|
||||
// Repair optional native grab failures from every input-owner path, including
|
||||
// command re-enable and browser/OCR changes. Core failures remain fatal.
|
||||
func (owner *commandOwner) syncApplicationAvailability() bool {
|
||||
if owner.device.applicationBindingsBlocked == 0 {
|
||||
return true
|
||||
}
|
||||
owner.applicationActive = false
|
||||
if owner.listener.applicationUnavailable.Load() {
|
||||
return true
|
||||
}
|
||||
if err := owner.configureApplicationBindings(); err != nil {
|
||||
owner.listener.failures <- err
|
||||
return false
|
||||
}
|
||||
owner.listener.applicationUnavailable.Store(true)
|
||||
owner.router.ReplaceBindings(owner.contextBindings())
|
||||
return true
|
||||
}
|
||||
|
||||
func (owner *commandOwner) syncApplicationBindings() bool {
|
||||
if !owner.syncApplicationAvailability() {
|
||||
return false
|
||||
}
|
||||
if !owner.hasApplicationBindings() {
|
||||
owner.applicationActive = false
|
||||
owner.applicationSignature = ""
|
||||
owner.listener.applicationUnavailable.Store(false)
|
||||
owner.device.applicationBindingsBlocked = 0
|
||||
return true
|
||||
}
|
||||
if len(owner.held) != 0 || time.Since(owner.applicationCheck) < xtermFocusCheckInterval {
|
||||
return true
|
||||
}
|
||||
owner.applicationCheck = time.Now()
|
||||
next := readApplicationBindingContext(owner.device, owner.overrides)
|
||||
if next.signature == owner.applicationSignature {
|
||||
return true
|
||||
}
|
||||
owner.device.applicationBindingsBlocked = 0
|
||||
owner.listener.applicationUnavailable.Store(false)
|
||||
if err := owner.configureApplicationBindings(); err != nil {
|
||||
owner.listener.failures <- err
|
||||
return false
|
||||
}
|
||||
owner.applicationActive = next.window != 0 && owner.device.applicationBindingsBlocked == 0
|
||||
owner.applicationSignature = next.signature
|
||||
if !owner.syncApplicationAvailability() {
|
||||
return false
|
||||
}
|
||||
owner.router.ReplaceBindings(owner.contextBindings())
|
||||
return true
|
||||
}
|
||||
|
||||
func (owner *commandOwner) hasApplicationBindings() bool {
|
||||
for _, binding := range owner.overrides {
|
||||
if binding.Application != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -157,6 +157,18 @@ func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.Keyboa
|
||||
capsCode = C.int(code)
|
||||
}
|
||||
}
|
||||
context := readApplicationBindingContext(device, overrides)
|
||||
overrides = context.overrides
|
||||
if device.applicationBindingsBlocked != 0 {
|
||||
var ordinary []input.BindingOverride
|
||||
for _, binding := range overrides {
|
||||
if binding.Application == "" {
|
||||
ordinary = append(ordinary, binding)
|
||||
}
|
||||
}
|
||||
overrides = ordinary
|
||||
context.window = 0
|
||||
}
|
||||
global := resolvedBindings(layout, false, overrides)
|
||||
browse := resolvedBindings(layout, true, overrides)
|
||||
if device.bypass != 0 {
|
||||
@@ -168,6 +180,18 @@ func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.Keyboa
|
||||
browse = input.OCRPendingBindings(global)
|
||||
}
|
||||
}
|
||||
if device.bypass == 0 {
|
||||
browse = input.ApplicationBindings(browse, layout, overrides)
|
||||
}
|
||||
applications := make(map[input.CommandChord]string)
|
||||
for _, override := range overrides {
|
||||
if override.Layout == layout && override.Application != "" {
|
||||
for _, key := range override.Keys {
|
||||
chord, _ := input.ParseCommandChord(key)
|
||||
applications[chord] = override.Application
|
||||
}
|
||||
}
|
||||
}
|
||||
customizedBrowse := make(map[input.CommandChord]bool)
|
||||
for _, override := range overrides {
|
||||
if override.Layout == layout && override.Scope == "browse" {
|
||||
@@ -179,6 +203,7 @@ func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.Keyboa
|
||||
}
|
||||
var native []C.NativeBinding
|
||||
var extraModifierMask uint16
|
||||
optionalUnavailable := false
|
||||
for chord, command := range browse {
|
||||
if chord.CthulhuModifier {
|
||||
extraModifierMask |= chord.Modifiers & (8 | 64)
|
||||
@@ -186,17 +211,28 @@ func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.Keyboa
|
||||
// Validate that the native keymap can actually produce the symbol.
|
||||
code := C.XKeysymToKeycode(device.display, C.KeySym(chord.Symbol))
|
||||
if code == 0 || uint32(C.XkbKeycodeToKeysym(device.display, code, 0, 0)) != chord.Symbol {
|
||||
if applications[chord] != "" {
|
||||
optionalUnavailable = true
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("key %s is unavailable as a base key on this X11 keymap", input.FormatCommandChord(chord))
|
||||
}
|
||||
continue
|
||||
}
|
||||
value := C.NativeBinding{symbol: C.ulong(chord.Symbol), modifiers: C.uint(chord.Modifiers)}
|
||||
for i, b := range []byte(applications[chord]) {
|
||||
value.application[i] = C.char(b)
|
||||
}
|
||||
if global[chord] == "" || ocrReview {
|
||||
value.browseOnly = 1
|
||||
}
|
||||
if customizedBrowse[chord] && !ocrReview {
|
||||
value.probe = 1
|
||||
}
|
||||
if applications[chord] != "" {
|
||||
value.browseOnly = 0
|
||||
value.window = C.Window(context.window)
|
||||
}
|
||||
if command == input.DocumentActivate {
|
||||
value.activate = 1
|
||||
}
|
||||
@@ -219,5 +255,8 @@ func configureNativeBindingsWithOCR(device *C.CommandDevice, layout input.Keyboa
|
||||
if err := C.configure_command_bindings(device, first, C.int(len(native)), C.uint(extraModifierMask), insertCode, keypadCode, capsCode); err != 0 {
|
||||
return fmt.Errorf("change X11 key bindings: native error %d (key unavailable or grabbed by another application)", int(err))
|
||||
}
|
||||
if optionalUnavailable {
|
||||
device.applicationBindingsBlocked = 1
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -34,6 +34,9 @@ func isCapsLockToggle(keys []C.CommandKey) bool {
|
||||
}
|
||||
|
||||
func (owner *commandOwner) handleKey(key C.CommandKey) bool {
|
||||
if owner.applicationActive && len(owner.held) == 0 && key.pressed != 0 && !owner.learnMode && owner.uiSession == 0 && owner.remote == nil {
|
||||
owner.router.ReplaceBindings(owner.contextBindings())
|
||||
}
|
||||
owner.listener.grabActive.Store(true)
|
||||
// Focus policy can change while the native owner waits for an X
|
||||
// event. Replay a stale browse-only press against the requested
|
||||
|
||||
@@ -18,9 +18,19 @@
|
||||
static pthread_mutex_t error_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static Display *error_display;
|
||||
static int grab_error;
|
||||
static int installing_application_keys, application_grab_error;
|
||||
static Window optional_application_windows[2];
|
||||
static int (*previous_error_handler)(Display *, XErrorEvent *);
|
||||
static int command_error(Display *display, XErrorEvent *event) {
|
||||
if (display == error_display) { grab_error = event->error_code; return 0; }
|
||||
if (display == error_display) {
|
||||
if (installing_application_keys && (event->error_code==BadAccess || event->error_code==BadWindow)) {
|
||||
application_grab_error=event->error_code; return 0;
|
||||
}
|
||||
if (event->error_code == BadWindow &&
|
||||
((optional_application_windows[0] && event->resourceid==optional_application_windows[0]) ||
|
||||
(optional_application_windows[1] && event->resourceid==optional_application_windows[1]))) return 0;
|
||||
grab_error = event->error_code; return 0;
|
||||
}
|
||||
return previous_error_handler ? previous_error_handler(display, event) : 0;
|
||||
}
|
||||
// Metadata readers share the keyboard owner's guard because Xlib's error
|
||||
@@ -422,8 +432,13 @@ static void grab_command_keys(CommandDevice *device) {
|
||||
if (device->insertCode) XGrabKey(device->display,device->insertCode,mask,device->root,False,GrabModeAsync,GrabModeSync);
|
||||
if (device->keypadCode && !(mask & device->numlockMask)) XGrabKey(device->display,device->keypadCode,mask,device->root,False,GrabModeAsync,GrabModeSync);
|
||||
}
|
||||
// Finish root/core requests before classifying optional client-grab errors.
|
||||
for (int client_phase=0;client_phase<2;client_phase++) {
|
||||
if (client_phase && (!device->applicationGrabWindow || device->applicationBindingsBlocked)) continue;
|
||||
installing_application_keys=client_phase;
|
||||
for (int j=0;j<device->bindingCount;j++) {
|
||||
NativeBinding binding=device->bindings[j];
|
||||
if (!!binding.window != client_phase) continue;
|
||||
if (binding.browseOnly && !device->browse && !(device->probeBindings && binding.probe)) continue;
|
||||
int code=XKeysymToKeycode(device->display,binding.symbol);
|
||||
if (!code) continue;
|
||||
@@ -431,9 +446,12 @@ static void grab_command_keys(CommandDevice *device) {
|
||||
if ((mask & ~device->ignoredModifierMask) != binding.modifiers) continue;
|
||||
// Non-numeric keypad navigation has a different meaning with NumLock.
|
||||
if (binding.symbol>=XK_KP_Home && binding.symbol<=XK_KP_Delete && (mask & device->numlockMask)) continue;
|
||||
XGrabKey(device->display,code,mask,device->root,False,GrabModeAsync,GrabModeSync);
|
||||
XGrabKey(device->display,code,mask,binding.window ? binding.window : device->root,False,GrabModeAsync,GrabModeSync);
|
||||
}
|
||||
}
|
||||
if (device->applicationGrabWindow && !device->applicationBindingsBlocked) XSync(device->display,False);
|
||||
installing_application_keys=0;
|
||||
}
|
||||
}
|
||||
int set_command_keys(CommandDevice *device, int enabled) {
|
||||
// Another reader may have changed Caps Lock while command input was
|
||||
@@ -447,7 +465,13 @@ int set_command_keys(CommandDevice *device, int enabled) {
|
||||
XSync(device->display,False);
|
||||
error_display=device->display; grab_error=0;
|
||||
previous_error_handler=XSetErrorHandler(command_error);
|
||||
application_grab_error=0; installing_application_keys=0;
|
||||
optional_application_windows[0]=device->applicationGrabWindow;
|
||||
optional_application_windows[1]=0;
|
||||
for (int i=0;i<device->bindingCount;i++) if (device->bindings[i].window) {optional_application_windows[1]=device->bindings[i].window;break;}
|
||||
XUngrabKey(device->display,AnyKey,AnyModifier,device->root);
|
||||
if (device->applicationGrabWindow) XUngrabKey(device->display,AnyKey,AnyModifier,device->applicationGrabWindow);
|
||||
device->applicationGrabWindow=enabled ? optional_application_windows[1] : 0;
|
||||
if (!enabled) {
|
||||
// A synchronous passive grab may already have activated before Go
|
||||
// consumes its press. XUngrabKey only removes future registrations.
|
||||
@@ -456,11 +480,21 @@ int set_command_keys(CommandDevice *device, int enabled) {
|
||||
}
|
||||
if (enabled) grab_command_keys(device);
|
||||
XSync(device->display,False);
|
||||
if (application_grab_error) {
|
||||
// Never leave a partially registered application key set behind.
|
||||
if (device->applicationGrabWindow) XUngrabKey(device->display,AnyKey,AnyModifier,device->applicationGrabWindow);
|
||||
device->applicationGrabWindow=0;
|
||||
device->applicationBindingsBlocked=1;
|
||||
XSync(device->display,False);
|
||||
}
|
||||
int error=grab_error;
|
||||
if (error && enabled) {
|
||||
XUngrabKey(device->display,AnyKey,AnyModifier,device->root);
|
||||
if (device->applicationGrabWindow) XUngrabKey(device->display,AnyKey,AnyModifier,device->applicationGrabWindow);
|
||||
device->applicationGrabWindow=0;
|
||||
XSync(device->display,False);
|
||||
}
|
||||
optional_application_windows[0]=optional_application_windows[1]=0;
|
||||
XSetErrorHandler(previous_error_handler); error_display=NULL;
|
||||
pthread_mutex_unlock(&error_mutex);
|
||||
device->commands=enabled && !error;
|
||||
@@ -472,10 +506,16 @@ int configure_command_bindings(CommandDevice *device, NativeBinding *bindings, i
|
||||
NativeBinding *copy=count ? malloc(sizeof(NativeBinding)*count) : NULL;
|
||||
if (count && !copy) return -3;
|
||||
if (count) memcpy(copy,bindings,sizeof(NativeBinding)*count);
|
||||
int optional_invalid=0;
|
||||
for (int i=0;i<count;i++) {
|
||||
int code=XKeysymToKeycode(device->display,copy[i].symbol);
|
||||
if (!code || XkbKeycodeToKeysym(device->display,code,0,0)!=copy[i].symbol) { free(copy); return -2; }
|
||||
if (!code || XkbKeycodeToKeysym(device->display,code,0,0)!=copy[i].symbol) {
|
||||
if (copy[i].window) {optional_invalid=1;continue;}
|
||||
free(copy);return -2;
|
||||
}
|
||||
}
|
||||
int previousApplicationBlocked=device->applicationBindingsBlocked;
|
||||
if (optional_invalid) device->applicationBindingsBlocked=1;
|
||||
int previousInsert=device->insertCode, previousKeypad=device->keypadCode, previousCaps=device->capsCode;
|
||||
NativeBinding *previous=device->bindings;
|
||||
int previousCount=device->bindingCount, enabled=device->commands;
|
||||
@@ -491,6 +531,7 @@ int configure_command_bindings(CommandDevice *device, NativeBinding *bindings, i
|
||||
if (!error && probing) error=set_command_keys(device,enabled);
|
||||
if (error) {
|
||||
device->bindings=previous; device->bindingCount=previousCount; device->extraModifierMask=previousMask;
|
||||
device->applicationBindingsBlocked=previousApplicationBlocked;
|
||||
device->insertCode=previousInsert; device->keypadCode=previousKeypad; device->capsCode=previousCaps;
|
||||
int restoreError=set_command_keys(device,enabled);
|
||||
free(copy);
|
||||
@@ -633,6 +674,12 @@ int next_command_key(CommandDevice *device, CommandKey *key) {
|
||||
for (int i=0;i<device->bindingCount;i++) {
|
||||
NativeBinding binding=device->bindings[i];
|
||||
if (binding.symbol==symbol && binding.modifiers==modifiers) {
|
||||
if (binding.application[0]) {
|
||||
Foreground foreground=read_foreground(device->display);
|
||||
if (!foreground.known || !cthulhu_application_matches(device->display,foreground.window,binding.application)) {
|
||||
XAllowEvents(device->display,ReplayKeyboard,event.xkey.time); XFlush(device->display); return 0;
|
||||
}
|
||||
}
|
||||
browseOnly=binding.browseOnly; activate=binding.activate; break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#include <X11/Xlib.h>
|
||||
|
||||
typedef struct { unsigned long symbol; unsigned int modifiers; int browseOnly, activate, probe; } NativeBinding;
|
||||
typedef struct { unsigned long symbol; unsigned int modifiers; int browseOnly, activate, probe; Window window; char application[128]; } NativeBinding;
|
||||
typedef struct {
|
||||
NativeBinding *bindings;
|
||||
int bindingCount, probeBindings;
|
||||
@@ -26,6 +26,8 @@ typedef struct {
|
||||
int browse;
|
||||
int nativeButtonFocus;
|
||||
Window browseWindow;
|
||||
Window applicationGrabWindow;
|
||||
int applicationBindingsBlocked;
|
||||
} CommandDevice;
|
||||
typedef struct { int pressed, code, symbol, remoteSymbol, textSymbol, modifiers, locks; unsigned long timestamp; char text[64]; } CommandKey;
|
||||
typedef struct {
|
||||
@@ -71,4 +73,10 @@ int replay_command_keys(CommandDevice *device, CommandKey *keys, int count);
|
||||
void close_commands(CommandDevice *device);
|
||||
int cthulhu_ocr_click(unsigned long foreground, int x, int y, int root_width, int root_height);
|
||||
|
||||
|
||||
int cthulhu_application_matches(Display *display, Window window, const char *application);
|
||||
unsigned long cthulhu_application_window(const char *application);
|
||||
Foreground cthulhu_application_foreground(const char *application);
|
||||
int cthulhu_application_matches_unchecked(Display *display,Window window,const char *application);
|
||||
|
||||
#endif
|
||||
@@ -74,13 +74,18 @@ func (owner *commandOwner) contextBindings() input.CommandBindings {
|
||||
if owner.device.bypass != 0 {
|
||||
return input.BypassCommandBindings(owner.globalBindings)
|
||||
}
|
||||
overrides, global := owner.overrides, owner.globalBindings
|
||||
if owner.hasApplicationBindings() {
|
||||
overrides = owner.applicationOverrides()
|
||||
global = resolvedBindings(owner.layout, false, overrides)
|
||||
}
|
||||
if owner.ocrReview {
|
||||
if owner.ocrPending {
|
||||
return input.OCRPendingBindings(owner.globalBindings)
|
||||
return input.OCRPendingBindings(global)
|
||||
}
|
||||
return input.OCRCommandBindings(owner.globalBindings)
|
||||
return input.ApplicationBindings(input.OCRCommandBindings(global), owner.layout, overrides)
|
||||
}
|
||||
return resolvedBindings(owner.layout, owner.device.browse != 0, owner.overrides)
|
||||
return resolvedBindings(owner.layout, owner.device.browse != 0, overrides)
|
||||
}
|
||||
|
||||
// Configure grabs and routing together. Native replacement restores old
|
||||
|
||||
@@ -40,6 +40,9 @@ type commandOwner struct {
|
||||
lastLocks, lastFocusMatch C.int
|
||||
lastFocusCheck, drainDeadline time.Time
|
||||
steamFocus steamFocusRepair
|
||||
applicationSignature string
|
||||
applicationActive bool
|
||||
applicationCheck time.Time
|
||||
}
|
||||
|
||||
func (listener *CommandListener) runCommandLoop(workerContext context.Context, device *C.CommandDevice, layout input.KeyboardLayout, modifiers []string, core, tentacles []input.BindingOverride, symbols []uint32) {
|
||||
@@ -50,7 +53,7 @@ func (listener *CommandListener) runCommandLoop(workerContext context.Context, d
|
||||
func (owner *commandOwner) run() {
|
||||
owner.publishFocus()
|
||||
owner.globalBindings = resolvedBindings(owner.layout, false, owner.overrides)
|
||||
owner.router = input.NewCommandRouter(owner.symbols, owner.globalBindings)
|
||||
owner.router = input.NewCommandRouter(owner.symbols, owner.contextBindings())
|
||||
owner.lastLocks = C.command_lock_state(owner.device)
|
||||
for {
|
||||
if owner.workerContext.Err() != nil {
|
||||
@@ -73,6 +76,9 @@ func (owner *commandOwner) run() {
|
||||
if !owner.applyBindingUpdate() {
|
||||
return
|
||||
}
|
||||
if !owner.syncApplicationBindings() {
|
||||
return
|
||||
}
|
||||
if time.Since(owner.lastFocusCheck) >= xtermFocusCheckInterval {
|
||||
owner.checkSteamFocus(owner.publishFocus())
|
||||
}
|
||||
@@ -179,6 +185,10 @@ func (owner *commandOwner) applyBindingUpdate() bool {
|
||||
if err == nil {
|
||||
owner.layout, owner.modifiers, owner.overrides = nextLayout, nextModifiers, nextOverrides
|
||||
owner.core, owner.tentacles = nextCore, nextTentacles
|
||||
owner.applicationCheck = time.Time{}
|
||||
if update.ocrReview == nil {
|
||||
owner.applicationSignature = "\x01"
|
||||
}
|
||||
owner.listener.publishTentacleBindings(nextOverrides)
|
||||
owner.ocrReview, owner.ocrPending = nextOCR, nextPending
|
||||
owner.listener.ocrPending.Store(nextPending)
|
||||
@@ -303,7 +313,7 @@ func (owner *commandOwner) syncGrabs() bool {
|
||||
owner.device.nativeButtonFocus = 1
|
||||
}
|
||||
owner.listener.nativeButtonApplied.Store(owner.device.nativeButtonFocus != 0)
|
||||
return true
|
||||
return owner.syncApplicationAvailability()
|
||||
}
|
||||
|
||||
func (owner *commandOwner) publishLocks(key C.CommandKey) {
|
||||
|
||||
@@ -23,6 +23,9 @@ func tentacleUpdateCapabilities(entry tentacle.Entry, manifest tentacle.Manifest
|
||||
if entry.ReaderSettings {
|
||||
previous = append(previous, "reader-settings")
|
||||
}
|
||||
if entry.Automation {
|
||||
previous = append(previous, "automation")
|
||||
}
|
||||
previous = append(previous, entry.RemoteGrants...)
|
||||
if len(previous) == 0 {
|
||||
previous = append(previous, "none")
|
||||
@@ -46,12 +49,13 @@ func tentacleInstallConfirmation(entry tentacle.Entry, manifest tentacle.Manifes
|
||||
if slices.Contains(manifest.Capabilities, "reader-settings") {
|
||||
permissions += " It can also add preferences pages and quick settings, inspect speech voices, and temporarily change the reader voice configuration."
|
||||
}
|
||||
permissions += automationPermissions(manifest.Capabilities)
|
||||
permissions += remotePermissions(manifest.Capabilities)
|
||||
return fmt.Sprintf("%s %s version %s from %s?\n\n%s\n\nOnly install packages from publishers you trust. Tentacles run with your account's access; resource limits do not protect your files or network.\n\nTentacle management changes take effect immediately.", label, entry.Name, entry.Version, entry.Repository, permissions)
|
||||
}
|
||||
|
||||
func tentacleUpdateConfirmation(entry tentacle.Entry, update tentacle.AvailableUpdate, manifest tentacle.Manifest) string {
|
||||
permissions := tentacleUpdateCapabilities(entry, manifest) + remotePermissions(manifest.Capabilities)
|
||||
permissions := tentacleUpdateCapabilities(entry, manifest) + remotePermissions(manifest.Capabilities) + automationPermissions(manifest.Capabilities)
|
||||
return fmt.Sprintf("Update %s from version %s to version %s?\n\n%s\n\nOnly update packages from publishers you trust. Tentacles run with your account's access.\n\nChanges take effect immediately.", update.Name, update.InstalledVersion, update.AvailableVersion, permissions)
|
||||
}
|
||||
|
||||
@@ -76,3 +80,10 @@ func remotePermissions(grants []string) string {
|
||||
}
|
||||
return " Requested remote access: " + strings.Join(requested, "; ") + ". Installation does not start a connection or authorize control. Each session requires local approval, and unavailable reader operations remain disabled."
|
||||
}
|
||||
|
||||
func automationPermissions(grants []string) string {
|
||||
if slices.Contains(grants, "automation") {
|
||||
return " It can also control the mouse and OCR in a declared foreground application when invoked."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -66,3 +66,17 @@ func TestRemoteGrantConfirmationExplainsDirectionAndConsent(t *testing.T) {
|
||||
t.Fatal("existing grants hidden")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationPermissionIsDisclosedSeparately(t *testing.T) {
|
||||
for _, granted := range []bool{false, true} {
|
||||
manifest := tentacle.Manifest{Capabilities: []string{"presentation", "interaction"}}
|
||||
if granted {
|
||||
manifest.Capabilities = append(manifest.Capabilities, "automation")
|
||||
}
|
||||
for _, message := range []string{tentacleInstallConfirmation(tentacle.Entry{}, manifest, "Install"), tentacleUpdateConfirmation(tentacle.Entry{}, tentacle.AvailableUpdate{}, manifest)} {
|
||||
if strings.Contains(message, "control the mouse and OCR") != granted {
|
||||
t.Fatal("automation permission described incorrectly", message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package tentacle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplicationSDKPeer(t *testing.T) {
|
||||
mode := os.Getenv("CTHULHU_PRIVATE_APPLICATION_PEER")
|
||||
if mode == "" {
|
||||
return
|
||||
}
|
||||
automatic := mode != "scope"
|
||||
command := sdk.Command{ID: "probe", Title: "Application probe", Application: "Example App", Automation: automatic, Presentation: automatic, Interaction: automatic,
|
||||
Handle: func(context.Context, json.RawMessage) (any, error) {
|
||||
if !automatic {
|
||||
return "scoped", nil
|
||||
}
|
||||
return sdk.Interaction{Automation: &sdk.Automation{Actions: []sdk.AutomationAction{{Kind: "move", X: 5000, Y: 5000}}}, Done: true}, nil
|
||||
}}
|
||||
client := sdk.NewSessionClient()
|
||||
if err := sdk.ServeSession(os.Stdin, os.Stdout, []sdk.Command{command}, nil, client); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func TestApplicationSDKHostConformance(t *testing.T) {
|
||||
for _, language := range []string{"go", "python"} {
|
||||
for _, mode := range []string{"scope", "automation", "denied"} {
|
||||
t.Run(language+"/"+mode, func(t *testing.T) {
|
||||
t.Setenv("CTHULHU_PRIVATE_APPLICATION_PEER", mode)
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program := []string{executable, "-test.run=^TestApplicationSDKPeer$"}
|
||||
if language == "python" {
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
source, err := filepath.Abs("testdata/sdk_application_peer.py")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
program = []string{python, "-B", source}
|
||||
}
|
||||
manager := testManager(t, DefaultLimits(), nil)
|
||||
spec := Spec{ID: "probe", Program: program, SessionEvents: true, ApplicationBindings: true}
|
||||
if mode != "scope" {
|
||||
spec.Presentation = true
|
||||
spec.Interaction = true
|
||||
spec.Automation = mode == "automation"
|
||||
}
|
||||
session, err := manager.Start(t.Context(), spec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitSignal(t, session.Ready())
|
||||
state, failure := session.Status()
|
||||
if mode == "denied" {
|
||||
if state != Failed {
|
||||
t.Fatalf("ungranted extension became %s", state)
|
||||
}
|
||||
return
|
||||
}
|
||||
if state != Ready || failure != nil {
|
||||
t.Fatalf("%s: %v", state, failure)
|
||||
}
|
||||
if err := session.Activate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := session.Invoke(t.Context(), "probe", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := waitResult(t, pending)
|
||||
if result.Err != nil {
|
||||
t.Fatal(result.Err)
|
||||
}
|
||||
if mode == "scope" {
|
||||
if string(result.Value) != `"scoped"` {
|
||||
t.Fatal(string(result.Value))
|
||||
}
|
||||
return
|
||||
}
|
||||
var value sdk.Interaction
|
||||
if err := json.Unmarshal(result.Value, &value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if value.Automation == nil || len(value.Automation.Actions) != 1 {
|
||||
t.Fatal(string(result.Value))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package tentacle
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplicationCommandRegistration(t *testing.T) {
|
||||
var registration Registration
|
||||
raw := `{"protocol":{"major":1,"minor":1},"session":"test","commands":[{"id":"click","title":"Click","application":"ck3","presentation":true,"interaction":true,"bindings":[{"layout":"desktop","scope":"global","key":"Ctrl+D"}]}]}`
|
||||
if err := decodeStrict([]byte(raw), ®istration); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := validateRegistrationVersion(registration, "test", Version{Major: 1, Minor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := json.Marshal(registration)
|
||||
if string(data) == "" {
|
||||
t.Fatal("empty registration")
|
||||
}
|
||||
for _, app := range []string{"ck3\n", string([]byte{0xff})} {
|
||||
registration.Commands[0].Application = app
|
||||
if validateRegistrationVersion(registration, "test", Version{Major: 1, Minor: 1}) == nil {
|
||||
t.Errorf("accepted application %q", app)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationBindingStatusesUseApplicationScope(t *testing.T) {
|
||||
manager, err := NewManager(DefaultLimits(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
commands := []Command{{ID: "center", Application: "ck3", Bindings: []Binding{{Layout: "desktop", Scope: "global", Key: "Shift+1"}}}}
|
||||
statuses := resolveBindings("ck3", commands, manager.occupiedBindings(), manager.occupiedBindings(true))
|
||||
if len(statuses) != 1 || !statuses[0].Bound {
|
||||
t.Fatalf("browser default blocked application: %+v", statuses)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationAndAutomationGrantsAreIndependent(t *testing.T) {
|
||||
scoped := Command{ID: "scoped", Title: "Scoped", Application: "example"}
|
||||
spec := Spec{ID: "test", Program: []string{"/bin/true"}, SessionEvents: true, ApplicationBindings: true}
|
||||
if err := validateCommandAccess(scoped, spec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := scoped
|
||||
command.Automation = true
|
||||
command.Presentation = true
|
||||
command.Interaction = true
|
||||
spec.Presentation = true
|
||||
spec.Interaction = true
|
||||
if validateCommandAccess(command, spec) == nil {
|
||||
t.Fatal("interaction grant authorized automation")
|
||||
}
|
||||
spec.Automation = true
|
||||
if err := validateCommandAccess(command, spec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec.SessionEvents = false
|
||||
if validateSpec(spec) == nil {
|
||||
t.Fatal("extensions allowed without negotiation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationAutomationRegistryRoundTrip(t *testing.T) {
|
||||
registry := &Registry{Path: filepath.Join(t.TempDir(), "tentacles.toml")}
|
||||
if _, err := registry.Load(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := Entry{ID: "extension", Program: []string{"/bin/true"}, SessionEvents: true, ApplicationBindings: true, Automation: true, Presentation: true, Interaction: true}
|
||||
if err := registry.Save([]Entry{entry}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := (&Registry{Path: registry.Path}).Load()
|
||||
if err != nil || len(loaded) != 1 {
|
||||
t.Fatal(loaded, err)
|
||||
}
|
||||
if !loaded[0].Spec().Automation || !loaded[0].Spec().ApplicationBindings {
|
||||
t.Fatal("extension opt-ins lost on restart")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationDeclarationRequiresNegotiation(t *testing.T) {
|
||||
command := Command{ID: "probe", Title: "Scoped", Application: "Example App"}
|
||||
spec := Spec{ID: "probe", Program: []string{"/bin/true"}, SessionEvents: true}
|
||||
if validateCommandAccess(command, spec) == nil {
|
||||
t.Fatal("undeclared application API accepted")
|
||||
}
|
||||
spec.ApplicationBindings = true
|
||||
if err := validateCommandAccess(command, spec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec.SessionEvents = false
|
||||
if validateSpec(spec) == nil {
|
||||
t.Fatal("application API accepted in legacy protocol")
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,13 @@ func (session *Session) Bindings() []BindingStatus {
|
||||
|
||||
// Caller holds manager.mutex, but no session lock. Revoked sessions immediately
|
||||
// stop reserving chords even while their processes are still shutting down.
|
||||
func (manager *Manager) occupiedBindings() map[input.KeyboardLayout]input.CommandBindings {
|
||||
func (manager *Manager) occupiedBindings(application ...bool) map[input.KeyboardLayout]input.CommandBindings {
|
||||
occupied := make(map[input.KeyboardLayout]input.CommandBindings)
|
||||
for layout, bindings := range manager.coreBindings {
|
||||
core := manager.coreBindings
|
||||
if len(application) > 0 && application[0] {
|
||||
core = manager.coreApplicationBindings
|
||||
}
|
||||
for layout, bindings := range core {
|
||||
occupied[layout] = make(input.CommandBindings)
|
||||
for chord, command := range bindings {
|
||||
occupied[layout][chord] = command
|
||||
@@ -69,18 +73,25 @@ func (manager *Manager) occupiedBindings() map[input.KeyboardLayout]input.Comman
|
||||
return occupied
|
||||
}
|
||||
|
||||
func resolveBindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings) []BindingStatus {
|
||||
func resolveBindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings, applicationOccupied ...map[input.KeyboardLayout]input.CommandBindings) []BindingStatus {
|
||||
var result []BindingStatus
|
||||
for _, command := range commands {
|
||||
commandID := "tentacle/" + identity + "/" + command.ID
|
||||
for _, binding := range command.Bindings {
|
||||
chord, _ := input.ParseCommandChord(binding.Key)
|
||||
bindings := occupied[bindingLayout(binding.Layout)]
|
||||
if command.Application != "" && len(applicationOccupied) > 0 {
|
||||
bindings = applicationOccupied[0][bindingLayout(binding.Layout)]
|
||||
}
|
||||
previous := bindings[chord]
|
||||
result = append(result, BindingStatus{Command: commandID, Suggested: binding,
|
||||
Bound: previous == "", Conflict: string(previous)})
|
||||
if previous == "" {
|
||||
bindings[chord] = input.Command(commandID)
|
||||
occupied[bindingLayout(binding.Layout)][chord] = input.Command(commandID)
|
||||
if len(applicationOccupied) > 0 {
|
||||
applicationOccupied[0][bindingLayout(binding.Layout)][chord] = input.Command(commandID)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func preparePackage(ctx context.Context, root string, repository Repository, loc
|
||||
remoteGrants = append(remoteGrants, grant)
|
||||
}
|
||||
}
|
||||
prepared.Entry = Entry{SessionEvents: packageManifest.Protocol.Minor == 1, RemoteGrants: remoteGrants, ID: PackageID(repository, localID), LocalID: localID, Name: manifest.Name, Version: manifest.Version,
|
||||
prepared.Entry = Entry{ApplicationBindings: slices.Contains(packageManifest.APIs, "application-bindings"), Automation: slices.Contains(packageManifest.Capabilities, "automation"), SessionEvents: packageManifest.Protocol.Minor == 1, RemoteGrants: remoteGrants, ID: PackageID(repository, localID), LocalID: localID, Name: manifest.Name, Version: manifest.Version,
|
||||
Program: program, Directory: final, Presentation: presentation, Interaction: interactive, ReaderSettings: readerSettings, Repository: repository.URL, RepositoryID: repository.ID,
|
||||
RepositoryRevision: repository.Revision, PackageDirectory: final, PackageSHA256: release.SHA256}
|
||||
if err := ValidateEntries([]Entry{prepared.Entry}); err != nil {
|
||||
|
||||
@@ -500,3 +500,41 @@ func TestSessionPackageGrantsPersistAndRejectMismatch(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationAutomationPackagePermission(t *testing.T) {
|
||||
binary, err := os.ReadFile("/bin/true")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, granted := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(granted), func(t *testing.T) {
|
||||
capabilities := []string{"presentation", "interaction"}
|
||||
text := "'presentation','interaction'"
|
||||
if granted {
|
||||
capabilities = append(capabilities, "automation")
|
||||
text += ",'automation'"
|
||||
}
|
||||
manifest := strings.Replace(packageManifest(), "minor=0", "minor=1", 1)
|
||||
manifest = strings.Replace(manifest, "apis=['commands','presentation']", "apis=['commands','session-events','presentation','interaction','application-bindings','automation']", 1)
|
||||
manifest = strings.Replace(manifest, "capabilities=['presentation']", "capabilities=["+text+"]", 1)
|
||||
data := packageArchive(t, []archiveMember{{name: "tentacle.toml", data: []byte(manifest), mode: 0644}, {name: "bin/echo", data: binary, mode: 0755}})
|
||||
repository, client := packageFixture(t, data)
|
||||
repository.Tentacles[0].Capabilities = capabilities
|
||||
prepared, err := preparePackage(t.Context(), t.TempDir(), repository, "echo", client)
|
||||
if !granted {
|
||||
if err == nil {
|
||||
prepared.Discard()
|
||||
t.Fatal("automation installed without grant")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer prepared.Discard()
|
||||
if !prepared.Entry.Spec().Automation || !prepared.Entry.Spec().ApplicationBindings {
|
||||
t.Fatal("package grants not propagated")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,8 @@ func DefaultLimits() Limits {
|
||||
// Spec is a validated launch description, independent of package metadata.
|
||||
// Program[0] must be absolute; arguments are never interpreted by a shell.
|
||||
type Spec struct {
|
||||
ApplicationBindings bool // Opt-in application-scoped command declarations.
|
||||
Automation bool // Explicit local mouse/OCR automation grant.
|
||||
SessionEvents bool // Opt in to protocol 1.1 lifecycle calls and events.
|
||||
RemoteGrants []string // Install grants only; do not authorize desktop access.
|
||||
ID string
|
||||
@@ -62,6 +64,7 @@ type Manager struct {
|
||||
pending chan struct{}
|
||||
closed bool
|
||||
coreBindings map[input.KeyboardLayout]input.CommandBindings
|
||||
coreApplicationBindings map[input.KeyboardLayout]input.CommandBindings
|
||||
containment *containment
|
||||
supervisorProgram []string
|
||||
cleanupError error
|
||||
@@ -106,14 +109,16 @@ func NewManager(limits Limits, overrides []input.BindingOverride) (*Manager, err
|
||||
return nil, err
|
||||
}
|
||||
coreBindings := make(map[input.KeyboardLayout]input.CommandBindings)
|
||||
coreApplicationBindings := make(map[input.KeyboardLayout]input.CommandBindings)
|
||||
for _, layout := range []input.KeyboardLayout{input.DesktopKeyboardLayout, input.LaptopKeyboardLayout} {
|
||||
bindings, err := input.ResolveCommandBindings(layout, true, overrides)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
coreBindings[layout] = bindings
|
||||
coreApplicationBindings[layout] = input.ApplicationOccupiedBindings(layout, overrides)
|
||||
}
|
||||
return &Manager{limits: limits, sessions: make(map[string]*Session), coreBindings: coreBindings,
|
||||
return &Manager{limits: limits, sessions: make(map[string]*Session), coreBindings: coreBindings, coreApplicationBindings: coreApplicationBindings,
|
||||
starting: make(chan struct{}, limits.Starting), pending: make(chan struct{}, limits.PendingTotal)}, nil
|
||||
}
|
||||
|
||||
@@ -209,6 +214,9 @@ func (manager *Manager) Shutdown(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func validateSpec(spec Spec) error {
|
||||
if (spec.ApplicationBindings || spec.Automation) && !spec.SessionEvents || spec.Automation && (!spec.ApplicationBindings || !spec.Interaction) {
|
||||
return errors.New("invalid application extension grants")
|
||||
}
|
||||
if !tentaclewire.ValidRemoteGrants(spec.RemoteGrants) || len(spec.RemoteGrants) > 0 && !spec.SessionEvents {
|
||||
return errors.New("invalid remote grants")
|
||||
}
|
||||
|
||||
@@ -15,6 +15,12 @@ func (spec Spec) apis(legacy []string) []string {
|
||||
if spec.SessionEvents {
|
||||
apis = append(apis, "session-events")
|
||||
}
|
||||
if spec.ApplicationBindings {
|
||||
apis = append(apis, "application-bindings")
|
||||
}
|
||||
if spec.Automation {
|
||||
apis = append(apis, "automation")
|
||||
}
|
||||
if len(spec.RemoteGrants) > 0 {
|
||||
apis = append(apis, "remote-access")
|
||||
}
|
||||
@@ -25,5 +31,18 @@ func (spec Spec) capabilities(legacy []string) []string {
|
||||
if !spec.SessionEvents {
|
||||
return legacy
|
||||
}
|
||||
return append(append([]string{}, legacy[1:]...), spec.RemoteGrants...)
|
||||
grants := append(append([]string{}, legacy[1:]...), spec.RemoteGrants...)
|
||||
if spec.Automation {
|
||||
grants = append(grants, "automation")
|
||||
}
|
||||
return grants
|
||||
}
|
||||
|
||||
func validateCommandAccess(command Command, spec Spec) error {
|
||||
if command.Application != "" && (!spec.SessionEvents || !spec.ApplicationBindings) ||
|
||||
command.Automation && !spec.Automation || command.Reader && !spec.ReaderSettings ||
|
||||
command.Presentation && !spec.Presentation || command.Interaction && (!command.Presentation || !spec.Interaction) {
|
||||
return ErrProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func (session *Session) run() {
|
||||
return
|
||||
}
|
||||
for _, command := range registration.Commands {
|
||||
if command.Reader && !session.spec.ReaderSettings || command.Presentation && !session.spec.Presentation || command.Interaction && (!command.Presentation || !session.spec.Interaction) {
|
||||
if validateCommandAccess(command, session.spec) != nil {
|
||||
session.fail(ErrProtocol)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ type Version struct {
|
||||
}
|
||||
|
||||
type Command struct {
|
||||
Application string `json:"application,omitempty"`
|
||||
Automation bool `json:"automation,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
@@ -156,16 +158,22 @@ func validateRegistrationVersion(registration Registration, session string, vers
|
||||
seen := make(map[string]bool)
|
||||
settings := false
|
||||
for _, command := range registration.Commands {
|
||||
if command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !validId(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" ||
|
||||
if command.Application != "" && !tentaclewire.ValidApplication(command.Application) || command.Automation && (command.Application == "" || !command.Interaction) || command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !validId(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" ||
|
||||
len(command.Title) > 256 || len(command.Description) > 1024 {
|
||||
return ErrProtocol
|
||||
}
|
||||
if command.Application != "" && version.Minor < 1 {
|
||||
return ErrProtocol
|
||||
}
|
||||
seen[command.ID] = true
|
||||
settings = settings || command.Settings
|
||||
if len(command.Bindings) > 4 {
|
||||
return ErrLimit
|
||||
}
|
||||
for _, binding := range command.Bindings {
|
||||
if command.Application != "" && binding.Scope != "global" {
|
||||
return ErrProtocol
|
||||
}
|
||||
if err := validateBinding(binding); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
// Entry records an explicitly added local program or a verified package.
|
||||
// Discovery never adds entries. Enablement is desired state; failures retain it.
|
||||
type Entry struct {
|
||||
ApplicationBindings bool `toml:"application-bindings,omitempty"`
|
||||
Automation bool `toml:"automation,omitempty"`
|
||||
SessionEvents bool `toml:"session-events,omitempty"`
|
||||
RemoteGrants []string `toml:"remote-grants,omitempty"`
|
||||
ID string `toml:"id"`
|
||||
@@ -38,7 +40,7 @@ type Entry struct {
|
||||
}
|
||||
|
||||
func (entry Entry) Spec() Spec {
|
||||
return Spec{SessionEvents: entry.SessionEvents, RemoteGrants: append([]string(nil), entry.RemoteGrants...), ID: entry.ID, Program: append([]string(nil), entry.Program...), Directory: entry.Directory, Presentation: entry.Presentation, Interaction: entry.Interaction, ReaderSettings: entry.ReaderSettings}
|
||||
return Spec{ApplicationBindings: entry.ApplicationBindings, Automation: entry.Automation, SessionEvents: entry.SessionEvents, RemoteGrants: append([]string(nil), entry.RemoteGrants...), ID: entry.ID, Program: append([]string(nil), entry.Program...), Directory: entry.Directory, Presentation: entry.Presentation, Interaction: entry.Interaction, ReaderSettings: entry.ReaderSettings}
|
||||
}
|
||||
|
||||
type registryDocument struct {
|
||||
|
||||
@@ -126,6 +126,7 @@ func (session *Session) Activate() error {
|
||||
session.manager.mutex.Lock()
|
||||
defer session.manager.mutex.Unlock()
|
||||
occupied := session.manager.occupiedBindings()
|
||||
applicationOccupied := session.manager.occupiedBindings(true)
|
||||
session.mutex.Lock()
|
||||
defer session.mutex.Unlock()
|
||||
if session.state != Ready || session.ctx.Err() != nil {
|
||||
@@ -136,7 +137,7 @@ func (session *Session) Activate() error {
|
||||
}{session.identity}) {
|
||||
return ErrBusy
|
||||
}
|
||||
session.bindings = resolveBindings(session.spec.ID, session.commands, occupied)
|
||||
session.bindings = resolveBindings(session.spec.ID, session.commands, occupied, applicationOccupied)
|
||||
session.state = Active
|
||||
session.log("tentacle activated")
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Copyright (c) 2026 Storm Dragon
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Private application-extension conformance peer. Never injects input."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "sdk" / "python"))
|
||||
from cthulhu_tentacle import Command, serve
|
||||
from cthulhu_tentacle.session import SessionClient
|
||||
|
||||
automatic = os.environ["CTHULHU_PRIVATE_APPLICATION_PEER"] != "scope"
|
||||
def handle(_cancelled, _arguments):
|
||||
if not automatic:
|
||||
return "scoped"
|
||||
return {"automation": {"actions": [{"kind": "move", "x": 5000, "y": 5000}]}, "done": True}
|
||||
|
||||
serve([Command("probe", "Application probe", "Application probe", handle,
|
||||
application="Example App", automation=automatic,
|
||||
presentation=automatic, interaction=automatic)], session_client=SessionClient())
|
||||
@@ -0,0 +1,7 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package tentaclewire
|
||||
|
||||
import "git.stormux.org/storm/cthulhu/internal/input"
|
||||
|
||||
func ValidApplication(value string) bool { return input.ValidApplication(value) }
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
package tentaclewire
|
||||
|
||||
// Automation is a bounded sequence for the application owning this command.
|
||||
// Coordinates are ten-thousandths of the foreground client rectangle.
|
||||
type Automation struct {
|
||||
Actions []AutomationAction `json:"actions"`
|
||||
}
|
||||
type AutomationAction struct {
|
||||
Kind string `json:"kind"`
|
||||
X int `json:"x,omitempty"`
|
||||
Y int `json:"y,omitempty"`
|
||||
Button int `json:"button,omitempty"`
|
||||
Modifier string `json:"modifier,omitempty"`
|
||||
Steps int `json:"steps,omitempty"`
|
||||
Milliseconds int `json:"milliseconds,omitempty"`
|
||||
}
|
||||
|
||||
func ValidAutomation(value Automation) bool {
|
||||
if len(value.Actions) == 0 || len(value.Actions) > 16 {
|
||||
return false
|
||||
}
|
||||
delay := 0
|
||||
for index, a := range value.Actions {
|
||||
if a.Kind == "ocr-route" && index != 0 || a.Kind == "ocr-scan" && index != len(value.Actions)-1 {
|
||||
return false
|
||||
}
|
||||
clean := a
|
||||
switch a.Kind {
|
||||
case "move", "drag":
|
||||
if a.Kind == "drag" {
|
||||
if a.Milliseconds < 0 || a.Milliseconds > 1000 {
|
||||
return false
|
||||
}
|
||||
delay += 2 * a.Milliseconds
|
||||
clean.Milliseconds = 0
|
||||
}
|
||||
if a.X < 0 || a.X > 10000 || a.Y < 0 || a.Y > 10000 {
|
||||
return false
|
||||
}
|
||||
clean.X, clean.Y = 0, 0
|
||||
case "click":
|
||||
if a.Button != 1 && a.Button != 3 {
|
||||
return false
|
||||
}
|
||||
if a.Modifier != "" && a.Modifier != "control" && a.Modifier != "shift" {
|
||||
return false
|
||||
}
|
||||
if a.Milliseconds < 0 || a.Milliseconds > 1000 {
|
||||
return false
|
||||
}
|
||||
delay += a.Milliseconds
|
||||
clean.Milliseconds = 0
|
||||
clean.Button, clean.Modifier = 0, ""
|
||||
case "scroll":
|
||||
if a.Steps == 0 || a.Steps < -100 || a.Steps > 100 {
|
||||
return false
|
||||
}
|
||||
if a.Milliseconds < 0 || a.Milliseconds > 1000 {
|
||||
return false
|
||||
}
|
||||
count := a.Steps
|
||||
if count < 0 {
|
||||
count = -count
|
||||
}
|
||||
delay += (count - 1) * a.Milliseconds
|
||||
clean.Milliseconds = 0
|
||||
clean.Steps = 0
|
||||
case "delay":
|
||||
if a.Milliseconds < 1 || a.Milliseconds > 1000 {
|
||||
return false
|
||||
}
|
||||
delay += a.Milliseconds
|
||||
clean.Milliseconds = 0
|
||||
case "ocr-route", "ocr-dismiss", "ocr-scan", "tone":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
clean.Kind = ""
|
||||
if clean != (AutomationAction{}) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return delay <= 2000
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package tentaclewire
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAutomationInteraction(t *testing.T) {
|
||||
good := `{"automation":{"actions":[{"kind":"move","x":5000,"y":5000},{"kind":"click","button":3,"modifier":"shift"},{"kind":"ocr-dismiss"},{"kind":"ocr-scan"}]},"done":true}`
|
||||
if _, err := DecodeInteraction([]byte(good)); err != nil {
|
||||
t.Fatalf("valid automation rejected: %v", err)
|
||||
}
|
||||
for _, raw := range []string{
|
||||
`{"automation":{"actions":[]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"ocr-scan"},{"kind":"move"}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"move"},{"kind":"ocr-route"}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"key","button":1}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"move","x":10001}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"click","button":2}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"delay","milliseconds":5001}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"ocr-scan","modifier":"shift"}]},"done":true}`,
|
||||
`{"automation":{"actions":[{"kind":"ocr-scan"}]},"next":"other"}`,
|
||||
`{"automation":{"actions":[{"kind":"ocr-scan"}]},"done":true,"source":"focus","next":"other"}`,
|
||||
} {
|
||||
if _, err := DecodeInteraction([]byte(raw)); err == nil {
|
||||
t.Errorf("accepted %s", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationNegotiatesSeparatePermission(t *testing.T) {
|
||||
base := []string{"commands", "session-events", "presentation", "interaction", "application-bindings"}
|
||||
grants := []string{"presentation", "interaction"}
|
||||
if !ValidNegotiation(1, base, grants) {
|
||||
t.Fatal("application bindings should not imply automation permission")
|
||||
}
|
||||
apis := append(append([]string{}, base...), "automation")
|
||||
if ValidNegotiation(1, apis, grants) {
|
||||
t.Fatal("automation API accepted without automation grant")
|
||||
}
|
||||
if !ValidNegotiation(1, apis, append(grants, "automation")) {
|
||||
t.Fatal("explicit automation permission rejected")
|
||||
}
|
||||
if ValidNegotiation(0, apis, append(grants, "automation")) {
|
||||
t.Fatal("legacy protocol accepted extensions")
|
||||
}
|
||||
if ValidNegotiation(1, []string{"commands", "session-events", "automation"}, []string{"automation"}) {
|
||||
t.Fatal("automation accepted without scope and interaction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomationTimingsAreExplicitAndBounded(t *testing.T) {
|
||||
for _, a := range []AutomationAction{{Kind: "click", Button: 1, Milliseconds: 20}, {Kind: "drag", X: 5000, Y: 5000, Milliseconds: 150}} {
|
||||
if !ValidAutomation(Automation{Actions: []AutomationAction{a}}) {
|
||||
t.Fatalf("explicit timing rejected: %+v", a)
|
||||
}
|
||||
}
|
||||
if ValidAutomation(Automation{Actions: []AutomationAction{{Kind: "drag", Milliseconds: 1001}}}) {
|
||||
t.Fatal("unbounded drag timing")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
// A polling reply may announce a changed status, replace the form, request
|
||||
// reader-owned consent, or finish with a verified background lease.
|
||||
type Interaction struct {
|
||||
Automation *Automation `json:"automation,omitempty"`
|
||||
Presentation
|
||||
Form *Form `json:"form,omitempty"`
|
||||
Next string `json:"next,omitempty"`
|
||||
@@ -84,7 +85,11 @@ func DecodeInteraction(data []byte) (Interaction, error) {
|
||||
if value.Source != "" && value.Source != "focus" && value.Source != "clipboard" {
|
||||
return value, ErrProtocol
|
||||
}
|
||||
if value.RemoteBackground != nil {
|
||||
if value.Automation != nil {
|
||||
if !ValidAutomation(*value.Automation) || !value.Done || value.Next != "" || value.Poll != "" || value.Form != nil || value.Source != "" || value.Clipboard != nil || value.Reader != nil || value.Remote != nil || value.RemoteBackground != nil || value.Uninterruptible {
|
||||
return value, ErrProtocol
|
||||
}
|
||||
} else if value.RemoteBackground != nil {
|
||||
if len(value.RemoteBackground.Lease) != 32 || value.RemoteBackground.Epoch == 0 || !value.Done || value.Next != "" || value.Poll != "" || value.Form != nil || value.Source != "" || value.Clipboard != nil || value.Reader != nil || value.Remote != nil || value.Uninterruptible {
|
||||
return value, ErrProtocol
|
||||
}
|
||||
|
||||
@@ -37,13 +37,13 @@ func ValidNegotiation(minor int, apis, capabilities []string) bool {
|
||||
}
|
||||
a, c := map[string]bool{}, map[string]bool{}
|
||||
for _, api := range apis {
|
||||
if a[api] || !slices.Contains([]string{"commands", "presentation", "interaction", "reader-settings", "session-events", "remote-access"}, api) {
|
||||
if a[api] || !slices.Contains([]string{"commands", "presentation", "interaction", "reader-settings", "session-events", "remote-access", "application-bindings", "automation"}, api) {
|
||||
return false
|
||||
}
|
||||
a[api] = true
|
||||
}
|
||||
for _, capability := range capabilities {
|
||||
if c[capability] || !(slices.Contains(RemoteGrants(), capability) || slices.Contains([]string{"presentation", "interaction", "reader-settings"}, capability)) {
|
||||
if c[capability] || !(slices.Contains(RemoteGrants(), capability) || slices.Contains([]string{"presentation", "interaction", "reader-settings", "automation"}, capability)) {
|
||||
return false
|
||||
}
|
||||
c[capability] = true
|
||||
@@ -51,11 +51,14 @@ func ValidNegotiation(minor int, apis, capabilities []string) bool {
|
||||
if !a["commands"] || !a["session-events"] || a["interaction"] && !a["presentation"] || a["reader-settings"] && !a["interaction"] {
|
||||
return false
|
||||
}
|
||||
for _, api := range []string{"presentation", "interaction", "reader-settings"} {
|
||||
for _, api := range []string{"presentation", "interaction", "reader-settings", "automation"} {
|
||||
if a[api] != c[api] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if a["automation"] && (!a["application-bindings"] || !a["interaction"]) {
|
||||
return false
|
||||
}
|
||||
hasRemote := false
|
||||
for _, grant := range RemoteGrants() {
|
||||
hasRemote = hasRemote || c[grant]
|
||||
|
||||
@@ -43,6 +43,10 @@ type VoiceFamily = config.VoiceFamily
|
||||
type Presentation = tentaclewire.Presentation
|
||||
|
||||
// Interaction requires the explicit interaction grant as well as presentation.
|
||||
func ValidApplication(value string) bool { return tentaclewire.ValidApplication(value) }
|
||||
|
||||
type Automation = tentaclewire.Automation
|
||||
type AutomationAction = tentaclewire.AutomationAction
|
||||
type Interaction = tentaclewire.Interaction
|
||||
type Submission = tentaclewire.Submission
|
||||
type Item = tentaclewire.Item
|
||||
@@ -67,6 +71,8 @@ const (
|
||||
type Handler func(ctx context.Context, arguments json.RawMessage) (any, error)
|
||||
|
||||
type Command struct {
|
||||
Application string `json:"application,omitempty"`
|
||||
Automation bool `json:"automation,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
@@ -143,7 +149,7 @@ func serve(input io.ReadCloser, output io.WriteCloser, commands []Command, exten
|
||||
}
|
||||
settings := false
|
||||
for _, command := range commands {
|
||||
if command.Reader && !command.Interaction || command.Settings && (!command.Interaction || !command.Presentation || settings) || command.ID == "" || command.Handle == nil || handlers[command.ID] != nil {
|
||||
if command.Application != "" && !tentaclewire.ValidApplication(command.Application) || command.Automation && (command.Application == "" || !command.Interaction) || command.Reader && !command.Interaction || command.Settings && (!command.Interaction || !command.Presentation || settings) || command.ID == "" || command.Handle == nil || handlers[command.ID] != nil {
|
||||
return ErrProtocol
|
||||
}
|
||||
settings = settings || command.Settings
|
||||
@@ -243,7 +249,7 @@ func serve(input io.ReadCloser, output io.WriteCloser, commands []Command, exten
|
||||
return ErrProtocol
|
||||
}
|
||||
for _, command := range commands {
|
||||
if command.Presentation && !slices.Contains(params.APIs, "presentation") || command.Interaction && (!command.Presentation || !slices.Contains(params.APIs, "interaction")) || command.Reader && !slices.Contains(params.APIs, "reader-settings") {
|
||||
if command.Application != "" && !slices.Contains(params.APIs, "application-bindings") || command.Automation && (!slices.Contains(params.APIs, "automation") || !slices.Contains(params.Capabilities, "automation")) || command.Presentation && !slices.Contains(params.APIs, "presentation") || command.Interaction && (!command.Presentation || !slices.Contains(params.APIs, "interaction")) || command.Reader && !slices.Contains(params.APIs, "reader-settings") {
|
||||
return ErrProtocol
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,15 +49,19 @@ class Command:
|
||||
interaction: bool = False
|
||||
settings: bool = False
|
||||
reader: bool = False
|
||||
application: str = ""
|
||||
automation: bool = False
|
||||
|
||||
def declaration(self):
|
||||
declaration = {"id": self.id, "title": self.title, "description": self.description,
|
||||
"bindings": self.bindings}
|
||||
if self.presentation:
|
||||
declaration["presentation"] = True
|
||||
for name in ("interaction", "settings", "reader"):
|
||||
for name in ("interaction", "settings", "reader", "automation"):
|
||||
if getattr(self, name):
|
||||
declaration[name] = True
|
||||
if self.application:
|
||||
declaration["application"] = self.application
|
||||
return declaration
|
||||
|
||||
|
||||
@@ -184,7 +188,8 @@ def serve(commands, inputStream=None, outputStream=None, extensions=None, sessio
|
||||
if (sum(command.settings for command in commands) > 1
|
||||
or any(command.interaction and not command.presentation
|
||||
or command.settings and not command.interaction
|
||||
or command.reader and not command.interaction for command in commands)):
|
||||
or command.reader and not command.interaction
|
||||
or command.automation and (not command.application or not command.interaction) for command in commands)):
|
||||
raise ProtocolError("Invalid command capabilities")
|
||||
session, active, sequence = None, False, 0
|
||||
while not cancelled.is_set():
|
||||
@@ -231,6 +236,8 @@ def serve(commands, inputStream=None, outputStream=None, extensions=None, sessio
|
||||
or not isinstance(params["session"], str) or not params["session"]
|
||||
or len(params["session"].encode("utf-8")) > 128
|
||||
or not valid_apis
|
||||
or (any(command.application for command in commands) and "application-bindings" not in apis)
|
||||
or (any(command.automation for command in commands) and "automation" not in apis)
|
||||
or (any(command.presentation for command in commands)
|
||||
and "presentation" not in apis)
|
||||
or (any(command.interaction for command in commands) and "interaction" not in apis)
|
||||
|
||||
@@ -11,7 +11,7 @@ from . import MAX_FRAME, ProtocolError, _encode, _fields
|
||||
|
||||
REMOTE_GRANTS = frozenset(("output-observe", "remote-present", "keyboard-capture",
|
||||
"keyboard-inject", "braille-stream", "clipboard-exchange"))
|
||||
BASE_APIS = frozenset(("commands", "presentation", "interaction", "reader-settings"))
|
||||
BASE_APIS = frozenset(("commands", "presentation", "interaction", "reader-settings", "automation"))
|
||||
|
||||
|
||||
def valid_negotiation(apis, capabilities):
|
||||
@@ -21,11 +21,12 @@ def valid_negotiation(apis, capabilities):
|
||||
a, c = set(apis), set(capabilities)
|
||||
return (len(a) == len(apis) and len(c) == len(capabilities)
|
||||
and {"commands", "session-events"} <= a
|
||||
and a <= BASE_APIS | {"session-events", "remote-access"}
|
||||
and a <= BASE_APIS | {"session-events", "remote-access", "application-bindings"}
|
||||
and c <= (BASE_APIS - {"commands"}) | REMOTE_GRANTS
|
||||
and a & (BASE_APIS - {"commands"}) == c & (BASE_APIS - {"commands"})
|
||||
and ("interaction" not in a or "presentation" in a)
|
||||
and ("reader-settings" not in a or "interaction" in a)
|
||||
and ("automation" not in a or {"interaction", "application-bindings"} <= a)
|
||||
and ("remote-access" in a) == bool(c & REMOTE_GRANTS))
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Private X11 client for application matching and mouse tests."""
|
||||
import json
|
||||
import sys
|
||||
from Xlib import X, XK, Xatom, display
|
||||
connection = display.Display()
|
||||
screen = connection.screen()
|
||||
root = screen.root
|
||||
window = root.create_window(20, 20, 240, 140, 0, screen.root_depth,
|
||||
X.InputOutput, X.CopyFromParent,
|
||||
event_mask=X.ButtonPressMask | X.ButtonReleaseMask | X.KeyPressMask | X.KeyReleaseMask)
|
||||
window.set_wm_class("example-app", "example-app")
|
||||
window.map()
|
||||
root.change_property(connection.intern_atom("_NET_ACTIVE_WINDOW"), Xatom.WINDOW, 32, [window.id])
|
||||
window.set_input_focus(X.RevertToParent, X.CurrentTime)
|
||||
connection.sync()
|
||||
print(json.dumps({"window": window.id}), flush=True)
|
||||
for line in sys.stdin:
|
||||
if line.strip() == "focus-other":
|
||||
other = root.create_window(300, 20, 240, 140, 0, screen.root_depth,
|
||||
X.InputOutput, X.CopyFromParent, event_mask=X.KeyPressMask | X.KeyReleaseMask)
|
||||
other.set_wm_class("other", "other")
|
||||
other.map()
|
||||
root.change_property(connection.intern_atom("_NET_ACTIVE_WINDOW"), Xatom.WINDOW, 32, [other.id])
|
||||
other.set_input_focus(X.RevertToParent, X.CurrentTime)
|
||||
connection.sync()
|
||||
print(json.dumps({"focused": other.id}), flush=True)
|
||||
continue
|
||||
if line.strip() == "destroy":
|
||||
window.destroy()
|
||||
root.change_property(connection.intern_atom("_NET_ACTIVE_WINDOW"), Xatom.WINDOW, 32, [0])
|
||||
root.set_input_focus(X.RevertToParent, X.CurrentTime)
|
||||
connection.sync()
|
||||
print(json.dumps({"destroyed": True}), flush=True)
|
||||
continue
|
||||
if line.strip() == "ungrab-client":
|
||||
window.ungrab_key(connection.keysym_to_keycode(XK.string_to_keysym("d")), X.ControlMask)
|
||||
connection.sync()
|
||||
print(json.dumps({"ungrabbed": True}), flush=True)
|
||||
continue
|
||||
if line.strip() in ("grab-root", "grab-client"):
|
||||
target = root if line.strip() == "grab-root" else window
|
||||
target.grab_key(connection.keysym_to_keycode(XK.string_to_keysym("d")), X.ControlMask,
|
||||
False, X.GrabModeAsync, X.GrabModeAsync)
|
||||
connection.sync()
|
||||
print(json.dumps({"grabbed": True}), flush=True)
|
||||
continue
|
||||
if line.strip() == "wait-press":
|
||||
while True:
|
||||
event = connection.next_event()
|
||||
if event.type == X.ButtonPress:
|
||||
print(json.dumps({"pressed": True}), flush=True)
|
||||
break
|
||||
continue
|
||||
if line.strip() in ("other", "example-app"):
|
||||
window.set_wm_class(line.strip(), line.strip())
|
||||
connection.sync()
|
||||
print(json.dumps({"class": line.strip()}), flush=True)
|
||||
continue
|
||||
if line.strip() != "events":
|
||||
break
|
||||
connection.sync()
|
||||
events = []
|
||||
keys = []
|
||||
while connection.pending_events():
|
||||
event = connection.next_event()
|
||||
if event.type in (X.ButtonPress, X.ButtonRelease):
|
||||
events.append({"pressed": event.type == X.ButtonPress, "button": event.detail,
|
||||
"x": event.root_x, "y": event.root_y, "state": event.state})
|
||||
if event.type in (X.KeyPress, X.KeyRelease):
|
||||
keys.append({"symbol": connection.keycode_to_keysym(event.detail, 0), "pressed": event.type == X.KeyPress})
|
||||
pointer = root.query_pointer()
|
||||
print(json.dumps({"events": events, "keys": keys, "mask": pointer.mask, "pointer": [pointer.root_x, pointer.root_y]}), flush=True)
|
||||
connection.close()
|
||||
Reference in new issue
Block a user