More capabilities for tentacles, for an upcoming one
This commit is contained in:
1 parent
ffc5107112
commit
a34d7e70c8
53 files changed
+2744
-131
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user