- go.yaml.in/yaml/v3 v3.0.5 → v3.0.6
- go.yaml.in/yaml/v3 v3.0.5 → v3.0.6 (tools)
#128 build(deps): update 2 dependencies
M .hexcheck.yaml +1 -1
| @@ -84,7 +84,7 @@ heuristics: | |||
| 84 | 84 | ruleSettings: | |
| 85 | 85 | missing-generated-mock-for-port: | |
| 86 | 86 | # Sealed message unions are channel data, not ports; tested by sending messages (ADR 005). | |
| 87 | - | excludePaths: [internal/ports/control.go, internal/ports/client_events.go, internal/ports/client_commands.go, internal/ports/input_events.go, internal/ports/output_events.go, internal/ports/lease.go, internal/ports/session_backend.go] | |
| 87 | + | excludePaths: [internal/ports/client_events.go, internal/ports/client_commands.go, internal/ports/input_events.go, internal/ports/output_events.go, internal/ports/lease.go, internal/ports/session_backend.go] | |
| 88 | 88 | no-adapter-to-adapter-imports: | |
| 89 | 89 | # Composition root wires concrete adapters; Makefile ADAPTER_LIBS governs adapter sharing. | |
| 90 | 90 | excludePaths: [internal/app/**] | |
| @@ -84,7 +84,7 @@ heuristics: | |||||
| 84 | ruleSettings: | 84 | ruleSettings: | ||
| 85 | missing-generated-mock-for-port: | 85 | missing-generated-mock-for-port: | ||
| 86 | # Sealed message unions are channel data, not ports; tested by sending messages (ADR 005). | 86 | # Sealed message unions are channel data, not ports; tested by sending messages (ADR 005). | ||
| 87 | - | excludePaths: [internal/ports/control.go, internal/ports/client_events.go, internal/ports/client_commands.go, internal/ports/input_events.go, internal/ports/output_events.go, internal/ports/lease.go, internal/ports/session_backend.go] | 87 | + | excludePaths: [internal/ports/client_events.go, internal/ports/client_commands.go, internal/ports/input_events.go, internal/ports/output_events.go, internal/ports/lease.go, internal/ports/session_backend.go] |
| 88 | no-adapter-to-adapter-imports: | 88 | no-adapter-to-adapter-imports: | ||
| 89 | # Composition root wires concrete adapters; Makefile ADAPTER_LIBS governs adapter sharing. | 89 | # Composition root wires concrete adapters; Makefile ADAPTER_LIBS governs adapter sharing. | ||
| 90 | excludePaths: [internal/app/**] | 90 | excludePaths: [internal/app/**] | ||
M .mockery.yml +0 -5
| @@ -76,11 +76,6 @@ packages: | |||
| 76 | 76 | filename: seat_control_mock_test.go | |
| 77 | 77 | github.com/bnema/neferwl/internal/adapters/vulkan: | |
| 78 | 78 | interfaces: | |
| 79 | - | copyCompletion: | |
| 80 | - | config: | |
| 81 | - | dir: internal/adapters/vulkan | |
| 82 | - | pkgname: vulkan | |
| 83 | - | filename: copy_completion_mock_test.go | |
| 84 | 79 | captureSync: | |
| 85 | 80 | config: | |
| 86 | 81 | dir: internal/adapters/vulkan | |
| @@ -76,11 +76,6 @@ packages: | |||||
| 76 | filename: seat_control_mock_test.go | 76 | filename: seat_control_mock_test.go | ||
| 77 | github.com/bnema/neferwl/internal/adapters/vulkan: | 77 | github.com/bnema/neferwl/internal/adapters/vulkan: | ||
| 78 | interfaces: | 78 | interfaces: | ||
| 79 | - | copyCompletion: | |||
| 80 | - | config: | |||
| 81 | - | dir: internal/adapters/vulkan | |||
| 82 | - | pkgname: vulkan | |||
| 83 | - | filename: copy_completion_mock_test.go | |||
| 84 | captureSync: | 79 | captureSync: | ||
| 85 | config: | 80 | config: | ||
| 86 | dir: internal/adapters/vulkan | 81 | dir: internal/adapters/vulkan | ||
M AGENTS.md +7 -8
| @@ -40,14 +40,13 @@ Test doubles are always generated by Mockery v3 (`testify` template). Never hand | |||
| 40 | 40 | ||
| 41 | 41 | ## End-to-end tests (headless backend) | |
| 42 | 42 | ||
| 43 | - | Unit tests are not enough for user-facing behavior (binds, gestures, window placement, config keys). Test it end to end on an isolated headless session before declaring it done; see [docs/dev/headless.md](docs/dev/headless.md) and [docs/control.md](docs/control.md). | |
| 44 | - | ||
| 45 | - | - Build the branch binary (`CGO_ENABLED=0 go build -o <tmp>/neferwl ./cmd/neferwl`) and use it for every command. | |
| 46 | - | - Start a session with a throwaway config: `<tmp>/neferwl session new --id test --config <tmp>/config --ttl 60s -- --no-xwayland`. It prints readiness JSON with the session's Wayland display; use that display for external clients. | |
| 47 | - | - Pass `-s test` to every control command so the live desktop stays untouched: `<tmp>/neferwl -s test key Super+s`, `swipe 4 down`, `type <text>`. Wait with `--until` and `--wait` instead of sleeping. | |
| 48 | - | - Check state with `<tmp>/neferwl -s test state` and captures with `<tmp>/neferwl -s test shot`; for a frame sequence, `shot --every-frame`, then `shot --stop`. | |
| 49 | - | - Logs are in `$XDG_STATE_HOME/neferwl/sessions/test/latest.log`, not stderr. | |
| 50 | - | - Stop the session with `<tmp>/neferwl session rm test`. | |
| 43 | + | Unit tests are not enough for user-facing behavior (binds, gestures, window placement, config keys). Test it end to end on the headless backend before declaring it done; see [docs/dev/headless.md](docs/dev/headless.md). | |
| 44 | + | ||
| 45 | + | - Build the branch binary (`CGO_ENABLED=0 go build -o <tmp>/neferwl ./cmd/neferwl`) and run it with a throwaway config: `<tmp>/neferwl --backend=headless --config <tmp>/config --no-xwayland --screenshot <tmp>/shots --input <script> --timeout 10s`. | |
| 46 | + | - Input scripts drive keys and gestures (`key Super+s`, `swipe4 down`, `sleep 1s`); see the table in docs/dev/headless.md. | |
| 47 | + | - Logs go to `$XDG_STATE_HOME/neferwl/runs/headless/latest.log`, not stderr. Read the headless `WAYLAND_DISPLAY` from its `listening` entry. | |
| 48 | + | - Isolate from the user's live session: run the headless compositor, its clients and `neferwl state` with `env -u NEFERWL_STATE -u NEFERWL_SLOT WAYLAND_DISPLAY=<headless>`. `NEFERWL_STATE` wins over `WAYLAND_DISPLAY` and would read the live session's state. | |
| 49 | + | - Check results with `WAYLAND_DISPLAY=<headless> neferwl state` (windows, stash index/count, visibility) and the `latest.png` screenshot. | |
| 51 | 50 | ||
| 52 | 51 | ## Checks before merge | |
| 53 | 52 | ||
| @@ -40,14 +40,13 @@ Test doubles are always generated by Mockery v3 (`testify` template). Never hand | |||||
| 40 | 40 | ||||
| 41 | ## End-to-end tests (headless backend) | 41 | ## End-to-end tests (headless backend) | ||
| 42 | 42 | ||||
| 43 | - | Unit tests are not enough for user-facing behavior (binds, gestures, window placement, config keys). Test it end to end on an isolated headless session before declaring it done; see [docs/dev/headless.md](docs/dev/headless.md) and [docs/control.md](docs/control.md). | 43 | + | Unit tests are not enough for user-facing behavior (binds, gestures, window placement, config keys). Test it end to end on the headless backend before declaring it done; see [docs/dev/headless.md](docs/dev/headless.md). |
| 44 | - | 44 | + | ||
| 45 | - | - Build the branch binary (`CGO_ENABLED=0 go build -o <tmp>/neferwl ./cmd/neferwl`) and use it for every command. | 45 | + | - Build the branch binary (`CGO_ENABLED=0 go build -o <tmp>/neferwl ./cmd/neferwl`) and run it with a throwaway config: `<tmp>/neferwl --backend=headless --config <tmp>/config --no-xwayland --screenshot <tmp>/shots --input <script> --timeout 10s`. |
| 46 | - | - Start a session with a throwaway config: `<tmp>/neferwl session new --id test --config <tmp>/config --ttl 60s -- --no-xwayland`. It prints readiness JSON with the session's Wayland display; use that display for external clients. | 46 | + | - Input scripts drive keys and gestures (`key Super+s`, `swipe4 down`, `sleep 1s`); see the table in docs/dev/headless.md. |
| 47 | - | - Pass `-s test` to every control command so the live desktop stays untouched: `<tmp>/neferwl -s test key Super+s`, `swipe 4 down`, `type <text>`. Wait with `--until` and `--wait` instead of sleeping. | 47 | + | - Logs go to `$XDG_STATE_HOME/neferwl/runs/headless/latest.log`, not stderr. Read the headless `WAYLAND_DISPLAY` from its `listening` entry. |
| 48 | - | - Check state with `<tmp>/neferwl -s test state` and captures with `<tmp>/neferwl -s test shot`; for a frame sequence, `shot --every-frame`, then `shot --stop`. | 48 | + | - Isolate from the user's live session: run the headless compositor, its clients and `neferwl state` with `env -u NEFERWL_STATE -u NEFERWL_SLOT WAYLAND_DISPLAY=<headless>`. `NEFERWL_STATE` wins over `WAYLAND_DISPLAY` and would read the live session's state. |
| 49 | - | - Logs are in `$XDG_STATE_HOME/neferwl/sessions/test/latest.log`, not stderr. | 49 | + | - Check results with `WAYLAND_DISPLAY=<headless> neferwl state` (windows, stash index/count, visibility) and the `latest.png` screenshot. |
| 50 | - | - Stop the session with `<tmp>/neferwl session rm test`. | |||
| 51 | 50 | ||||
| 52 | ## Checks before merge | 51 | ## Checks before merge | ||
| 53 | 52 | ||||
M README.md +1 -46
| @@ -25,8 +25,6 @@ https://github.com/user-attachments/assets/1ff42ce5-47b3-4cf8-a3a7-5fc5abde4af1 | |||
| 25 | 25 | - **Stash:** `cmd+s` toggles a floating strip of windows set aside for the current workspace; `cmd+shift+s` moves a window into or out of it. See [Stash](docs/config.md#stash). | |
| 26 | 26 | - **Hint mode:** click what is on screen by typing its label. Works best in apps like Firefox; see [Hint mode](docs/config.md#hint-mode). | |
| 27 | 27 | - **Animations:** short and cheap; turn them off with `animations = off`. | |
| 28 | - | - **Headless server:** run without a screen on virtual outputs, then stream with Sunshine, watch over VNC or record; see [Headless and server mode](docs/server.md). | |
| 29 | - | - **Agents and scripts:** throwaway sessions that a script or AI agent drives with actions, input, state and screenshots, each command waiting for its result; see [Scripting and agents](docs/control.md). | |
| 30 | 28 | ||
| 31 | 29 | Written in Go, without cgo. Each piece of state has one owner goroutine, connected to the others by channels; hot paths reuse memory and client buffers stay off the Go heap. See [Architecture](docs/dev/architecture.md) for the concurrency model, the GC strategy and the reusable Go libraries. | |
| 32 | 30 | ||
| @@ -176,47 +174,6 @@ Bring your own layer-shell UI, such as Noctalia or Waybar. For capture and idle | |||
| 176 | 174 | ||
| 177 | 175 | Configuration is a flat `key = value` file that reloads on save. A JSON state file exposes outputs, workspaces and windows to scripts; see [Desktop integration](docs/desktop.md). | |
| 178 | 176 | ||
| 179 | - | ### Headless server | |
| 180 | - | ||
| 181 | - | `neferwl --backend=headless --profile=persistent` runs NeferWL on a machine without a screen, on the virtual outputs declared in the config. `neferwl-server.service` runs it as a systemd user service. Apps connect to its Wayland display as usual; Sunshine, OBS and other PipeWire clients stream its outputs through the portal. See [Headless and server mode](docs/server.md) for the setup and a game streaming host with Sunshine. | |
| 182 | - | ||
| 183 | - | ### Agents and automation | |
| 184 | - | ||
| 185 | - | Each headless session has a control socket for scripts and AI agents. Every command waits for its effect and replies with what changed, so no sleeps are needed. A session looks like this: | |
| 186 | - | ||
| 187 | - | 1. Start a throwaway session; it prints its Wayland display and control socket: | |
| 188 | - | ||
| 189 | - | ```sh | |
| 190 | - | neferwl session new --id demo --ttl 10m -- --no-terminal | |
| 191 | - | ``` | |
| 192 | - | ||
| 193 | - | 2. Launch an app and wait for its window: | |
| 194 | - | ||
| 195 | - | ```sh | |
| 196 | - | neferwl -s demo do spawn foot --until 'window-mapped app_id=foot' | |
| 197 | - | ``` | |
| 198 | - | ||
| 199 | - | 3. Act, then wait until the result is on screen and capture it: | |
| 200 | - | ||
| 201 | - | ```sh | |
| 202 | - | neferwl -s demo type 'echo hello' | |
| 203 | - | neferwl -s demo key Return --shot # prints the PNG path | |
| 204 | - | ``` | |
| 205 | - | ||
| 206 | - | 4. Read the state: | |
| 207 | - | ||
| 208 | - | ```sh | |
| 209 | - | neferwl -s demo state | jq '.windows[] | {id, app_id, visible}' | |
| 210 | - | ``` | |
| 211 | - | ||
| 212 | - | 5. Stop the session: | |
| 213 | - | ||
| 214 | - | ```sh | |
| 215 | - | neferwl session rm demo | |
| 216 | - | ``` | |
| 217 | - | ||
| 218 | - | Give an agent the [`skills/neferwl`](skills/neferwl/SKILL.md) skill so it knows the commands. [Scripting and agents](docs/control.md) covers waits, captures, video and security; the wire protocol is in [docs/dev/control.md](docs/dev/control.md). | |
| 219 | - | ||
| 220 | 177 | ## Hardware support | |
| 221 | 178 | ||
| 222 | 179 | NeferWL requires Linux, atomic KMS and a Vulkan 1.3 device that can export images as dmabufs. It reports an error at startup if these requirements are not met. | |
| @@ -235,9 +192,7 @@ Reports from NVIDIA and Intel users are welcome. | |||
| 235 | 192 | - [Desktop integration](docs/desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | |
| 236 | 193 | - [Screen capture](docs/capture.md): protocols, indicator, executable allowlist and portals. | |
| 237 | 194 | - [Performance](docs/performance.md): VRR and real-time priority. | |
| 238 | - | - [Headless and server mode](docs/server.md): profiles, the server service, streaming with Sunshine and remote viewing. | |
| 239 | - | - [Scripting and agents](docs/control.md): sessions, targeting, waits, state, captures and runtime outputs. | |
| 240 | - | - [Developer documentation](docs/dev/index.md): architecture, headless testing, control protocol, profiling and frame stats. | |
| 195 | + | - [Developer documentation](docs/dev/index.md): architecture, headless testing, profiling and frame stats. | |
| 241 | 196 | ||
| 242 | 197 | ## Contributing | |
| 243 | 198 | ||
| @@ -25,8 +25,6 @@ https://github.com/user-attachments/assets/1ff42ce5-47b3-4cf8-a3a7-5fc5abde4af1 | |||||
| 25 | - **Stash:** `cmd+s` toggles a floating strip of windows set aside for the current workspace; `cmd+shift+s` moves a window into or out of it. See [Stash](docs/config.md#stash). | 25 | - **Stash:** `cmd+s` toggles a floating strip of windows set aside for the current workspace; `cmd+shift+s` moves a window into or out of it. See [Stash](docs/config.md#stash). | ||
| 26 | - **Hint mode:** click what is on screen by typing its label. Works best in apps like Firefox; see [Hint mode](docs/config.md#hint-mode). | 26 | - **Hint mode:** click what is on screen by typing its label. Works best in apps like Firefox; see [Hint mode](docs/config.md#hint-mode). | ||
| 27 | - **Animations:** short and cheap; turn them off with `animations = off`. | 27 | - **Animations:** short and cheap; turn them off with `animations = off`. | ||
| 28 | - | - **Headless server:** run without a screen on virtual outputs, then stream with Sunshine, watch over VNC or record; see [Headless and server mode](docs/server.md). | |||
| 29 | - | - **Agents and scripts:** throwaway sessions that a script or AI agent drives with actions, input, state and screenshots, each command waiting for its result; see [Scripting and agents](docs/control.md). | |||
| 30 | 28 | ||||
| 31 | Written in Go, without cgo. Each piece of state has one owner goroutine, connected to the others by channels; hot paths reuse memory and client buffers stay off the Go heap. See [Architecture](docs/dev/architecture.md) for the concurrency model, the GC strategy and the reusable Go libraries. | 29 | Written in Go, without cgo. Each piece of state has one owner goroutine, connected to the others by channels; hot paths reuse memory and client buffers stay off the Go heap. See [Architecture](docs/dev/architecture.md) for the concurrency model, the GC strategy and the reusable Go libraries. | ||
| 32 | 30 | ||||
| @@ -176,47 +174,6 @@ Bring your own layer-shell UI, such as Noctalia or Waybar. For capture and idle | |||||
| 176 | 174 | ||||
| 177 | Configuration is a flat `key = value` file that reloads on save. A JSON state file exposes outputs, workspaces and windows to scripts; see [Desktop integration](docs/desktop.md). | 175 | Configuration is a flat `key = value` file that reloads on save. A JSON state file exposes outputs, workspaces and windows to scripts; see [Desktop integration](docs/desktop.md). | ||
| 178 | 176 | ||||
| 179 | - | ### Headless server | |||
| 180 | - | ||||
| 181 | - | `neferwl --backend=headless --profile=persistent` runs NeferWL on a machine without a screen, on the virtual outputs declared in the config. `neferwl-server.service` runs it as a systemd user service. Apps connect to its Wayland display as usual; Sunshine, OBS and other PipeWire clients stream its outputs through the portal. See [Headless and server mode](docs/server.md) for the setup and a game streaming host with Sunshine. | |||
| 182 | - | ||||
| 183 | - | ### Agents and automation | |||
| 184 | - | ||||
| 185 | - | Each headless session has a control socket for scripts and AI agents. Every command waits for its effect and replies with what changed, so no sleeps are needed. A session looks like this: | |||
| 186 | - | ||||
| 187 | - | 1. Start a throwaway session; it prints its Wayland display and control socket: | |||
| 188 | - | ||||
| 189 | - | ```sh | |||
| 190 | - | neferwl session new --id demo --ttl 10m -- --no-terminal | |||
| 191 | - | ``` | |||
| 192 | - | ||||
| 193 | - | 2. Launch an app and wait for its window: | |||
| 194 | - | ||||
| 195 | - | ```sh | |||
| 196 | - | neferwl -s demo do spawn foot --until 'window-mapped app_id=foot' | |||
| 197 | - | ``` | |||
| 198 | - | ||||
| 199 | - | 3. Act, then wait until the result is on screen and capture it: | |||
| 200 | - | ||||
| 201 | - | ```sh | |||
| 202 | - | neferwl -s demo type 'echo hello' | |||
| 203 | - | neferwl -s demo key Return --shot # prints the PNG path | |||
| 204 | - | ``` | |||
| 205 | - | ||||
| 206 | - | 4. Read the state: | |||
| 207 | - | ||||
| 208 | - | ```sh | |||
| 209 | - | neferwl -s demo state | jq '.windows[] | {id, app_id, visible}' | |||
| 210 | - | ``` | |||
| 211 | - | ||||
| 212 | - | 5. Stop the session: | |||
| 213 | - | ||||
| 214 | - | ```sh | |||
| 215 | - | neferwl session rm demo | |||
| 216 | - | ``` | |||
| 217 | - | ||||
| 218 | - | Give an agent the [`skills/neferwl`](skills/neferwl/SKILL.md) skill so it knows the commands. [Scripting and agents](docs/control.md) covers waits, captures, video and security; the wire protocol is in [docs/dev/control.md](docs/dev/control.md). | |||
| 219 | - | ||||
| 220 | ## Hardware support | 177 | ## Hardware support | ||
| 221 | 178 | ||||
| 222 | NeferWL requires Linux, atomic KMS and a Vulkan 1.3 device that can export images as dmabufs. It reports an error at startup if these requirements are not met. | 179 | NeferWL requires Linux, atomic KMS and a Vulkan 1.3 device that can export images as dmabufs. It reports an error at startup if these requirements are not met. | ||
| @@ -235,9 +192,7 @@ Reports from NVIDIA and Intel users are welcome. | |||||
| 235 | - [Desktop integration](docs/desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | 192 | - [Desktop integration](docs/desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | ||
| 236 | - [Screen capture](docs/capture.md): protocols, indicator, executable allowlist and portals. | 193 | - [Screen capture](docs/capture.md): protocols, indicator, executable allowlist and portals. | ||
| 237 | - [Performance](docs/performance.md): VRR and real-time priority. | 194 | - [Performance](docs/performance.md): VRR and real-time priority. | ||
| 238 | - | - [Headless and server mode](docs/server.md): profiles, the server service, streaming with Sunshine and remote viewing. | 195 | + | - [Developer documentation](docs/dev/index.md): architecture, headless testing, profiling and frame stats. |
| 239 | - | - [Scripting and agents](docs/control.md): sessions, targeting, waits, state, captures and runtime outputs. | |||
| 240 | - | - [Developer documentation](docs/dev/index.md): architecture, headless testing, control protocol, profiling and frame stats. | |||
| 241 | 196 | ||||
| 242 | ## Contributing | 197 | ## Contributing | ||
| 243 | 198 | ||||
M docs/capture.md +2 -2
| @@ -88,7 +88,7 @@ NeferWL serves the GNOME ScreenCast, DisplayConfig, Introspect and Screenshot D- | |||
| 88 | 88 | ||
| 89 | 89 | The packaged `neferwl-portals.conf` routes `ScreenCast` and `Screenshot` to the gnome portal. | |
| 90 | 90 | ||
| 91 | - | The D-Bus interfaces are served on the session bus when NeferWL runs on a hardware session. The persistent [headless profile](server.md#profiles) serves them too; the ephemeral profile only with `--dbus`. Names already owned (by a GNOME session) are skipped. | |
| 91 | + | The D-Bus interfaces are served on the session bus when NeferWL runs on a hardware session. With `--backend=headless`, pass `-dbus` to serve them. Names already owned (by a GNOME session) are skipped. | |
| 92 | 92 | ||
| 93 | 93 | Screenshots through the portal are taken without asking, for any program running as you whose executable is on the allowlist. The indicator still flashes. | |
| 94 | 94 | ||
| @@ -102,4 +102,4 @@ capture = portal | |||
| 102 | 102 | ||
| 103 | 103 | Pick the output in the portal dialog, for example a virtual `tv` with `output.tv.hdr = on`. | |
| 104 | 104 | ||
| 105 | - | To stream from a machine with no display, see [Game streaming with Sunshine](server.md#game-streaming-with-sunshine). | |
| 105 | + | To stream from a machine with no display, run NeferWL in server mode: see [Game server](server.md). | |
| @@ -88,7 +88,7 @@ NeferWL serves the GNOME ScreenCast, DisplayConfig, Introspect and Screenshot D- | |||||
| 88 | 88 | ||||
| 89 | The packaged `neferwl-portals.conf` routes `ScreenCast` and `Screenshot` to the gnome portal. | 89 | The packaged `neferwl-portals.conf` routes `ScreenCast` and `Screenshot` to the gnome portal. | ||
| 90 | 90 | ||||
| 91 | - | The D-Bus interfaces are served on the session bus when NeferWL runs on a hardware session. The persistent [headless profile](server.md#profiles) serves them too; the ephemeral profile only with `--dbus`. Names already owned (by a GNOME session) are skipped. | 91 | + | The D-Bus interfaces are served on the session bus when NeferWL runs on a hardware session. With `--backend=headless`, pass `-dbus` to serve them. Names already owned (by a GNOME session) are skipped. |
| 92 | 92 | ||||
| 93 | Screenshots through the portal are taken without asking, for any program running as you whose executable is on the allowlist. The indicator still flashes. | 93 | Screenshots through the portal are taken without asking, for any program running as you whose executable is on the allowlist. The indicator still flashes. | ||
| 94 | 94 | ||||
| @@ -102,4 +102,4 @@ capture = portal | |||||
| 102 | 102 | ||||
| 103 | Pick the output in the portal dialog, for example a virtual `tv` with `output.tv.hdr = on`. | 103 | Pick the output in the portal dialog, for example a virtual `tv` with `output.tv.hdr = on`. | ||
| 104 | 104 | ||||
| 105 | - | To stream from a machine with no display, see [Game streaming with Sunshine](server.md#game-streaming-with-sunshine). | 105 | + | To stream from a machine with no display, run NeferWL in server mode: see [Game server](server.md). |
D docs/control.md +0 -191
| @@ -1,191 +0,0 @@ | |||
| 1 | - | # Scripting and agents | |
| 2 | - | ||
| 3 | - | Every headless NeferWL session has a control socket. Scripts, tests and AI | |
| 4 | - | agents use it to run actions, inject input, read state and take screenshots, | |
| 5 | - | and each command waits for its result, so no fixed sleeps are needed. Use it on | |
| 6 | - | a throwaway session to test a config or an app away from your desktop, or on | |
| 7 | - | the long-running [server](server.md). The `neferwl` CLI wraps the socket; the | |
| 8 | - | wire protocol is in [docs/dev/control.md](dev/control.md). | |
| 9 | - | ||
| 10 | - | ## Sessions | |
| 11 | - | ||
| 12 | - | A session is one headless compositor with its own Wayland display, control | |
| 13 | - | socket, state and captures. | |
| 14 | - | ||
| 15 | - | ```sh | |
| 16 | - | neferwl session new --id demo --ttl 10m # start a session, print its readiness JSON | |
| 17 | - | neferwl session ls # list live sessions | |
| 18 | - | neferwl session rm demo # stop it | |
| 19 | - | ``` | |
| 20 | - | ||
| 21 | - | `session new` starts the compositor detached and prints one JSON line once it | |
| 22 | - | is ready: | |
| 23 | - | ||
| 24 | - | ```json | |
| 25 | - | {"id":"demo","wayland":"wayland-3","control":"/run/user/1000/neferwl/sessions/demo/control.sock","display":":2"} | |
| 26 | - | ``` | |
| 27 | - | ||
| 28 | - | `display` is the X11 display, empty with `--no-xwayland`. `--env` prints | |
| 29 | - | `NEFERWL_SESSION=` and `WAYLAND_DISPLAY=` lines instead. | |
| 30 | - | ||
| 31 | - | | Flag | Default | Meaning | | |
| 32 | - | |---|---|---| | |
| 33 | - | | `--id ID` | random | Session ID | | |
| 34 | - | | `--profile` | `ephemeral` | `ephemeral` or `persistent`; see [Headless and server mode](server.md#profiles) | | |
| 35 | - | | `--size WxH[,WxH...]` | `1920x1080` (ephemeral) | Output sizes, laid out left to right (`HEADLESS-1`, `HEADLESS-2`, ...) | | |
| 36 | - | | `--config PATH` | XDG default | Config file; use a throwaway one for tests | | |
| 37 | - | | `--ttl DURATION` | none | The session exits after this time | | |
| 38 | - | | `--start-timeout DURATION` | `30s` | Give up if the session is not ready in time | | |
| 39 | - | | `--dbus-session` | off | Keep the parent D-Bus session bus (removed by default) | | |
| 40 | - | | `--env` | off | Print shell assignments instead of JSON | | |
| 41 | - | ||
| 42 | - | Compositor flags go after `--`, for example | |
| 43 | - | `neferwl session new --id demo -- --no-xwayland --no-terminal`. The ephemeral | |
| 44 | - | profile opens the configured terminal at startup unless `--no-terminal` is | |
| 45 | - | given. | |
| 46 | - | ||
| 47 | - | The session does not inherit the caller's `WAYLAND_DISPLAY`, `DISPLAY` or | |
| 48 | - | session targets, so apps it starts never open on your desktop. Logs go to | |
| 49 | - | `$XDG_STATE_HOME/neferwl/sessions/<id>/latest.log`. | |
| 50 | - | ||
| 51 | - | `neferwl-server.service` runs the persistent [server](server.md) as the session | |
| 52 | - | `server`. | |
| 53 | - | ||
| 54 | - | ## Targeting | |
| 55 | - | ||
| 56 | - | Control commands pick their session in this order: | |
| 57 | - | ||
| 58 | - | 1. `-s ID`; | |
| 59 | - | 2. `NEFERWL_SESSION`; | |
| 60 | - | 3. `NEFERWL_CONTROL` (a control socket path); | |
| 61 | - | 4. the session whose Wayland display is `WAYLAND_DISPLAY`. | |
| 62 | - | ||
| 63 | - | Programs started inside a session get `NEFERWL_SESSION`, `NEFERWL_CONTROL` and | |
| 64 | - | `WAYLAND_DISPLAY`, so `neferwl key` run from a session's terminal controls that | |
| 65 | - | session. In scripts, always pass `-s ID`. Without a target, the command fails | |
| 66 | - | and lists live sessions. | |
| 67 | - | ||
| 68 | - | Start your own clients with the session's `wayland` display | |
| 69 | - | (`WAYLAND_DISPLAY=wayland-3 foot &`), or let the compositor start them with | |
| 70 | - | `neferwl -s demo do spawn foot`. | |
| 71 | - | ||
| 72 | - | ## Act, then observe | |
| 73 | - | ||
| 74 | - | Each action or input command waits for its effect, then replies with what | |
| 75 | - | changed: | |
| 76 | - | ||
| 77 | - | ```sh | |
| 78 | - | neferwl -s demo do spawn foot --until 'window-mapped app_id=foot' | |
| 79 | - | ``` | |
| 80 | - | ||
| 81 | - | ```json | |
| 82 | - | {"ok":true,"done":"settled","diff":{"mapped":[2],"focus_from":1,"focus_to":2,"focus_changed":true},...} | |
| 83 | - | ``` | |
| 84 | - | ||
| 85 | - | | Command | Effect | | |
| 86 | - | |---|---| | |
| 87 | - | | `do ACTION [ARG...]` | Run a bind action: `do focus-workspace-next`, `do spawn foot`, `do workspace dev` | | |
| 88 | - | | `key COMBO` | Press and release a combination: `key Super+Return` | | |
| 89 | - | | `type TEXT` | Type text with the session's keymap | | |
| 90 | - | | `press COMBO`, `release COMBO` | Hold or release keys | | |
| 91 | - | | `move X Y` | Move the pointer to global logical coordinates | | |
| 92 | - | | `click [left\|right\|middle]` | Click a button (left by default) | | |
| 93 | - | | `swipe 3\|4 up\|down\|left\|right` | Touchpad swipe | | |
| 94 | - | ||
| 95 | - | Action names are the bind actions of the [configuration](config.md). Compositor | |
| 96 | - | binds such as `Super+o` also work through `key`. These flags go before or after | |
| 97 | - | the arguments: | |
| 98 | - | ||
| 99 | - | | Flag | Default | Meaning | | |
| 100 | - | |---|---|---| | |
| 101 | - | | `--wait LEVEL` | `settled` | `committed`: the action is applied. `settled`: animations are done and windows have committed their new sizes. `presented`: the result is on screen. | | |
| 102 | - | | `--until PREDICATE` | none | Also wait for `window-mapped app_id=APP`, `focused app_id=APP` or `unmapped id=N` | | |
| 103 | - | | `--timeout DURATION` | `10s` | Wait at most this long, up to `5m` | | |
| 104 | - | | `--shot` | off | Capture every output once the result is presented | | |
| 105 | - | ||
| 106 | - | `diff` lists mapped and unmapped window IDs, the focus change and the workspace | |
| 107 | - | now shown on each changed output (`HEADLESS-1:2`). On timeout the command | |
| 108 | - | prints `timeout` and exits with status 1. The reply still carries the partial | |
| 109 | - | diff; the action may have run, so check the state before retrying. | |
| 110 | - | ||
| 111 | - | `--` ends flag parsing for arguments that start with a dash: | |
| 112 | - | `neferwl -s demo move -- -640 0`, `neferwl -s demo type -- -x`. | |
| 113 | - | ||
| 114 | - | There is no sleep or hold command: use the shell between `press` and `release`. | |
| 115 | - | ||
| 116 | - | ## Observe state | |
| 117 | - | ||
| 118 | - | ```sh | |
| 119 | - | neferwl -s demo state # outputs, workspaces, windows, focus | |
| 120 | - | neferwl -s demo state | jq '.windows[] | {id, app_id, workspace, visible}' | |
| 121 | - | neferwl -s demo query state # the same state inside a reply envelope | |
| 122 | - | ``` | |
| 123 | - | ||
| 124 | - | The state has the shape of the desktop [state file](desktop.md#state-for-scripts) | |
| 125 | - | and never contains window titles. | |
| 126 | - | ||
| 127 | - | ## Captures | |
| 128 | - | ||
| 129 | - | ```sh | |
| 130 | - | neferwl -s demo shot # every output | |
| 131 | - | neferwl -s demo shot --output HEADLESS-1 # repeat --output for several | |
| 132 | - | neferwl -s demo shot --inline # also return base64 PNG data | |
| 133 | - | ``` | |
| 134 | - | ||
| 135 | - | A shot waits for the next presented frame and writes one 8-bit sRGB PNG per | |
| 136 | - | output under `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/shots/`. The reply lists | |
| 137 | - | `{output, path, seq}` for each, where `seq` is the presented scene. `--shot` on | |
| 138 | - | an action captures its result in the same round trip. Single shots do not show | |
| 139 | - | the cursor. | |
| 140 | - | ||
| 141 | - | ### Every frame and video | |
| 142 | - | ||
| 143 | - | ```sh | |
| 144 | - | neferwl -s demo shot --every-frame # start writing frames | |
| 145 | - | neferwl -s demo swipe 4 down --wait presented | |
| 146 | - | neferwl -s demo shot --stop # stop and close the index | |
| 147 | - | frames="$XDG_RUNTIME_DIR/neferwl/sessions/demo/shots/frames" | |
| 148 | - | ffmpeg -f concat -safe 0 -i "$frames/frames.ffconcat" -vf "fps=60,format=yuv420p" -c:v libx264 -crf 18 demo.mp4 | |
| 149 | - | ``` | |
| 150 | - | ||
| 151 | - | Continuous capture writes `frame-NNNNNN.png` per presented frame, `latest.png` | |
| 152 | - | (a hard link to the newest frame) and `frames.ffconcat` with the frame timing. | |
| 153 | - | `--dir DIR` selects another directory and `--output NAME` limits capture to | |
| 154 | - | that output. With several outputs, each gets a subdirectory named after it. | |
| 155 | - | The directory grows until `shot --stop`. Starting on an output that is already | |
| 156 | - | recording returns `bad-request`, and an unwritable directory returns | |
| 157 | - | `capture-failed`. If a write fails later, that output stops recording and the | |
| 158 | - | compositor logs a warning. | |
| 159 | - | ||
| 160 | - | On an HDR output, `--every-frame --raw` also writes `latest-pq.png`, the newest | |
| 161 | - | frame in raw PQ. | |
| 162 | - | ||
| 163 | - | ## Runtime outputs | |
| 164 | - | ||
| 165 | - | ```sh | |
| 166 | - | neferwl -s demo output add 1280x720@60 --name side | |
| 167 | - | neferwl -s demo output rm side | |
| 168 | - | ``` | |
| 169 | - | ||
| 170 | - | An added output lasts until `output rm` or the end of the session. The reply | |
| 171 | - | comes once the state lists or drops it. | |
| 172 | - | ||
| 173 | - | ## Security | |
| 174 | - | ||
| 175 | - | - The socket and its directory are private to the user (`0600`, `0700`), and | |
| 176 | - | the compositor checks the peer's uid with `SO_PEERCRED`. Any process of the | |
| 177 | - | same user gets full control, including input and captures; other users are | |
| 178 | - | rejected. | |
| 179 | - | - While the session is locked (`ext-session-lock-v1`), actions, input and | |
| 180 | - | captures are refused with `locked`, and continuous capture writes no frames. | |
| 181 | - | `quit` is still accepted so `session rm` can stop a locked session. Same-uid | |
| 182 | - | access does not bypass the lock. | |
| 183 | - | ||
| 184 | - | ## Limits | |
| 185 | - | ||
| 186 | - | - Only headless sessions have a control socket. On a DRM desktop, use the | |
| 187 | - | [state file](desktop.md#state-for-scripts) and Wayland tools. | |
| 188 | - | - Single shots are 8-bit sRGB; raw PQ is only available with `--every-frame`. | |
| 189 | - | - On a device without sync-file export (software Vulkan such as lavapipe, in | |
| 190 | - | CI or VMs), shots are read back on the CPU: slower, same pixels. | |
| 191 | - | - At most 64 requests wait at once per session; more get `busy`. | |
| @@ -1,191 +0,0 @@ | |||||
| 1 | - | # Scripting and agents | |||
| 2 | - | ||||
| 3 | - | Every headless NeferWL session has a control socket. Scripts, tests and AI | |||
| 4 | - | agents use it to run actions, inject input, read state and take screenshots, | |||
| 5 | - | and each command waits for its result, so no fixed sleeps are needed. Use it on | |||
| 6 | - | a throwaway session to test a config or an app away from your desktop, or on | |||
| 7 | - | the long-running [server](server.md). The `neferwl` CLI wraps the socket; the | |||
| 8 | - | wire protocol is in [docs/dev/control.md](dev/control.md). | |||
| 9 | - | ||||
| 10 | - | ## Sessions | |||
| 11 | - | ||||
| 12 | - | A session is one headless compositor with its own Wayland display, control | |||
| 13 | - | socket, state and captures. | |||
| 14 | - | ||||
| 15 | - | ```sh | |||
| 16 | - | neferwl session new --id demo --ttl 10m # start a session, print its readiness JSON | |||
| 17 | - | neferwl session ls # list live sessions | |||
| 18 | - | neferwl session rm demo # stop it | |||
| 19 | - | ``` | |||
| 20 | - | ||||
| 21 | - | `session new` starts the compositor detached and prints one JSON line once it | |||
| 22 | - | is ready: | |||
| 23 | - | ||||
| 24 | - | ```json | |||
| 25 | - | {"id":"demo","wayland":"wayland-3","control":"/run/user/1000/neferwl/sessions/demo/control.sock","display":":2"} | |||
| 26 | - | ``` | |||
| 27 | - | ||||
| 28 | - | `display` is the X11 display, empty with `--no-xwayland`. `--env` prints | |||
| 29 | - | `NEFERWL_SESSION=` and `WAYLAND_DISPLAY=` lines instead. | |||
| 30 | - | ||||
| 31 | - | | Flag | Default | Meaning | | |||
| 32 | - | |---|---|---| | |||
| 33 | - | | `--id ID` | random | Session ID | | |||
| 34 | - | | `--profile` | `ephemeral` | `ephemeral` or `persistent`; see [Headless and server mode](server.md#profiles) | | |||
| 35 | - | | `--size WxH[,WxH...]` | `1920x1080` (ephemeral) | Output sizes, laid out left to right (`HEADLESS-1`, `HEADLESS-2`, ...) | | |||
| 36 | - | | `--config PATH` | XDG default | Config file; use a throwaway one for tests | | |||
| 37 | - | | `--ttl DURATION` | none | The session exits after this time | | |||
| 38 | - | | `--start-timeout DURATION` | `30s` | Give up if the session is not ready in time | | |||
| 39 | - | | `--dbus-session` | off | Keep the parent D-Bus session bus (removed by default) | | |||
| 40 | - | | `--env` | off | Print shell assignments instead of JSON | | |||
| 41 | - | ||||
| 42 | - | Compositor flags go after `--`, for example | |||
| 43 | - | `neferwl session new --id demo -- --no-xwayland --no-terminal`. The ephemeral | |||
| 44 | - | profile opens the configured terminal at startup unless `--no-terminal` is | |||
| 45 | - | given. | |||
| 46 | - | ||||
| 47 | - | The session does not inherit the caller's `WAYLAND_DISPLAY`, `DISPLAY` or | |||
| 48 | - | session targets, so apps it starts never open on your desktop. Logs go to | |||
| 49 | - | `$XDG_STATE_HOME/neferwl/sessions/<id>/latest.log`. | |||
| 50 | - | ||||
| 51 | - | `neferwl-server.service` runs the persistent [server](server.md) as the session | |||
| 52 | - | `server`. | |||
| 53 | - | ||||
| 54 | - | ## Targeting | |||
| 55 | - | ||||
| 56 | - | Control commands pick their session in this order: | |||
| 57 | - | ||||
| 58 | - | 1. `-s ID`; | |||
| 59 | - | 2. `NEFERWL_SESSION`; | |||
| 60 | - | 3. `NEFERWL_CONTROL` (a control socket path); | |||
| 61 | - | 4. the session whose Wayland display is `WAYLAND_DISPLAY`. | |||
| 62 | - | ||||
| 63 | - | Programs started inside a session get `NEFERWL_SESSION`, `NEFERWL_CONTROL` and | |||
| 64 | - | `WAYLAND_DISPLAY`, so `neferwl key` run from a session's terminal controls that | |||
| 65 | - | session. In scripts, always pass `-s ID`. Without a target, the command fails | |||
| 66 | - | and lists live sessions. | |||
| 67 | - | ||||
| 68 | - | Start your own clients with the session's `wayland` display | |||
| 69 | - | (`WAYLAND_DISPLAY=wayland-3 foot &`), or let the compositor start them with | |||
| 70 | - | `neferwl -s demo do spawn foot`. | |||
| 71 | - | ||||
| 72 | - | ## Act, then observe | |||
| 73 | - | ||||
| 74 | - | Each action or input command waits for its effect, then replies with what | |||
| 75 | - | changed: | |||
| 76 | - | ||||
| 77 | - | ```sh | |||
| 78 | - | neferwl -s demo do spawn foot --until 'window-mapped app_id=foot' | |||
| 79 | - | ``` | |||
| 80 | - | ||||
| 81 | - | ```json | |||
| 82 | - | {"ok":true,"done":"settled","diff":{"mapped":[2],"focus_from":1,"focus_to":2,"focus_changed":true},...} | |||
| 83 | - | ``` | |||
| 84 | - | ||||
| 85 | - | | Command | Effect | | |||
| 86 | - | |---|---| | |||
| 87 | - | | `do ACTION [ARG...]` | Run a bind action: `do focus-workspace-next`, `do spawn foot`, `do workspace dev` | | |||
| 88 | - | | `key COMBO` | Press and release a combination: `key Super+Return` | | |||
| 89 | - | | `type TEXT` | Type text with the session's keymap | | |||
| 90 | - | | `press COMBO`, `release COMBO` | Hold or release keys | | |||
| 91 | - | | `move X Y` | Move the pointer to global logical coordinates | | |||
| 92 | - | | `click [left\|right\|middle]` | Click a button (left by default) | | |||
| 93 | - | | `swipe 3\|4 up\|down\|left\|right` | Touchpad swipe | | |||
| 94 | - | ||||
| 95 | - | Action names are the bind actions of the [configuration](config.md). Compositor | |||
| 96 | - | binds such as `Super+o` also work through `key`. These flags go before or after | |||
| 97 | - | the arguments: | |||
| 98 | - | ||||
| 99 | - | | Flag | Default | Meaning | | |||
| 100 | - | |---|---|---| | |||
| 101 | - | | `--wait LEVEL` | `settled` | `committed`: the action is applied. `settled`: animations are done and windows have committed their new sizes. `presented`: the result is on screen. | | |||
| 102 | - | | `--until PREDICATE` | none | Also wait for `window-mapped app_id=APP`, `focused app_id=APP` or `unmapped id=N` | | |||
| 103 | - | | `--timeout DURATION` | `10s` | Wait at most this long, up to `5m` | | |||
| 104 | - | | `--shot` | off | Capture every output once the result is presented | | |||
| 105 | - | ||||
| 106 | - | `diff` lists mapped and unmapped window IDs, the focus change and the workspace | |||
| 107 | - | now shown on each changed output (`HEADLESS-1:2`). On timeout the command | |||
| 108 | - | prints `timeout` and exits with status 1. The reply still carries the partial | |||
| 109 | - | diff; the action may have run, so check the state before retrying. | |||
| 110 | - | ||||
| 111 | - | `--` ends flag parsing for arguments that start with a dash: | |||
| 112 | - | `neferwl -s demo move -- -640 0`, `neferwl -s demo type -- -x`. | |||
| 113 | - | ||||
| 114 | - | There is no sleep or hold command: use the shell between `press` and `release`. | |||
| 115 | - | ||||
| 116 | - | ## Observe state | |||
| 117 | - | ||||
| 118 | - | ```sh | |||
| 119 | - | neferwl -s demo state # outputs, workspaces, windows, focus | |||
| 120 | - | neferwl -s demo state | jq '.windows[] | {id, app_id, workspace, visible}' | |||
| 121 | - | neferwl -s demo query state # the same state inside a reply envelope | |||
| 122 | - | ``` | |||
| 123 | - | ||||
| 124 | - | The state has the shape of the desktop [state file](desktop.md#state-for-scripts) | |||
| 125 | - | and never contains window titles. | |||
| 126 | - | ||||
| 127 | - | ## Captures | |||
| 128 | - | ||||
| 129 | - | ```sh | |||
| 130 | - | neferwl -s demo shot # every output | |||
| 131 | - | neferwl -s demo shot --output HEADLESS-1 # repeat --output for several | |||
| 132 | - | neferwl -s demo shot --inline # also return base64 PNG data | |||
| 133 | - | ``` | |||
| 134 | - | ||||
| 135 | - | A shot waits for the next presented frame and writes one 8-bit sRGB PNG per | |||
| 136 | - | output under `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/shots/`. The reply lists | |||
| 137 | - | `{output, path, seq}` for each, where `seq` is the presented scene. `--shot` on | |||
| 138 | - | an action captures its result in the same round trip. Single shots do not show | |||
| 139 | - | the cursor. | |||
| 140 | - | ||||
| 141 | - | ### Every frame and video | |||
| 142 | - | ||||
| 143 | - | ```sh | |||
| 144 | - | neferwl -s demo shot --every-frame # start writing frames | |||
| 145 | - | neferwl -s demo swipe 4 down --wait presented | |||
| 146 | - | neferwl -s demo shot --stop # stop and close the index | |||
| 147 | - | frames="$XDG_RUNTIME_DIR/neferwl/sessions/demo/shots/frames" | |||
| 148 | - | ffmpeg -f concat -safe 0 -i "$frames/frames.ffconcat" -vf "fps=60,format=yuv420p" -c:v libx264 -crf 18 demo.mp4 | |||
| 149 | - | ``` | |||
| 150 | - | ||||
| 151 | - | Continuous capture writes `frame-NNNNNN.png` per presented frame, `latest.png` | |||
| 152 | - | (a hard link to the newest frame) and `frames.ffconcat` with the frame timing. | |||
| 153 | - | `--dir DIR` selects another directory and `--output NAME` limits capture to | |||
| 154 | - | that output. With several outputs, each gets a subdirectory named after it. | |||
| 155 | - | The directory grows until `shot --stop`. Starting on an output that is already | |||
| 156 | - | recording returns `bad-request`, and an unwritable directory returns | |||
| 157 | - | `capture-failed`. If a write fails later, that output stops recording and the | |||
| 158 | - | compositor logs a warning. | |||
| 159 | - | ||||
| 160 | - | On an HDR output, `--every-frame --raw` also writes `latest-pq.png`, the newest | |||
| 161 | - | frame in raw PQ. | |||
| 162 | - | ||||
| 163 | - | ## Runtime outputs | |||
| 164 | - | ||||
| 165 | - | ```sh | |||
| 166 | - | neferwl -s demo output add 1280x720@60 --name side | |||
| 167 | - | neferwl -s demo output rm side | |||
| 168 | - | ``` | |||
| 169 | - | ||||
| 170 | - | An added output lasts until `output rm` or the end of the session. The reply | |||
| 171 | - | comes once the state lists or drops it. | |||
| 172 | - | ||||
| 173 | - | ## Security | |||
| 174 | - | ||||
| 175 | - | - The socket and its directory are private to the user (`0600`, `0700`), and | |||
| 176 | - | the compositor checks the peer's uid with `SO_PEERCRED`. Any process of the | |||
| 177 | - | same user gets full control, including input and captures; other users are | |||
| 178 | - | rejected. | |||
| 179 | - | - While the session is locked (`ext-session-lock-v1`), actions, input and | |||
| 180 | - | captures are refused with `locked`, and continuous capture writes no frames. | |||
| 181 | - | `quit` is still accepted so `session rm` can stop a locked session. Same-uid | |||
| 182 | - | access does not bypass the lock. | |||
| 183 | - | ||||
| 184 | - | ## Limits | |||
| 185 | - | ||||
| 186 | - | - Only headless sessions have a control socket. On a DRM desktop, use the | |||
| 187 | - | [state file](desktop.md#state-for-scripts) and Wayland tools. | |||
| 188 | - | - Single shots are 8-bit sRGB; raw PQ is only available with `--every-frame`. | |||
| 189 | - | - On a device without sync-file export (software Vulkan such as lavapipe, in | |||
| 190 | - | CI or VMs), shots are read back on the CPU: slower, same pixels. | |||
| 191 | - | - At most 64 requests wait at once per session; more get `busy`. | |||
M docs/desktop.md +1 -5
| @@ -150,7 +150,7 @@ Workspace IDs are `name:<name>` for named workspaces, stable across launches. Nu | |||
| 150 | 150 | ||
| 151 | 151 | ## State for scripts | |
| 152 | 152 | ||
| 153 | - | NeferWL writes its state as JSON to `$XDG_RUNTIME_DIR/neferwl/<wayland socket>.json` (`$XDG_RUNTIME_DIR/neferwl/sessions/<id>/state.json` for a [headless session](server.md)), also given to started programs as `$NEFERWL_STATE`. It lists outputs, workspaces, the focused window, and every window with its app ID, PID, workspace, column and row, and whether it is floating or the fullscreen window of its workspace (`floating`, `fullscreen`). A fullscreen window keeps `fullscreen` while a stashed window is shown over it and while its workspace is not shown; combine it with `visible` to know what covers an output. | |
| 153 | + | NeferWL writes its state as JSON to `$XDG_RUNTIME_DIR/neferwl/<wayland socket>.json`, also given to started programs as `$NEFERWL_STATE`. It lists outputs, workspaces, the focused window, and every window with its app ID, PID, workspace, column and row, and whether it is floating or the fullscreen window of its workspace (`floating`, `fullscreen`). A fullscreen window keeps `fullscreen` while a stashed window is shown over it and while its workspace is not shown; combine it with `visible` to know what covers an output. | |
| 154 | 154 | ||
| 155 | 155 | Each window also carries metadata keys: | |
| 156 | 156 | ||
| @@ -163,10 +163,6 @@ Each window also carries metadata keys: | |||
| 163 | 163 | ||
| 164 | 164 | The `workspaces` list holds every workspace with its `visible` flag, its columns and the windows in them, each with `x`, `y`, `width` and `height` in logical pixels of its output. A workspace's `cover` is its active fullscreen window, 0 if none; a window's `fullscreen` is also set for the other fullscreen windows it holds, which sit output-sized in their own column or band. The file is written at most once per second. | |
| 165 | 165 | ||
| 166 | - | `neferwl state` prints it. On a headless session it reads the live state over | |
| 167 | - | the [control socket](control.md) (`neferwl -s ID state`); otherwise it reads the | |
| 168 | - | file. | |
| 169 | - | ||
| 170 | 166 | ```sh | |
| 171 | 167 | neferwl state # the whole state | |
| 172 | 168 | neferwl state output-of "$PID" # the output showing that process's window | |
| @@ -150,7 +150,7 @@ Workspace IDs are `name:<name>` for named workspaces, stable across launches. Nu | |||||
| 150 | 150 | ||||
| 151 | ## State for scripts | 151 | ## State for scripts | ||
| 152 | 152 | ||||
| 153 | - | NeferWL writes its state as JSON to `$XDG_RUNTIME_DIR/neferwl/<wayland socket>.json` (`$XDG_RUNTIME_DIR/neferwl/sessions/<id>/state.json` for a [headless session](server.md)), also given to started programs as `$NEFERWL_STATE`. It lists outputs, workspaces, the focused window, and every window with its app ID, PID, workspace, column and row, and whether it is floating or the fullscreen window of its workspace (`floating`, `fullscreen`). A fullscreen window keeps `fullscreen` while a stashed window is shown over it and while its workspace is not shown; combine it with `visible` to know what covers an output. | 153 | + | NeferWL writes its state as JSON to `$XDG_RUNTIME_DIR/neferwl/<wayland socket>.json`, also given to started programs as `$NEFERWL_STATE`. It lists outputs, workspaces, the focused window, and every window with its app ID, PID, workspace, column and row, and whether it is floating or the fullscreen window of its workspace (`floating`, `fullscreen`). A fullscreen window keeps `fullscreen` while a stashed window is shown over it and while its workspace is not shown; combine it with `visible` to know what covers an output. |
| 154 | 154 | ||||
| 155 | Each window also carries metadata keys: | 155 | Each window also carries metadata keys: | ||
| 156 | 156 | ||||
| @@ -163,10 +163,6 @@ Each window also carries metadata keys: | |||||
| 163 | 163 | ||||
| 164 | The `workspaces` list holds every workspace with its `visible` flag, its columns and the windows in them, each with `x`, `y`, `width` and `height` in logical pixels of its output. A workspace's `cover` is its active fullscreen window, 0 if none; a window's `fullscreen` is also set for the other fullscreen windows it holds, which sit output-sized in their own column or band. The file is written at most once per second. | 164 | The `workspaces` list holds every workspace with its `visible` flag, its columns and the windows in them, each with `x`, `y`, `width` and `height` in logical pixels of its output. A workspace's `cover` is its active fullscreen window, 0 if none; a window's `fullscreen` is also set for the other fullscreen windows it holds, which sit output-sized in their own column or band. The file is written at most once per second. | ||
| 165 | 165 | ||||
| 166 | - | `neferwl state` prints it. On a headless session it reads the live state over | |||
| 167 | - | the [control socket](control.md) (`neferwl -s ID state`); otherwise it reads the | |||
| 168 | - | file. | |||
| 169 | - | ||||
| 170 | ```sh | 166 | ```sh | ||
| 171 | neferwl state # the whole state | 167 | neferwl state # the whole state | ||
| 172 | neferwl state output-of "$PID" # the output showing that process's window | 168 | neferwl state output-of "$PID" # the output showing that process's window | ||
D docs/dev/control.md +0 -187
| @@ -1,187 +0,0 @@ | |||
| 1 | - | # Control protocol | |
| 2 | - | ||
| 3 | - | Wire reference for the headless control socket. For sessions, targeting and CLI | |
| 4 | - | usage, see [Scripting and agents](../control.md). | |
| 5 | - | ||
| 6 | - | ## Connection | |
| 7 | - | ||
| 8 | - | Each session listens on `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/control.sock` | |
| 9 | - | (directory `0700`, socket `0600`). The server reads the peer's credentials with | |
| 10 | - | `SO_PEERCRED` and closes connections from another uid. An accepted connection | |
| 11 | - | has every capability: `read`, `act`, `input`, `capture`, `admin`. | |
| 12 | - | ||
| 13 | - | Messages are JSON lines: one object per line, in both directions. A connection | |
| 14 | - | handles one request at a time: the next line is read after the previous reply | |
| 15 | - | is sent. Open several connections for concurrent requests. | |
| 16 | - | ||
| 17 | - | `id` is optional and may be any JSON value; the reply echoes it, or carries | |
| 18 | - | `null` when it is missing or the line is not valid JSON. | |
| 19 | - | ||
| 20 | - | ## Handshake | |
| 21 | - | ||
| 22 | - | ```json | |
| 23 | - | {"id":1,"op":"hello"} | |
| 24 | - | {"id":1,"ok":true,"v":1,"caps":["read","act","input","capture","admin"],"commands":[{"name":"output-add","arg":"MODE","kind":"admin","caps":["admin"],"summary":"Add a runtime virtual output."},...]} | |
| 25 | - | ``` | |
| 26 | - | ||
| 27 | - | `commands` is the catalog: each entry has `name`, `arg`, `kind` (`action`, | |
| 28 | - | `action-arg`, `query`, `inject`, `shot`, `admin`), `caps` and `summary`. Action | |
| 29 | - | names are the bind actions; `do` has no automation-only names. Additive changes | |
| 30 | - | keep `v: 1`; clients ignore unknown fields. | |
| 31 | - | ||
| 32 | - | ## Requests | |
| 33 | - | ||
| 34 | - | | `op` | Fields | Capability | | |
| 35 | - | |---|---|---| | |
| 36 | - | | `do` | `action` (name and arguments, e.g. `"focus-workspace 2"`), wait fields | `act` | | |
| 37 | - | | `inject` | `kind` and its fields (below), wait fields | `input` | | |
| 38 | - | | `query` | `what`: `"state"` | `read` | | |
| 39 | - | | `shot` | `outputs`, `inline`, `raw`, `timeout` | `capture` | | |
| 40 | - | | `shot` (continuous) | `every_frame` or `stop`, `outputs`, `dir`, `raw` | `capture` | | |
| 41 | - | | `output-add` | `mode` (`WxH[@Hz]`), optional `name` | `admin` | | |
| 42 | - | | `output-rm` | `name` | `admin` | | |
| 43 | - | ||
| 44 | - | Wait fields, on `do` and `inject`: | |
| 45 | - | ||
| 46 | - | | Field | Type | Default | Meaning | | |
| 47 | - | |---|---|---|---| | |
| 48 | - | | `wait` | `"committed"`, `"settled"`, `"presented"` | `"settled"` | Completion level | | |
| 49 | - | | `until` | string | none | State predicate | | |
| 50 | - | | `timeout` | Go duration string | `"10s"` | Bound on the wait, at most `5m` | | |
| 51 | - | | `shot` | `true`, `false` or a list of output names | none | Capture after the wait; implies `presented` | | |
| 52 | - | ||
| 53 | - | ### Inject kinds | |
| 54 | - | ||
| 55 | - | | `kind` | Fields | Meaning | | |
| 56 | - | |---|---|---| | |
| 57 | - | | `key` | `combo` | Press and release a combination such as `Super+Return` | | |
| 58 | - | | `type` | `text` | Type text through the session keymap | | |
| 59 | - | | `press`, `release` | `combo` | Press, or release in reverse order | | |
| 60 | - | | `pointer` | `cmd`, `args` | `move` with absolute global logical `x`, `y` strings; `click` (default `left`), `down`, `up` with `left`, `right` or `middle` | | |
| 61 | - | | `swipe` | `fingers` (3 or 4), `dir` | Touchpad swipe `up`, `down`, `left` or `right` | | |
| 62 | - | ||
| 63 | - | ```json | |
| 64 | - | {"id":1,"op":"inject","kind":"key","combo":"Super+Return","until":"window-mapped app_id=foot"} | |
| 65 | - | {"id":2,"op":"inject","kind":"pointer","cmd":"move","args":["320","240"]} | |
| 66 | - | {"id":3,"op":"inject","kind":"swipe","fingers":4,"dir":"down","wait":"presented"} | |
| 67 | - | ``` | |
| 68 | - | ||
| 69 | - | Injected input goes through the core input path, so compositor binds run as | |
| 70 | - | for a physical device. The first injection on a connection announces an input | |
| 71 | - | device with ID `1` named `control` (for `output.<name>.input = control`). | |
| 72 | - | ||
| 73 | - | ## Wait semantics | |
| 74 | - | ||
| 75 | - | - `committed`: the action or input batch has been applied to core state. | |
| 76 | - | - `settled`: animations are finished and every affected window has committed | |
| 77 | - | its configured size. | |
| 78 | - | - `presented`: the resulting scene has been presented on its outputs. | |
| 79 | - | ||
| 80 | - | `until` is checked on top of the level; the reply comes when both hold. | |
| 81 | - | ||
| 82 | - | | Predicate | Holds when | | |
| 83 | - | |---|---| | |
| 84 | - | | `window-mapped app_id=APP` | A window with that app ID mapped after the request | | |
| 85 | - | | `focused app_id=APP` | A window with that app ID has focus | | |
| 86 | - | | `unmapped id=N` | Window `N` is gone | | |
| 87 | - | ||
| 88 | - | `timeout` covers the wait and any capture together. A `timeout` above `5m` is | |
| 89 | - | `bad-request` with `detail: "timeout exceeds 5m"`. On timeout the reply has | |
| 90 | - | `error: "timeout"` and still carries `diff`, `state` and `late`: the action may | |
| 91 | - | have run. | |
| 92 | - | ||
| 93 | - | At most 64 requests wait at once per session (any request with `wait` above | |
| 94 | - | `committed`, `until`, `shot`, `output-add` or `output-rm`). A further one gets | |
| 95 | - | `busy` before it runs. Committed-only requests and `quit` are never refused for | |
| 96 | - | this. | |
| 97 | - | ||
| 98 | - | ## Replies | |
| 99 | - | ||
| 100 | - | ```json | |
| 101 | - | {"id":2,"ok":true,"done":"settled","diff":{"mapped":[2],"focus_from":1,"focus_to":2,"focus_changed":true},"state":{...},"late":null} | |
| 102 | - | ``` | |
| 103 | - | ||
| 104 | - | | Field | Meaning | | |
| 105 | - | |---|---| | |
| 106 | - | | `id` | Echo of the request `id` | | |
| 107 | - | | `ok` | `true` on success | | |
| 108 | - | | `done` | Level reached: `committed`, `settled`, `presented` | | |
| 109 | - | | `diff` | Changes since the request: `mapped`, `unmapped` (window IDs), `focus_from`, `focus_to`, `focus_changed`, `workspaces` (`"OUTPUT:WS"` for each output whose shown workspace changed). Unchanged parts are omitted. | | |
| 110 | - | | `state` | State after the request, in the state file's shape, without window titles | | |
| 111 | - | | `late` | Window IDs still not settled at timeout | | |
| 112 | - | | `shots` | Captures: `{output, path, seq, png?}` | | |
| 113 | - | | `dir` | Continuous capture directory | | |
| 114 | - | | `error` | Error code, omitted on success | | |
| 115 | - | | `detail` | Human-readable detail for some errors | | |
| 116 | - | ||
| 117 | - | ## Captures | |
| 118 | - | ||
| 119 | - | ```json | |
| 120 | - | {"id":4,"op":"shot","outputs":["HEADLESS-1"],"inline":true} | |
| 121 | - | {"id":4,"ok":true,"done":"presented","shots":[{"output":"HEADLESS-1","path":"/run/user/1000/neferwl/sessions/demo/shots/7-HEADLESS-1.png","seq":7,"png":"iVBOR..."}],...} | |
| 122 | - | ``` | |
| 123 | - | ||
| 124 | - | An empty or missing `outputs` selects every output; an unknown name is | |
| 125 | - | `bad-request`. Shots wait for presentation and write private 8-bit sRGB PNG | |
| 126 | - | files under the session's `shots/` directory. `seq` is the presented scene | |
| 127 | - | sequence. `png` (base64) is present only with `inline: true`; the file is | |
| 128 | - | written anyway. `raw: true` on a single shot is `bad-request` with | |
| 129 | - | `detail: "raw shots need --every-frame"`. | |
| 130 | - | ||
| 131 | - | Continuous capture: | |
| 132 | - | ||
| 133 | - | ```json | |
| 134 | - | {"id":5,"op":"shot","every_frame":true,"dir":"/tmp/frames","outputs":["HEADLESS-1"],"raw":false} | |
| 135 | - | {"id":6,"op":"shot","stop":true} | |
| 136 | - | ``` | |
| 137 | - | ||
| 138 | - | `dir` must be absolute; it defaults to the session's `shots/frames`. With | |
| 139 | - | several outputs, each writes to `<dir>/<output>/`. Each directory gets | |
| 140 | - | `frame-NNNNNN.png`, `latest.png` (hard link to the newest frame) and | |
| 141 | - | `frames.ffconcat`; `raw: true` adds `latest-pq.png` on HDR outputs. Frames are | |
| 142 | - | skipped while the session is locked. `every_frame` with `stop`, or with | |
| 143 | - | `inline`, is `bad-request`. | |
| 144 | - | ||
| 145 | - | ## Runtime outputs | |
| 146 | - | ||
| 147 | - | ```json | |
| 148 | - | {"id":7,"op":"output-add","mode":"800x600@60","name":"extra"} | |
| 149 | - | {"id":8,"op":"output-rm","name":"extra"} | |
| 150 | - | ``` | |
| 151 | - | ||
| 152 | - | The reply comes once core state lists or drops the output, within 10 seconds. | |
| 153 | - | ||
| 154 | - | ## Errors | |
| 155 | - | ||
| 156 | - | | Code | Meaning | | |
| 157 | - | |---|---| | |
| 158 | - | | `bad-request` | Invalid JSON, unknown `op`, or invalid fields | | |
| 159 | - | | `unknown-command` | `action` is not in the catalog | | |
| 160 | - | | `forbidden` | The connection lacks the capability | | |
| 161 | - | | `locked` | The session is locked: actions other than `quit`, input and captures are refused | | |
| 162 | - | | `busy` | 64 requests are already waiting, or the capture backend is busy; retry later | | |
| 163 | - | | `timeout` | The completion condition was not reached in time; partial results are included | | |
| 164 | - | | `capture-failed` | A capture or the frame writer failed; see `detail` | | |
| 165 | - | ||
| 166 | - | ## Session startup | |
| 167 | - | ||
| 168 | - | `neferwl session new` starts a detached child with stdin, stdout and stderr on | |
| 169 | - | `/dev/null`: | |
| 170 | - | ||
| 171 | - | ```text | |
| 172 | - | <executable> --backend=headless --profile=P --session-id=ID --ready-fd=3 | |
| 173 | - | [--size=WxH,...] [--config=PATH] [--timeout=TTL] [extra flags...] | |
| 174 | - | ``` | |
| 175 | - | ||
| 176 | - | The child writes one JSON line with `id`, `wayland`, `control` and `display` | |
| 177 | - | to fd 3 when ready, then closes it. EOF before that line means startup failed. | |
| 178 | - | The child environment drops `WAYLAND_DISPLAY`, `WAYLAND_SOCKET`, `DISPLAY`, | |
| 179 | - | `NEFERWL_SESSION`, `NEFERWL_CONTROL`, `NEFERWL_STATE` and `NEFERWL_SLOT`, and | |
| 180 | - | `DBUS_SESSION_BUS_ADDRESS` unless `--dbus-session` is given. | |
| 181 | - | ||
| 182 | - | Session metadata lives in `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/meta.json` | |
| 183 | - | beside `control.sock`, `state.json`, `shots/` and a lifetime `lock`. | |
| 184 | - | `session ls` reclaims unlocked stale directories. `session rm` sends | |
| 185 | - | `{"op":"do","action":"quit","wait":"committed"}` and waits for the lock to be | |
| 186 | - | released; if the socket is unreachable, it sends SIGTERM only after checking | |
| 187 | - | that the recorded PID runs the same executable. | |
| @@ -1,187 +0,0 @@ | |||||
| 1 | - | # Control protocol | |||
| 2 | - | ||||
| 3 | - | Wire reference for the headless control socket. For sessions, targeting and CLI | |||
| 4 | - | usage, see [Scripting and agents](../control.md). | |||
| 5 | - | ||||
| 6 | - | ## Connection | |||
| 7 | - | ||||
| 8 | - | Each session listens on `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/control.sock` | |||
| 9 | - | (directory `0700`, socket `0600`). The server reads the peer's credentials with | |||
| 10 | - | `SO_PEERCRED` and closes connections from another uid. An accepted connection | |||
| 11 | - | has every capability: `read`, `act`, `input`, `capture`, `admin`. | |||
| 12 | - | ||||
| 13 | - | Messages are JSON lines: one object per line, in both directions. A connection | |||
| 14 | - | handles one request at a time: the next line is read after the previous reply | |||
| 15 | - | is sent. Open several connections for concurrent requests. | |||
| 16 | - | ||||
| 17 | - | `id` is optional and may be any JSON value; the reply echoes it, or carries | |||
| 18 | - | `null` when it is missing or the line is not valid JSON. | |||
| 19 | - | ||||
| 20 | - | ## Handshake | |||
| 21 | - | ||||
| 22 | - | ```json | |||
| 23 | - | {"id":1,"op":"hello"} | |||
| 24 | - | {"id":1,"ok":true,"v":1,"caps":["read","act","input","capture","admin"],"commands":[{"name":"output-add","arg":"MODE","kind":"admin","caps":["admin"],"summary":"Add a runtime virtual output."},...]} | |||
| 25 | - | ``` | |||
| 26 | - | ||||
| 27 | - | `commands` is the catalog: each entry has `name`, `arg`, `kind` (`action`, | |||
| 28 | - | `action-arg`, `query`, `inject`, `shot`, `admin`), `caps` and `summary`. Action | |||
| 29 | - | names are the bind actions; `do` has no automation-only names. Additive changes | |||
| 30 | - | keep `v: 1`; clients ignore unknown fields. | |||
| 31 | - | ||||
| 32 | - | ## Requests | |||
| 33 | - | ||||
| 34 | - | | `op` | Fields | Capability | | |||
| 35 | - | |---|---|---| | |||
| 36 | - | | `do` | `action` (name and arguments, e.g. `"focus-workspace 2"`), wait fields | `act` | | |||
| 37 | - | | `inject` | `kind` and its fields (below), wait fields | `input` | | |||
| 38 | - | | `query` | `what`: `"state"` | `read` | | |||
| 39 | - | | `shot` | `outputs`, `inline`, `raw`, `timeout` | `capture` | | |||
| 40 | - | | `shot` (continuous) | `every_frame` or `stop`, `outputs`, `dir`, `raw` | `capture` | | |||
| 41 | - | | `output-add` | `mode` (`WxH[@Hz]`), optional `name` | `admin` | | |||
| 42 | - | | `output-rm` | `name` | `admin` | | |||
| 43 | - | ||||
| 44 | - | Wait fields, on `do` and `inject`: | |||
| 45 | - | ||||
| 46 | - | | Field | Type | Default | Meaning | | |||
| 47 | - | |---|---|---|---| | |||
| 48 | - | | `wait` | `"committed"`, `"settled"`, `"presented"` | `"settled"` | Completion level | | |||
| 49 | - | | `until` | string | none | State predicate | | |||
| 50 | - | | `timeout` | Go duration string | `"10s"` | Bound on the wait, at most `5m` | | |||
| 51 | - | | `shot` | `true`, `false` or a list of output names | none | Capture after the wait; implies `presented` | | |||
| 52 | - | ||||
| 53 | - | ### Inject kinds | |||
| 54 | - | ||||
| 55 | - | | `kind` | Fields | Meaning | | |||
| 56 | - | |---|---|---| | |||
| 57 | - | | `key` | `combo` | Press and release a combination such as `Super+Return` | | |||
| 58 | - | | `type` | `text` | Type text through the session keymap | | |||
| 59 | - | | `press`, `release` | `combo` | Press, or release in reverse order | | |||
| 60 | - | | `pointer` | `cmd`, `args` | `move` with absolute global logical `x`, `y` strings; `click` (default `left`), `down`, `up` with `left`, `right` or `middle` | | |||
| 61 | - | | `swipe` | `fingers` (3 or 4), `dir` | Touchpad swipe `up`, `down`, `left` or `right` | | |||
| 62 | - | ||||
| 63 | - | ```json | |||
| 64 | - | {"id":1,"op":"inject","kind":"key","combo":"Super+Return","until":"window-mapped app_id=foot"} | |||
| 65 | - | {"id":2,"op":"inject","kind":"pointer","cmd":"move","args":["320","240"]} | |||
| 66 | - | {"id":3,"op":"inject","kind":"swipe","fingers":4,"dir":"down","wait":"presented"} | |||
| 67 | - | ``` | |||
| 68 | - | ||||
| 69 | - | Injected input goes through the core input path, so compositor binds run as | |||
| 70 | - | for a physical device. The first injection on a connection announces an input | |||
| 71 | - | device with ID `1` named `control` (for `output.<name>.input = control`). | |||
| 72 | - | ||||
| 73 | - | ## Wait semantics | |||
| 74 | - | ||||
| 75 | - | - `committed`: the action or input batch has been applied to core state. | |||
| 76 | - | - `settled`: animations are finished and every affected window has committed | |||
| 77 | - | its configured size. | |||
| 78 | - | - `presented`: the resulting scene has been presented on its outputs. | |||
| 79 | - | ||||
| 80 | - | `until` is checked on top of the level; the reply comes when both hold. | |||
| 81 | - | ||||
| 82 | - | | Predicate | Holds when | | |||
| 83 | - | |---|---| | |||
| 84 | - | | `window-mapped app_id=APP` | A window with that app ID mapped after the request | | |||
| 85 | - | | `focused app_id=APP` | A window with that app ID has focus | | |||
| 86 | - | | `unmapped id=N` | Window `N` is gone | | |||
| 87 | - | ||||
| 88 | - | `timeout` covers the wait and any capture together. A `timeout` above `5m` is | |||
| 89 | - | `bad-request` with `detail: "timeout exceeds 5m"`. On timeout the reply has | |||
| 90 | - | `error: "timeout"` and still carries `diff`, `state` and `late`: the action may | |||
| 91 | - | have run. | |||
| 92 | - | ||||
| 93 | - | At most 64 requests wait at once per session (any request with `wait` above | |||
| 94 | - | `committed`, `until`, `shot`, `output-add` or `output-rm`). A further one gets | |||
| 95 | - | `busy` before it runs. Committed-only requests and `quit` are never refused for | |||
| 96 | - | this. | |||
| 97 | - | ||||
| 98 | - | ## Replies | |||
| 99 | - | ||||
| 100 | - | ```json | |||
| 101 | - | {"id":2,"ok":true,"done":"settled","diff":{"mapped":[2],"focus_from":1,"focus_to":2,"focus_changed":true},"state":{...},"late":null} | |||
| 102 | - | ``` | |||
| 103 | - | ||||
| 104 | - | | Field | Meaning | | |||
| 105 | - | |---|---| | |||
| 106 | - | | `id` | Echo of the request `id` | | |||
| 107 | - | | `ok` | `true` on success | | |||
| 108 | - | | `done` | Level reached: `committed`, `settled`, `presented` | | |||
| 109 | - | | `diff` | Changes since the request: `mapped`, `unmapped` (window IDs), `focus_from`, `focus_to`, `focus_changed`, `workspaces` (`"OUTPUT:WS"` for each output whose shown workspace changed). Unchanged parts are omitted. | | |||
| 110 | - | | `state` | State after the request, in the state file's shape, without window titles | | |||
| 111 | - | | `late` | Window IDs still not settled at timeout | | |||
| 112 | - | | `shots` | Captures: `{output, path, seq, png?}` | | |||
| 113 | - | | `dir` | Continuous capture directory | | |||
| 114 | - | | `error` | Error code, omitted on success | | |||
| 115 | - | | `detail` | Human-readable detail for some errors | | |||
| 116 | - | ||||
| 117 | - | ## Captures | |||
| 118 | - | ||||
| 119 | - | ```json | |||
| 120 | - | {"id":4,"op":"shot","outputs":["HEADLESS-1"],"inline":true} | |||
| 121 | - | {"id":4,"ok":true,"done":"presented","shots":[{"output":"HEADLESS-1","path":"/run/user/1000/neferwl/sessions/demo/shots/7-HEADLESS-1.png","seq":7,"png":"iVBOR..."}],...} | |||
| 122 | - | ``` | |||
| 123 | - | ||||
| 124 | - | An empty or missing `outputs` selects every output; an unknown name is | |||
| 125 | - | `bad-request`. Shots wait for presentation and write private 8-bit sRGB PNG | |||
| 126 | - | files under the session's `shots/` directory. `seq` is the presented scene | |||
| 127 | - | sequence. `png` (base64) is present only with `inline: true`; the file is | |||
| 128 | - | written anyway. `raw: true` on a single shot is `bad-request` with | |||
| 129 | - | `detail: "raw shots need --every-frame"`. | |||
| 130 | - | ||||
| 131 | - | Continuous capture: | |||
| 132 | - | ||||
| 133 | - | ```json | |||
| 134 | - | {"id":5,"op":"shot","every_frame":true,"dir":"/tmp/frames","outputs":["HEADLESS-1"],"raw":false} | |||
| 135 | - | {"id":6,"op":"shot","stop":true} | |||
| 136 | - | ``` | |||
| 137 | - | ||||
| 138 | - | `dir` must be absolute; it defaults to the session's `shots/frames`. With | |||
| 139 | - | several outputs, each writes to `<dir>/<output>/`. Each directory gets | |||
| 140 | - | `frame-NNNNNN.png`, `latest.png` (hard link to the newest frame) and | |||
| 141 | - | `frames.ffconcat`; `raw: true` adds `latest-pq.png` on HDR outputs. Frames are | |||
| 142 | - | skipped while the session is locked. `every_frame` with `stop`, or with | |||
| 143 | - | `inline`, is `bad-request`. | |||
| 144 | - | ||||
| 145 | - | ## Runtime outputs | |||
| 146 | - | ||||
| 147 | - | ```json | |||
| 148 | - | {"id":7,"op":"output-add","mode":"800x600@60","name":"extra"} | |||
| 149 | - | {"id":8,"op":"output-rm","name":"extra"} | |||
| 150 | - | ``` | |||
| 151 | - | ||||
| 152 | - | The reply comes once core state lists or drops the output, within 10 seconds. | |||
| 153 | - | ||||
| 154 | - | ## Errors | |||
| 155 | - | ||||
| 156 | - | | Code | Meaning | | |||
| 157 | - | |---|---| | |||
| 158 | - | | `bad-request` | Invalid JSON, unknown `op`, or invalid fields | | |||
| 159 | - | | `unknown-command` | `action` is not in the catalog | | |||
| 160 | - | | `forbidden` | The connection lacks the capability | | |||
| 161 | - | | `locked` | The session is locked: actions other than `quit`, input and captures are refused | | |||
| 162 | - | | `busy` | 64 requests are already waiting, or the capture backend is busy; retry later | | |||
| 163 | - | | `timeout` | The completion condition was not reached in time; partial results are included | | |||
| 164 | - | | `capture-failed` | A capture or the frame writer failed; see `detail` | | |||
| 165 | - | ||||
| 166 | - | ## Session startup | |||
| 167 | - | ||||
| 168 | - | `neferwl session new` starts a detached child with stdin, stdout and stderr on | |||
| 169 | - | `/dev/null`: | |||
| 170 | - | ||||
| 171 | - | ```text | |||
| 172 | - | <executable> --backend=headless --profile=P --session-id=ID --ready-fd=3 | |||
| 173 | - | [--size=WxH,...] [--config=PATH] [--timeout=TTL] [extra flags...] | |||
| 174 | - | ``` | |||
| 175 | - | ||||
| 176 | - | The child writes one JSON line with `id`, `wayland`, `control` and `display` | |||
| 177 | - | to fd 3 when ready, then closes it. EOF before that line means startup failed. | |||
| 178 | - | The child environment drops `WAYLAND_DISPLAY`, `WAYLAND_SOCKET`, `DISPLAY`, | |||
| 179 | - | `NEFERWL_SESSION`, `NEFERWL_CONTROL`, `NEFERWL_STATE` and `NEFERWL_SLOT`, and | |||
| 180 | - | `DBUS_SESSION_BUS_ADDRESS` unless `--dbus-session` is given. | |||
| 181 | - | ||||
| 182 | - | Session metadata lives in `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/meta.json` | |||
| 183 | - | beside `control.sock`, `state.json`, `shots/` and a lifetime `lock`. | |||
| 184 | - | `session ls` reclaims unlocked stale directories. `session rm` sends | |||
| 185 | - | `{"op":"do","action":"quit","wait":"committed"}` and waits for the lock to be | |||
| 186 | - | released; if the socket is unreachable, it sends SIGTERM only after checking | |||
| 187 | - | that the recorded PID runs the same executable. | |||
M docs/dev/headless.md +77 -70
| @@ -1,45 +1,59 @@ | |||
| 1 | - | # Headless testing | |
| 1 | + | # Headless mode | |
| 2 | 2 | ||
| 3 | - | Test user-facing changes on an isolated headless session before merging. The | |
| 4 | - | session has its own Wayland display, control socket and logs, so the desktop | |
| 5 | - | stays untouched. [Scripting and agents](../control.md) documents every control | |
| 6 | - | command; this page covers testing NeferWL itself. | |
| 3 | + | Runs NeferWL without a screen, for tests and quick checks: | |
| 7 | 4 | ||
| 8 | - | ## End-to-end recipe | |
| 5 | + | ```sh | |
| 6 | + | neferwl --backend=headless --screenshot /tmp/neferwl-shots | |
| 7 | + | WAYLAND_DISPLAY=<name from the log> foot | |
| 8 | + | ``` | |
| 9 | + | ||
| 10 | + | - `latest.png` shows the current frame; `frames.ffconcat` records frame timing. Every frame is also saved as `frame-NNNNNN.png`, so the directory grows. `latest.png` is a hard link to the newest frame, so replace it rather than editing it in place. | |
| 11 | + | - `--size 640x360,640x360` creates two outputs, arranged left to right, | |
| 12 | + | for testing `focus-monitor-left/right` and moving columns between outputs. | |
| 13 | + | - With several outputs, each writes to `<dir>/HEADLESS-<n>/`. | |
| 14 | + | - `--timeout 5s` stops NeferWL after 5 seconds. | |
| 15 | + | - Animations are on by default. For checks that need instant layout changes, set `animations = off` in the throwaway config; otherwise let transitions settle before checking final geometry. | |
| 16 | + | - `grim` and recorders work too; see [Screen capture](../capture.md). | |
| 17 | + | ||
| 18 | + | ## Recording a video | |
| 19 | + | ||
| 20 | + | Convert the screenshots and their real-time timing index into a video: | |
| 9 | 21 | ||
| 10 | 22 | ```sh | |
| 11 | - | T=$(mktemp -d) | |
| 12 | - | CGO_ENABLED=0 go build -o "$T/neferwl" ./cmd/neferwl | |
| 13 | - | printf 'animations = off\n' >"$T/config" | |
| 14 | - | "$T/neferwl" session new --id test --config "$T/config" --ttl 60s -- --no-xwayland | |
| 15 | - | "$T/neferwl" -s test key Super+Return --until 'window-mapped app_id=foot' | |
| 16 | - | "$T/neferwl" -s test state | jq '.windows[] | {id, app_id, column, row}' | |
| 17 | - | "$T/neferwl" -s test shot | |
| 18 | - | "$T/neferwl" session rm test | |
| 23 | + | ffmpeg -f concat -safe 0 -i /tmp/shots/frames.ffconcat -vf "fps=60,format=yuv420p" -c:v libx264 -crf 18 demo.mp4 | |
| 19 | 24 | ``` | |
| 20 | 25 | ||
| 21 | - | - Use the branch binary for every command and `-s test` for every control | |
| 22 | - | command. | |
| 23 | - | - `--size 640x360,640x360` creates two outputs, left to right. | |
| 24 | - | - With animations on, keep the default `--wait settled` before reading | |
| 25 | - | geometry. | |
| 26 | - | - Launch external clients with the `wayland` display from the readiness JSON. | |
| 27 | - | - Logs: `$XDG_STATE_HOME/neferwl/sessions/test/latest.log`. | |
| 28 | - | - Record a sequence with `shot --every-frame` and `shot --stop`; see | |
| 29 | - | [Every frame and video](../control.md#every-frame-and-video). | |
| 30 | - | ||
| 31 | - | ## Demo recording | |
| 26 | + | For a GIF, convert `demo.mp4` with ffmpeg's `palettegen` and `paletteuse` filters. | |
| 27 | + | ||
| 28 | + | ### Demo recording | |
| 32 | 29 | Run `tools/demo/record.sh`. It requires Go 1.27, rootless Docker, ffmpeg, network access and an AMD GPU. | |
| 33 | 30 | It builds the Arch image (apps, tesseract, AT-SPI) and the compositor binary, then records the 1080p README demo. | |
| 34 | 31 | The compositor runs headless inside a disposable container, with the binary and a work directory bind-mounted and `/dev/dri` passed for the GPU. | |
| 35 | 32 | The image only carries Mesa's radeon Vulkan driver, and hint scans need the sync files that a hardware driver exports; the script stops early without an AMD render node. | |
| 36 | 33 | Firefox opens a live DuckDuckGo page, so the recording needs the network and its content varies. | |
| 37 | - | The recording script translates `input.txt` into control-socket commands while launching apps on the same clock. | |
| 34 | + | A FIFO feeds `input.txt` while the script launches the apps on the same clock. | |
| 38 | 35 | The hint step makes Firefox fullscreen and labels the page with `hint`; `hint-click <words>` then types the label of the link that shows those words, found from the scan's dump and an OCR read of the still page (`hint-read`). | |
| 39 | - | The recording only counts if the compositor stops on the quit key that ends `input.txt`; reaching its lifetime limit first fails the run as truncated. | |
| 36 | + | The recording only counts if the compositor stops on the quit key that ends `input.txt`; reaching its `--timeout` first fails the run as truncated. | |
| 40 | 37 | Temporary captures are removed by default; set `KEEP_CAPTURE=1` to keep successful runs. | |
| 41 | 38 | The recording and poster replace `docs/media/demo.mp4` and `docs/media/demo.png`. | |
| 42 | 39 | ||
| 40 | + | ## Input scripts | |
| 41 | + | ||
| 42 | + | `--input <file>`, or `--input -` for stdin, plays one command per line: | |
| 43 | + | ||
| 44 | + | | Command | Effect | | |
| 45 | + | |---|---| | |
| 46 | + | | `type <text>` | Type text | | |
| 47 | + | | `key Super+Return` | Press a key, with optional Shift, Ctrl, Alt or Super | | |
| 48 | + | | `hold Super+h 1s` | Press a key like `key`, hold it, then release it | | |
| 49 | + | | `press Super`, `release Super` | Hold or release a modifier across mouse actions (`Super`, `Shift`, `Ctrl`, `Alt`) | | |
| 50 | + | | `sleep 1s` | Wait | | |
| 51 | + | | `move <x> <y>` | Move the pointer, in output coordinates | | |
| 52 | + | | `click [left\|right\|middle]`, `down <button>`, `up <button>` | Mouse buttons | | |
| 53 | + | | `vt away`, `vt back` | Simulate a VT switch: the keys and modifiers held are forgotten and the seat goes inactive, then active again | | |
| 54 | + | | `swipe up\|down\|left\|right` | Three-finger flick | | |
| 55 | + | | `swipe4 up\|down` | Four-finger flick | | |
| 56 | + | ||
| 43 | 57 | ## Testing input methods | |
| 44 | 58 | ||
| 45 | 59 | `examples/testime` sends a preedit string, then commits text, each time an app enables text input: | |
| @@ -52,7 +66,7 @@ WAYLAND_DISPLAY=<name> go run ./examples/testime -preedit nihon -commit 日本 | |||
| 52 | 66 | ||
| 53 | 67 | ## Testing the virtual pointer | |
| 54 | 68 | ||
| 55 | - | `neferwl pointer` drives the pointer of the session whose `WAYLAND_DISPLAY` it runs with: | |
| 69 | + | `neferwl pointer` drives the pointer of the headless session (same display resolution as `neferwl state`); run it with the headless `WAYLAND_DISPLAY`: | |
| 56 | 70 | ||
| 57 | 71 | ```sh | |
| 58 | 72 | WAYLAND_DISPLAY=<name> neferwl pointer abs 0.1 0.5 click | |
| @@ -60,7 +74,7 @@ WAYLAND_DISPLAY=<name> neferwl pointer drag 100 0 scroll down 3 | |||
| 60 | 74 | WAYLAND_DISPLAY=<name> neferwl pointer --output HEADLESS-2 abs 0.5 0.5 | |
| 61 | 75 | ``` | |
| 62 | 76 | ||
| 63 | - | Check the result with `neferwl -s <id> state` (`.window.id` is the focused window). Single shots do not show the cursor; `--every-frame` frames do. `TestPointerCLI` (`internal/app`, in `go test ./...`) runs the built binary against a headless NeferWL and checks a click, a drag, a scroll and the release at exit on a test client. | |
| 77 | + | Check the result with `neferwl state` (`.window.id` is the focused window). Headless screenshots do not show the cursor. `TestPointerCLI` (`internal/app`, in `go test ./...`) runs the built binary against a headless NeferWL and checks a click, a drag, a scroll and the release at exit on a test client. | |
| 64 | 78 | ||
| 65 | 79 | ## wayvnc check | |
| 66 | 80 | ||
| @@ -124,36 +138,41 @@ For the test installation these are | |||
| 124 | 138 | `~/.local/share/nefer-hints-test/models`. | |
| 125 | 139 | ||
| 126 | 140 | ```sh | |
| 127 | - | XDG_STATE_HOME="$T/state" NEFERWL_HINT_DEBUG=1 dbus-run-session -- bash -c ' | |
| 141 | + | env -u NEFERWL_STATE -u NEFERWL_SLOT XDG_STATE_HOME="$T/state" \ | |
| 142 | + | NEFERWL_HINT_DEBUG=1 dbus-run-session -- bash -c ' | |
| 128 | 143 | T=$1 | |
| 144 | + | # Enable accessibility before either the compositor or its clients starts. | |
| 129 | 145 | gdbus call --session --dest org.a11y.Bus --object-path /org/a11y/bus \ | |
| 130 | 146 | --method org.freedesktop.DBus.Properties.Set org.a11y.Status IsEnabled "<true>" | |
| 147 | + | # On hosts whose registry service activation is unavailable (adjust path). | |
| 131 | 148 | /usr/lib/at-spi2-registryd >"$T/registry.log" 2>&1 & | |
| 132 | - | ready=$("$T/neferwl" session new --id hints --dbus-session --config "$T/config" \ | |
| 133 | - | --ttl 60s -- --no-xwayland) | |
| 134 | - | export WAYLAND_DISPLAY=$(printf "%s" "$ready" | jq -r .wayland) | |
| 135 | - | "$T/neferwl" -s hints shot --every-frame --dir "$T/shots" | |
| 149 | + | WAYLAND_DISPLAY=wp4-headless "$T/neferwl" --backend=headless \ | |
| 150 | + | --config "$T/config" --no-xwayland --screenshot "$T/shots" \ | |
| 151 | + | --input "$T/input" --timeout 20s & compositor=$! | |
| 152 | + | # Bounded wait for the actual display, not an inherited live-session display. | |
| 153 | + | for i in {1..50}; do | |
| 154 | + | display=$(jq -r "select(.message == \"listening\") | .WAYLAND_DISPLAY" \ | |
| 155 | + | "$T/state/neferwl/runs/headless/latest.log" 2>/dev/null | head -1) | |
| 156 | + | [ -n "$display" ] && break | |
| 157 | + | sleep .1 | |
| 158 | + | done | |
| 159 | + | [ -n "$display" ] || exit 1 | |
| 160 | + | export WAYLAND_DISPLAY="$display" | |
| 136 | 161 | foot sh -c "printf https://example.org/a; exec sleep 60" & | |
| 137 | 162 | chromium --ozone-platform=wayland --force-renderer-accessibility \ | |
| 138 | 163 | --user-data-dir="$T/chrome" "file://$T/page.html" >"$T/chromium.log" 2>&1 & | |
| 139 | - | "$T/neferwl" -s hints key Super+g --until "window-mapped app_id=chromium" | |
| 140 | - | read -r -p "Visible hint label: " label | |
| 141 | - | "$T/neferwl" -s hints type "$label" | |
| 142 | - | "$T/neferwl" -s hints shot | |
| 143 | - | "$T/neferwl" -s hints shot --stop | |
| 144 | - | "$T/neferwl" session rm hints | |
| 164 | + | wait "$compositor" | |
| 145 | 165 | ' bash "$T" | |
| 146 | 166 | ``` | |
| 147 | 167 | ||
| 148 | 168 | All clients and state queries must run inside that wrapper shell so they share | |
| 149 | 169 | its session bus as well as its Wayland display. Logs are in | |
| 150 | - | `$T/state/neferwl/sessions/hints/latest.log`. | |
| 151 | - | Prepare `$T/page.html` with underlined local links before running (the shell example also needs `jq`). OCR detects | |
| 170 | + | `$T/state/neferwl/runs/headless/latest.log`. | |
| 171 | + | Prepare `$T/page.html` with underlined local links before running. OCR detects | |
| 152 | 172 | URL-like text without an underline and underlined link text; ordinary menu | |
| 153 | 173 | labels, buttons, separators and box borders do not produce OCR targets. Arrange both windows | |
| 154 | 174 | visibly; open a menu if possible. | |
| 155 | - | Wait for the clients to map, run `neferwl -s hints key Super+g`, then use | |
| 156 | - | `neferwl -s hints type <visible-label>` while the session is running. | |
| 175 | + | Script `sleep 8s`, `key Super+g`, `sleep 4s`, then `type <visible label>`. | |
| 157 | 176 | Check screenshots before and after the click; a local link changing the page | |
| 158 | 177 | background is a convenient observable result. | |
| 159 | 178 | ||
| @@ -174,7 +193,7 @@ sources (startup rejects `hint.sources = ocr, ocr`). | |||
| 174 | 193 | ||
| 175 | 194 | ## OCR URL opening | |
| 176 | 195 | ||
| 177 | - | OCR targets with an http, https or mailto URL run `xdg-open` instead of a click. The recipe builds the binary, writes a minimal config, and puts a fake `xdg-open` first in `PATH`. It needs the hint prerequisites listed above. | |
| 196 | + | OCR targets with an http, https or mailto URL run `xdg-open` instead of a click. The recipe builds the binary, writes a minimal config and input script, and puts a fake `xdg-open` first in `PATH`. It needs the hint prerequisites listed above. | |
| 178 | 197 | ||
| 179 | 198 | ```sh | |
| 180 | 199 | T=$(mktemp -d); mkdir "$T/bin" | |
| @@ -189,21 +208,12 @@ hint.sources = atspi, ocr | |||
| 189 | 208 | bind.cmd+g = hint | |
| 190 | 209 | bind.cmd+u = spawn foot -o main.font=monospace:size=28 $T/show.sh | |
| 191 | 210 | EOF | |
| 192 | - | PATH="$T/bin:$PATH" "$T/neferwl" session new --id ocr --config "$T/config" --ttl 60s -- --no-xwayland | |
| 193 | - | "$T/neferwl" -s ocr shot --every-frame --dir "$T/shots" | |
| 194 | - | "$T/neferwl" -s ocr key Super+u --until 'window-mapped app_id=foot' | |
| 195 | - | "$T/neferwl" -s ocr key Super+g | |
| 196 | - | "$T/neferwl" -s ocr shot | |
| 197 | - | # Read the visible hint label, then: | |
| 198 | - | "$T/neferwl" -s ocr type '<label>' | |
| 199 | - | "$T/neferwl" -s ocr shot --stop | |
| 200 | - | "$T/neferwl" session rm ocr | |
| 211 | + | printf 'sleep 1s\nkey Super+u\nsleep 4s\nkey Super+g\nsleep 4s\n' >"$T/input" | |
| 212 | + | env -u NEFERWL_STATE -u NEFERWL_SLOT PATH="$T/bin:$PATH" "$T/neferwl" --backend=headless \ | |
| 213 | + | --config "$T/config" --no-xwayland --screenshot "$T/shots" --input "$T/input" --timeout 20s | |
| 201 | 214 | ``` | |
| 202 | 215 | ||
| 203 | - | The foot window shows `https://example.com`. Typing its hint label opens that | |
| 204 | - | URL; `$T/opened` holds exactly `https://example.com`. A `file:` target is clicked | |
| 205 | - | and leaves it empty. Launcher failures are in the session log under | |
| 206 | - | `component=launcher`. | |
| 216 | + | The input script opens a large-font foot showing `https://example.com` and runs `hint`. Read the label from the screenshot, then append `type <label>` and a `sleep 2s` to `$T/input` and run again. `$T/opened` then holds exactly `https://example.com`. A `file:` target is clicked and leaves it empty. Launcher failures are in the log under `component=launcher`. | |
| 207 | 217 | ||
| 208 | 218 | ## Primary output coordinates | |
| 209 | 219 | ||
| @@ -237,16 +247,13 @@ output.HEADLESS-2.right-of = HEADLESS-1 | |||
| 237 | 247 | On the isolated headless display, `wayland-info -i wl_output` should report | |
| 238 | 248 | HEADLESS-1 at (-640,0) and HEADLESS-2 at (0,0). | |
| 239 | 249 | ||
| 240 | - | ## Control input device | |
| 241 | - | ||
| 242 | - | Control input announces a device named `control` with ID | |
| 243 | - | `9223372036854775808`, which no real device uses. Use | |
| 244 | - | `output.tv.input = control` to test device-bound focus on a virtual output. | |
| 245 | - | Control `move` coordinates stay global logical coordinates. | |
| 246 | - | ||
| 247 | - | ## Session paths | |
| 250 | + | Scripted input announces device ID `1` with the fixed name `headless-script`. | |
| 251 | + | Use `output.tv.input = headless-script` to test device-bound focus on a virtual | |
| 252 | + | output. The script's `move` coordinates remain global logical coordinates. | |
| 248 | 253 | ||
| 249 | - | `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/` holds `meta.json`, `control.sock`, | |
| 250 | - | `state.json` and `shots/`. Logs live in | |
| 251 | - | `$XDG_STATE_HOME/neferwl/sessions/<id>/`; the 20 most recent session log | |
| 252 | - | directories are kept. | |
| 254 | + | `device <id>` selects the scripted device for subsequent keys, motions, buttons | |
| 255 | + | and gestures (positive integer; default `1`). A newly selected ID is announced | |
| 256 | + | once: ID `1` is `headless-script`, other IDs are `headless-script-<id>`. | |
| 257 | + | Devices share the scripted seat's keymap; release held keys before switching. | |
| 258 | + | For example, bind `headless-script-2` to `tv`, then interleave `device 2`, | |
| 259 | + | `key a`, `device 1`, `key a` to exercise bound/unbound focus switching. | |
| @@ -1,45 +1,59 @@ | |||||
| 1 | - | # Headless testing | 1 | + | # Headless mode |
| 2 | 2 | ||||
| 3 | - | Test user-facing changes on an isolated headless session before merging. The | 3 | + | Runs NeferWL without a screen, for tests and quick checks: |
| 4 | - | session has its own Wayland display, control socket and logs, so the desktop | |||
| 5 | - | stays untouched. [Scripting and agents](../control.md) documents every control | |||
| 6 | - | command; this page covers testing NeferWL itself. | |||
| 7 | 4 | ||||
| 8 | - | ## End-to-end recipe | 5 | + | ```sh |
| 6 | + | neferwl --backend=headless --screenshot /tmp/neferwl-shots | |||
| 7 | + | WAYLAND_DISPLAY=<name from the log> foot | |||
| 8 | + | ``` | |||
| 9 | + | ||||
| 10 | + | - `latest.png` shows the current frame; `frames.ffconcat` records frame timing. Every frame is also saved as `frame-NNNNNN.png`, so the directory grows. `latest.png` is a hard link to the newest frame, so replace it rather than editing it in place. | |||
| 11 | + | - `--size 640x360,640x360` creates two outputs, arranged left to right, | |||
| 12 | + | for testing `focus-monitor-left/right` and moving columns between outputs. | |||
| 13 | + | - With several outputs, each writes to `<dir>/HEADLESS-<n>/`. | |||
| 14 | + | - `--timeout 5s` stops NeferWL after 5 seconds. | |||
| 15 | + | - Animations are on by default. For checks that need instant layout changes, set `animations = off` in the throwaway config; otherwise let transitions settle before checking final geometry. | |||
| 16 | + | - `grim` and recorders work too; see [Screen capture](../capture.md). | |||
| 17 | + | ||||
| 18 | + | ## Recording a video | |||
| 19 | + | ||||
| 20 | + | Convert the screenshots and their real-time timing index into a video: | |||
| 9 | 21 | ||||
| 10 | ```sh | 22 | ```sh | ||
| 11 | - | T=$(mktemp -d) | 23 | + | ffmpeg -f concat -safe 0 -i /tmp/shots/frames.ffconcat -vf "fps=60,format=yuv420p" -c:v libx264 -crf 18 demo.mp4 |
| 12 | - | CGO_ENABLED=0 go build -o "$T/neferwl" ./cmd/neferwl | |||
| 13 | - | printf 'animations = off\n' >"$T/config" | |||
| 14 | - | "$T/neferwl" session new --id test --config "$T/config" --ttl 60s -- --no-xwayland | |||
| 15 | - | "$T/neferwl" -s test key Super+Return --until 'window-mapped app_id=foot' | |||
| 16 | - | "$T/neferwl" -s test state | jq '.windows[] | {id, app_id, column, row}' | |||
| 17 | - | "$T/neferwl" -s test shot | |||
| 18 | - | "$T/neferwl" session rm test | |||
| 19 | ``` | 24 | ``` | ||
| 20 | 25 | ||||
| 21 | - | - Use the branch binary for every command and `-s test` for every control | 26 | + | For a GIF, convert `demo.mp4` with ffmpeg's `palettegen` and `paletteuse` filters. |
| 22 | - | command. | 27 | + | |
| 23 | - | - `--size 640x360,640x360` creates two outputs, left to right. | 28 | + | ### Demo recording |
| 24 | - | - With animations on, keep the default `--wait settled` before reading | |||
| 25 | - | geometry. | |||
| 26 | - | - Launch external clients with the `wayland` display from the readiness JSON. | |||
| 27 | - | - Logs: `$XDG_STATE_HOME/neferwl/sessions/test/latest.log`. | |||
| 28 | - | - Record a sequence with `shot --every-frame` and `shot --stop`; see | |||
| 29 | - | [Every frame and video](../control.md#every-frame-and-video). | |||
| 30 | - | ||||
| 31 | - | ## Demo recording | |||
| 32 | Run `tools/demo/record.sh`. It requires Go 1.27, rootless Docker, ffmpeg, network access and an AMD GPU. | 29 | Run `tools/demo/record.sh`. It requires Go 1.27, rootless Docker, ffmpeg, network access and an AMD GPU. | ||
| 33 | It builds the Arch image (apps, tesseract, AT-SPI) and the compositor binary, then records the 1080p README demo. | 30 | It builds the Arch image (apps, tesseract, AT-SPI) and the compositor binary, then records the 1080p README demo. | ||
| 34 | The compositor runs headless inside a disposable container, with the binary and a work directory bind-mounted and `/dev/dri` passed for the GPU. | 31 | The compositor runs headless inside a disposable container, with the binary and a work directory bind-mounted and `/dev/dri` passed for the GPU. | ||
| 35 | The image only carries Mesa's radeon Vulkan driver, and hint scans need the sync files that a hardware driver exports; the script stops early without an AMD render node. | 32 | The image only carries Mesa's radeon Vulkan driver, and hint scans need the sync files that a hardware driver exports; the script stops early without an AMD render node. | ||
| 36 | Firefox opens a live DuckDuckGo page, so the recording needs the network and its content varies. | 33 | Firefox opens a live DuckDuckGo page, so the recording needs the network and its content varies. | ||
| 37 | - | The recording script translates `input.txt` into control-socket commands while launching apps on the same clock. | 34 | + | A FIFO feeds `input.txt` while the script launches the apps on the same clock. |
| 38 | The hint step makes Firefox fullscreen and labels the page with `hint`; `hint-click <words>` then types the label of the link that shows those words, found from the scan's dump and an OCR read of the still page (`hint-read`). | 35 | The hint step makes Firefox fullscreen and labels the page with `hint`; `hint-click <words>` then types the label of the link that shows those words, found from the scan's dump and an OCR read of the still page (`hint-read`). | ||
| 39 | - | The recording only counts if the compositor stops on the quit key that ends `input.txt`; reaching its lifetime limit first fails the run as truncated. | 36 | + | The recording only counts if the compositor stops on the quit key that ends `input.txt`; reaching its `--timeout` first fails the run as truncated. |
| 40 | Temporary captures are removed by default; set `KEEP_CAPTURE=1` to keep successful runs. | 37 | Temporary captures are removed by default; set `KEEP_CAPTURE=1` to keep successful runs. | ||
| 41 | The recording and poster replace `docs/media/demo.mp4` and `docs/media/demo.png`. | 38 | The recording and poster replace `docs/media/demo.mp4` and `docs/media/demo.png`. | ||
| 42 | 39 | ||||
| 40 | + | ## Input scripts | |||
| 41 | + | ||||
| 42 | + | `--input <file>`, or `--input -` for stdin, plays one command per line: | |||
| 43 | + | ||||
| 44 | + | | Command | Effect | | |||
| 45 | + | |---|---| | |||
| 46 | + | | `type <text>` | Type text | | |||
| 47 | + | | `key Super+Return` | Press a key, with optional Shift, Ctrl, Alt or Super | | |||
| 48 | + | | `hold Super+h 1s` | Press a key like `key`, hold it, then release it | | |||
| 49 | + | | `press Super`, `release Super` | Hold or release a modifier across mouse actions (`Super`, `Shift`, `Ctrl`, `Alt`) | | |||
| 50 | + | | `sleep 1s` | Wait | | |||
| 51 | + | | `move <x> <y>` | Move the pointer, in output coordinates | | |||
| 52 | + | | `click [left\|right\|middle]`, `down <button>`, `up <button>` | Mouse buttons | | |||
| 53 | + | | `vt away`, `vt back` | Simulate a VT switch: the keys and modifiers held are forgotten and the seat goes inactive, then active again | | |||
| 54 | + | | `swipe up\|down\|left\|right` | Three-finger flick | | |||
| 55 | + | | `swipe4 up\|down` | Four-finger flick | | |||
| 56 | + | ||||
| 43 | ## Testing input methods | 57 | ## Testing input methods | ||
| 44 | 58 | ||||
| 45 | `examples/testime` sends a preedit string, then commits text, each time an app enables text input: | 59 | `examples/testime` sends a preedit string, then commits text, each time an app enables text input: | ||
| @@ -52,7 +66,7 @@ WAYLAND_DISPLAY=<name> go run ./examples/testime -preedit nihon -commit 日本 | |||||
| 52 | 66 | ||||
| 53 | ## Testing the virtual pointer | 67 | ## Testing the virtual pointer | ||
| 54 | 68 | ||||
| 55 | - | `neferwl pointer` drives the pointer of the session whose `WAYLAND_DISPLAY` it runs with: | 69 | + | `neferwl pointer` drives the pointer of the headless session (same display resolution as `neferwl state`); run it with the headless `WAYLAND_DISPLAY`: |
| 56 | 70 | ||||
| 57 | ```sh | 71 | ```sh | ||
| 58 | WAYLAND_DISPLAY=<name> neferwl pointer abs 0.1 0.5 click | 72 | WAYLAND_DISPLAY=<name> neferwl pointer abs 0.1 0.5 click | ||
| @@ -60,7 +74,7 @@ WAYLAND_DISPLAY=<name> neferwl pointer drag 100 0 scroll down 3 | |||||
| 60 | WAYLAND_DISPLAY=<name> neferwl pointer --output HEADLESS-2 abs 0.5 0.5 | 74 | WAYLAND_DISPLAY=<name> neferwl pointer --output HEADLESS-2 abs 0.5 0.5 | ||
| 61 | ``` | 75 | ``` | ||
| 62 | 76 | ||||
| 63 | - | Check the result with `neferwl -s <id> state` (`.window.id` is the focused window). Single shots do not show the cursor; `--every-frame` frames do. `TestPointerCLI` (`internal/app`, in `go test ./...`) runs the built binary against a headless NeferWL and checks a click, a drag, a scroll and the release at exit on a test client. | 77 | + | Check the result with `neferwl state` (`.window.id` is the focused window). Headless screenshots do not show the cursor. `TestPointerCLI` (`internal/app`, in `go test ./...`) runs the built binary against a headless NeferWL and checks a click, a drag, a scroll and the release at exit on a test client. |
| 64 | 78 | ||||
| 65 | ## wayvnc check | 79 | ## wayvnc check | ||
| 66 | 80 | ||||
| @@ -124,36 +138,41 @@ For the test installation these are | |||||
| 124 | `~/.local/share/nefer-hints-test/models`. | 138 | `~/.local/share/nefer-hints-test/models`. | ||
| 125 | 139 | ||||
| 126 | ```sh | 140 | ```sh | ||
| 127 | - | XDG_STATE_HOME="$T/state" NEFERWL_HINT_DEBUG=1 dbus-run-session -- bash -c ' | 141 | + | env -u NEFERWL_STATE -u NEFERWL_SLOT XDG_STATE_HOME="$T/state" \ |
| 142 | + | NEFERWL_HINT_DEBUG=1 dbus-run-session -- bash -c ' | |||
| 128 | T=$1 | 143 | T=$1 | ||
| 144 | + | # Enable accessibility before either the compositor or its clients starts. | |||
| 129 | gdbus call --session --dest org.a11y.Bus --object-path /org/a11y/bus \ | 145 | gdbus call --session --dest org.a11y.Bus --object-path /org/a11y/bus \ | ||
| 130 | --method org.freedesktop.DBus.Properties.Set org.a11y.Status IsEnabled "<true>" | 146 | --method org.freedesktop.DBus.Properties.Set org.a11y.Status IsEnabled "<true>" | ||
| 147 | + | # On hosts whose registry service activation is unavailable (adjust path). | |||
| 131 | /usr/lib/at-spi2-registryd >"$T/registry.log" 2>&1 & | 148 | /usr/lib/at-spi2-registryd >"$T/registry.log" 2>&1 & | ||
| 132 | - | ready=$("$T/neferwl" session new --id hints --dbus-session --config "$T/config" \ | 149 | + | WAYLAND_DISPLAY=wp4-headless "$T/neferwl" --backend=headless \ |
| 133 | - | --ttl 60s -- --no-xwayland) | 150 | + | --config "$T/config" --no-xwayland --screenshot "$T/shots" \ |
| 134 | - | export WAYLAND_DISPLAY=$(printf "%s" "$ready" | jq -r .wayland) | 151 | + | --input "$T/input" --timeout 20s & compositor=$! |
| 135 | - | "$T/neferwl" -s hints shot --every-frame --dir "$T/shots" | 152 | + | # Bounded wait for the actual display, not an inherited live-session display. |
| 153 | + | for i in {1..50}; do | |||
| 154 | + | display=$(jq -r "select(.message == \"listening\") | .WAYLAND_DISPLAY" \ | |||
| 155 | + | "$T/state/neferwl/runs/headless/latest.log" 2>/dev/null | head -1) | |||
| 156 | + | [ -n "$display" ] && break | |||
| 157 | + | sleep .1 | |||
| 158 | + | done | |||
| 159 | + | [ -n "$display" ] || exit 1 | |||
| 160 | + | export WAYLAND_DISPLAY="$display" | |||
| 136 | foot sh -c "printf https://example.org/a; exec sleep 60" & | 161 | foot sh -c "printf https://example.org/a; exec sleep 60" & | ||
| 137 | chromium --ozone-platform=wayland --force-renderer-accessibility \ | 162 | chromium --ozone-platform=wayland --force-renderer-accessibility \ | ||
| 138 | --user-data-dir="$T/chrome" "file://$T/page.html" >"$T/chromium.log" 2>&1 & | 163 | --user-data-dir="$T/chrome" "file://$T/page.html" >"$T/chromium.log" 2>&1 & | ||
| 139 | - | "$T/neferwl" -s hints key Super+g --until "window-mapped app_id=chromium" | 164 | + | wait "$compositor" |
| 140 | - | read -r -p "Visible hint label: " label | |||
| 141 | - | "$T/neferwl" -s hints type "$label" | |||
| 142 | - | "$T/neferwl" -s hints shot | |||
| 143 | - | "$T/neferwl" -s hints shot --stop | |||
| 144 | - | "$T/neferwl" session rm hints | |||
| 145 | ' bash "$T" | 165 | ' bash "$T" | ||
| 146 | ``` | 166 | ``` | ||
| 147 | 167 | ||||
| 148 | All clients and state queries must run inside that wrapper shell so they share | 168 | All clients and state queries must run inside that wrapper shell so they share | ||
| 149 | its session bus as well as its Wayland display. Logs are in | 169 | its session bus as well as its Wayland display. Logs are in | ||
| 150 | - | `$T/state/neferwl/sessions/hints/latest.log`. | 170 | + | `$T/state/neferwl/runs/headless/latest.log`. |
| 151 | - | Prepare `$T/page.html` with underlined local links before running (the shell example also needs `jq`). OCR detects | 171 | + | Prepare `$T/page.html` with underlined local links before running. OCR detects |
| 152 | URL-like text without an underline and underlined link text; ordinary menu | 172 | URL-like text without an underline and underlined link text; ordinary menu | ||
| 153 | labels, buttons, separators and box borders do not produce OCR targets. Arrange both windows | 173 | labels, buttons, separators and box borders do not produce OCR targets. Arrange both windows | ||
| 154 | visibly; open a menu if possible. | 174 | visibly; open a menu if possible. | ||
| 155 | - | Wait for the clients to map, run `neferwl -s hints key Super+g`, then use | 175 | + | Script `sleep 8s`, `key Super+g`, `sleep 4s`, then `type <visible label>`. |
| 156 | - | `neferwl -s hints type <visible-label>` while the session is running. | |||
| 157 | Check screenshots before and after the click; a local link changing the page | 176 | Check screenshots before and after the click; a local link changing the page | ||
| 158 | background is a convenient observable result. | 177 | background is a convenient observable result. | ||
| 159 | 178 | ||||
| @@ -174,7 +193,7 @@ sources (startup rejects `hint.sources = ocr, ocr`). | |||||
| 174 | 193 | ||||
| 175 | ## OCR URL opening | 194 | ## OCR URL opening | ||
| 176 | 195 | ||||
| 177 | - | OCR targets with an http, https or mailto URL run `xdg-open` instead of a click. The recipe builds the binary, writes a minimal config, and puts a fake `xdg-open` first in `PATH`. It needs the hint prerequisites listed above. | 196 | + | OCR targets with an http, https or mailto URL run `xdg-open` instead of a click. The recipe builds the binary, writes a minimal config and input script, and puts a fake `xdg-open` first in `PATH`. It needs the hint prerequisites listed above. |
| 178 | 197 | ||||
| 179 | ```sh | 198 | ```sh | ||
| 180 | T=$(mktemp -d); mkdir "$T/bin" | 199 | T=$(mktemp -d); mkdir "$T/bin" | ||
| @@ -189,21 +208,12 @@ hint.sources = atspi, ocr | |||||
| 189 | bind.cmd+g = hint | 208 | bind.cmd+g = hint | ||
| 190 | bind.cmd+u = spawn foot -o main.font=monospace:size=28 $T/show.sh | 209 | bind.cmd+u = spawn foot -o main.font=monospace:size=28 $T/show.sh | ||
| 191 | EOF | 210 | EOF | ||
| 192 | - | PATH="$T/bin:$PATH" "$T/neferwl" session new --id ocr --config "$T/config" --ttl 60s -- --no-xwayland | 211 | + | printf 'sleep 1s\nkey Super+u\nsleep 4s\nkey Super+g\nsleep 4s\n' >"$T/input" |
| 193 | - | "$T/neferwl" -s ocr shot --every-frame --dir "$T/shots" | 212 | + | env -u NEFERWL_STATE -u NEFERWL_SLOT PATH="$T/bin:$PATH" "$T/neferwl" --backend=headless \ |
| 194 | - | "$T/neferwl" -s ocr key Super+u --until 'window-mapped app_id=foot' | 213 | + | --config "$T/config" --no-xwayland --screenshot "$T/shots" --input "$T/input" --timeout 20s |
| 195 | - | "$T/neferwl" -s ocr key Super+g | |||
| 196 | - | "$T/neferwl" -s ocr shot | |||
| 197 | - | # Read the visible hint label, then: | |||
| 198 | - | "$T/neferwl" -s ocr type '<label>' | |||
| 199 | - | "$T/neferwl" -s ocr shot --stop | |||
| 200 | - | "$T/neferwl" session rm ocr | |||
| 201 | ``` | 214 | ``` | ||
| 202 | 215 | ||||
| 203 | - | The foot window shows `https://example.com`. Typing its hint label opens that | 216 | + | The input script opens a large-font foot showing `https://example.com` and runs `hint`. Read the label from the screenshot, then append `type <label>` and a `sleep 2s` to `$T/input` and run again. `$T/opened` then holds exactly `https://example.com`. A `file:` target is clicked and leaves it empty. Launcher failures are in the log under `component=launcher`. |
| 204 | - | URL; `$T/opened` holds exactly `https://example.com`. A `file:` target is clicked | |||
| 205 | - | and leaves it empty. Launcher failures are in the session log under | |||
| 206 | - | `component=launcher`. | |||
| 207 | 217 | ||||
| 208 | ## Primary output coordinates | 218 | ## Primary output coordinates | ||
| 209 | 219 | ||||
| @@ -237,16 +247,13 @@ output.HEADLESS-2.right-of = HEADLESS-1 | |||||
| 237 | On the isolated headless display, `wayland-info -i wl_output` should report | 247 | On the isolated headless display, `wayland-info -i wl_output` should report | ||
| 238 | HEADLESS-1 at (-640,0) and HEADLESS-2 at (0,0). | 248 | HEADLESS-1 at (-640,0) and HEADLESS-2 at (0,0). | ||
| 239 | 249 | ||||
| 240 | - | ## Control input device | 250 | + | Scripted input announces device ID `1` with the fixed name `headless-script`. |
| 241 | - | 251 | + | Use `output.tv.input = headless-script` to test device-bound focus on a virtual | |
| 242 | - | Control input announces a device named `control` with ID | 252 | + | output. The script's `move` coordinates remain global logical coordinates. |
| 243 | - | `9223372036854775808`, which no real device uses. Use | |||
| 244 | - | `output.tv.input = control` to test device-bound focus on a virtual output. | |||
| 245 | - | Control `move` coordinates stay global logical coordinates. | |||
| 246 | - | ||||
| 247 | - | ## Session paths | |||
| 248 | 253 | ||||
| 249 | - | `$XDG_RUNTIME_DIR/neferwl/sessions/<id>/` holds `meta.json`, `control.sock`, | 254 | + | `device <id>` selects the scripted device for subsequent keys, motions, buttons |
| 250 | - | `state.json` and `shots/`. Logs live in | 255 | + | and gestures (positive integer; default `1`). A newly selected ID is announced |
| 251 | - | `$XDG_STATE_HOME/neferwl/sessions/<id>/`; the 20 most recent session log | 256 | + | once: ID `1` is `headless-script`, other IDs are `headless-script-<id>`. |
| 252 | - | directories are kept. | 257 | + | Devices share the scripted seat's keymap; release held keys before switching. |
| 258 | + | For example, bind `headless-script-2` to `tv`, then interleave `device 2`, | |||
| 259 | + | `key a`, `device 1`, `key a` to exercise bound/unbound focus switching. | |||
M docs/dev/index.md +1 -2
| @@ -3,7 +3,6 @@ | |||
| 3 | 3 | These guides cover NeferWL's internals and tools for development, testing and performance investigation. For configuration and desktop setup, see the [user documentation](../index.md). | |
| 4 | 4 | ||
| 5 | 5 | - [Architecture](architecture.md): owner goroutines, GC strategy and reusable purego libraries. | |
| 6 | - | - [Headless testing](headless.md): end-to-end recipe, demo recording, X11, colour and hint checks. | |
| 7 | - | - [Control protocol](control.md): wire messages, wait semantics, captures and error codes. | |
| 6 | + | - [Headless mode](headless.md): screenshots, scripted input and testing without a screen. | |
| 8 | 7 | - [Profiling](profiling.md): CPU and allocation profiling, logging and frame statistics. | |
| 9 | 8 | - [Repository rules](../../AGENTS.md): architecture constraints, test requirements and checks before merge. | |
| @@ -3,7 +3,6 @@ | |||||
| 3 | These guides cover NeferWL's internals and tools for development, testing and performance investigation. For configuration and desktop setup, see the [user documentation](../index.md). | 3 | These guides cover NeferWL's internals and tools for development, testing and performance investigation. For configuration and desktop setup, see the [user documentation](../index.md). | ||
| 4 | 4 | ||||
| 5 | - [Architecture](architecture.md): owner goroutines, GC strategy and reusable purego libraries. | 5 | - [Architecture](architecture.md): owner goroutines, GC strategy and reusable purego libraries. | ||
| 6 | - | - [Headless testing](headless.md): end-to-end recipe, demo recording, X11, colour and hint checks. | 6 | + | - [Headless mode](headless.md): screenshots, scripted input and testing without a screen. |
| 7 | - | - [Control protocol](control.md): wire messages, wait semantics, captures and error codes. | |||
| 8 | - [Profiling](profiling.md): CPU and allocation profiling, logging and frame statistics. | 7 | - [Profiling](profiling.md): CPU and allocation profiling, logging and frame statistics. | ||
| 9 | - [Repository rules](../../AGENTS.md): architecture constraints, test requirements and checks before merge. | 8 | - [Repository rules](../../AGENTS.md): architecture constraints, test requirements and checks before merge. | ||
M docs/dev/layouts.md +2 -1
| @@ -134,4 +134,5 @@ Required: `CGO_ENABLED=0 go build ./...`, `make check`, `make race`, | |||
| 134 | 134 | ||
| 135 | 135 | For end-to-end testing follow [headless.md](headless.md): a throwaway config per | |
| 136 | 136 | layout, several windows, focus/move on both axes, grow/shrink, maximize, | |
| 137 | - | overview and swipe, on an isolated session driven with `-s`. | |
| 137 | + | overview and swipe, with `WAYLAND_DISPLAY` isolated and `NEFERWL_STATE` and | |
| 138 | + | `NEFERWL_SLOT` unset. | |
| @@ -134,4 +134,5 @@ Required: `CGO_ENABLED=0 go build ./...`, `make check`, `make race`, | |||||
| 134 | 134 | ||||
| 135 | For end-to-end testing follow [headless.md](headless.md): a throwaway config per | 135 | For end-to-end testing follow [headless.md](headless.md): a throwaway config per | ||
| 136 | layout, several windows, focus/move on both axes, grow/shrink, maximize, | 136 | layout, several windows, focus/move on both axes, grow/shrink, maximize, | ||
| 137 | - | overview and swipe, on an isolated session driven with `-s`. | 137 | + | overview and swipe, with `WAYLAND_DISPLAY` isolated and `NEFERWL_STATE` and |
| 138 | + | `NEFERWL_SLOT` unset. | |||
M docs/index.md +2 -3
| @@ -1,12 +1,11 @@ | |||
| 1 | 1 | # NeferWL documentation | |
| 2 | 2 | ||
| 3 | - | NeferWL is a small Wayland compositor in Go. Start with Configuration to set up your keyboard, outputs and workflows, then use the guides below for desktop integration, screen capture, performance and headless use. | |
| 3 | + | NeferWL is a small Wayland compositor in Go. Start with Configuration to set up your keyboard, outputs and workflows, then use the guides below for desktop integration, screen capture and performance. | |
| 4 | 4 | ||
| 5 | 5 | - [Configuration](config.md): keys, actions, default bindings, layouts and HDR. | |
| 6 | 6 | - [Desktop integration](desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | |
| 7 | 7 | - [Screen capture](capture.md): protocols, indicator, executable allowlist and portals. | |
| 8 | 8 | - [Performance](performance.md): resource use, VRR and real-time priority. | |
| 9 | - | - [Headless and server mode](server.md): run NeferWL without a screen, as a long-running server or a game streaming host with Sunshine. | |
| 10 | - | - [Scripting and agents](control.md): sessions, actions, input, state and screenshots for scripts, tests and AI agents. | |
| 9 | + | - [Game server](server.md): `--backend=server` on a headless machine, streaming with Sunshine. | |
| 11 | 10 | ||
| 12 | 11 | Developer documentation: [docs/dev](dev/index.md) | |
| @@ -1,12 +1,11 @@ | |||||
| 1 | # NeferWL documentation | 1 | # NeferWL documentation | ||
| 2 | 2 | ||||
| 3 | - | NeferWL is a small Wayland compositor in Go. Start with Configuration to set up your keyboard, outputs and workflows, then use the guides below for desktop integration, screen capture, performance and headless use. | 3 | + | NeferWL is a small Wayland compositor in Go. Start with Configuration to set up your keyboard, outputs and workflows, then use the guides below for desktop integration, screen capture and performance. |
| 4 | 4 | ||||
| 5 | - [Configuration](config.md): keys, actions, default bindings, layouts and HDR. | 5 | - [Configuration](config.md): keys, actions, default bindings, layouts and HDR. | ||
| 6 | - [Desktop integration](desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | 6 | - [Desktop integration](desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting. | ||
| 7 | - [Screen capture](capture.md): protocols, indicator, executable allowlist and portals. | 7 | - [Screen capture](capture.md): protocols, indicator, executable allowlist and portals. | ||
| 8 | - [Performance](performance.md): resource use, VRR and real-time priority. | 8 | - [Performance](performance.md): resource use, VRR and real-time priority. | ||
| 9 | - | - [Headless and server mode](server.md): run NeferWL without a screen, as a long-running server or a game streaming host with Sunshine. | 9 | + | - [Game server](server.md): `--backend=server` on a headless machine, streaming with Sunshine. |
| 10 | - | - [Scripting and agents](control.md): sessions, actions, input, state and screenshots for scripts, tests and AI agents. | |||
| 11 | 10 | ||||
| 12 | Developer documentation: [docs/dev](dev/index.md) | 11 | Developer documentation: [docs/dev](dev/index.md) | ||
M docs/server.md +49 -137
| @@ -1,141 +1,22 @@ | |||
| 1 | - | # Headless and server mode | |
| 1 | + | # Game server | |
| 2 | 2 | ||
| 3 | - | `neferwl --backend=headless` runs the compositor without a screen. Apps connect | |
| 4 | - | to its Wayland display as usual and draw into virtual outputs, which you can | |
| 5 | - | stream, record or capture. Use it for a game streaming host, a remote desktop | |
| 6 | - | box, demo recordings or tests in CI. | |
| 3 | + | `neferwl --backend=server` runs NeferWL without a display: it drives only the virtual outputs declared in the config, reads input devices directly and serves screen casting on the session bus. With [Sunshine](https://github.com/LizardByte/Sunshine), it turns a headless machine into a game streaming host. | |
| 7 | 4 | ||
| 8 | - | ## Profiles | |
| 5 | + | Server mode differs from a desktop session: | |
| 9 | 6 | ||
| 10 | - | | | `ephemeral` (default) | `persistent` | | |
| 11 | - | |---|---|---| | |
| 12 | - | | Use | Throwaway sessions: tests, scripts, agents, recordings | A long-running server | | |
| 13 | - | | Outputs | `--size` heads (`HEADLESS-1`, default 1920x1080); config virtual outputs stay isolated | Virtual outputs from the config | | |
| 14 | - | | Input devices | None; input comes from the [control socket](control.md) | Reads `/dev/input/event*` directly | | |
| 15 | - | | `--input-devices` | `grab` reads devices too | `none` reads none | | |
| 16 | - | | Screen casting and screensaver D-Bus services | Only with `--dbus` | Always | | |
| 17 | - | | Scale changes | Not saved | Saved to the config | | |
| 18 | - | | Terminal at startup | Opens | None | | |
| 19 | - | | GPU | Any Vulkan device | A DRM render node; software rasterizers are refused | | |
| 7 | + | - No DRM/KMS and no logind session: no physical output lights up, and no VT is taken. | |
| 8 | + | - Virtual outputs are laid out left to right in config order, starting at 0,0. They take the startup focus and every pointer reaches them, so they are not isolated as on a desktop. | |
| 9 | + | - The screen-casting and screensaver D-Bus services always run. The logind power-key lock does not. | |
| 10 | + | - No terminal opens at startup. Scale changes are saved to the config, as on a desktop. | |
| 11 | + | - The test flags (`--screenshot`, `--screenshot-raw`, `--input`, `--size`, `--timeout`, `--headless-hdr`, `--dbus`) are rejected. | |
| 20 | 12 | ||
| 21 | - | Both profiles have no DRM/KMS and no logind session: no physical output lights | |
| 22 | - | up, no VT is taken and the logind power keys are not handled. Both register a | |
| 23 | - | session with a control socket, so [`neferwl -s ID ...`](control.md) works on | |
| 24 | - | either. A session ends on `neferwl session rm ID`, on SIGINT or SIGTERM, on the | |
| 25 | - | `quit` action, or when `--timeout` runs out (`--ttl` for `session new`). | |
| 13 | + | ## Requirements | |
| 26 | 14 | ||
| 27 | - | In the persistent profile, virtual outputs are laid out left to right in config | |
| 28 | - | order from 0,0. They take the startup focus and every pointer reaches them, | |
| 29 | - | unlike virtual outputs on a desktop. `--size` also creates fixed `HEADLESS-N` | |
| 30 | - | heads. | |
| 31 | - | ||
| 32 | - | `--backend=server` is a deprecated alias for | |
| 33 | - | `--backend=headless --profile=persistent`. | |
| 34 | - | ||
| 35 | - | ## Run it | |
| 36 | - | ||
| 37 | - | Declare at least one virtual output in `~/.config/neferwl/config`: | |
| 38 | - | ||
| 39 | - | ```ini | |
| 40 | - | output.tv = virtual 1920x1080@60 | |
| 41 | - | startup = foot | |
| 42 | - | ``` | |
| 43 | - | ||
| 44 | - | See [Virtual outputs](config.md#virtual-outputs) for modes, HDR and placement. | |
| 45 | - | Then start the compositor by hand, for example over SSH: | |
| 46 | - | ||
| 47 | - | ```sh | |
| 48 | - | neferwl --backend=headless --profile=persistent --session-id=box | |
| 49 | - | ``` | |
| 50 | - | ||
| 51 | - | or as the systemd user service: | |
| 52 | - | ||
| 53 | - | ```sh | |
| 54 | - | systemctl --user enable --now neferwl-server.service | |
| 55 | - | ``` | |
| 56 | - | ||
| 57 | - | The service runs `neferwl --backend=headless --profile=persistent --session --session-id=server`. | |
| 58 | - | It notifies systemd when ready, exports `WAYLAND_DISPLAY` and `DISPLAY` to the | |
| 59 | - | user manager, binds `graphical-session.target` and restarts on failure. It | |
| 60 | - | conflicts with `neferwl.service`, so it never runs beside a desktop session. | |
| 61 | - | Starting it from a desktop session hands the graphical session over to the | |
| 62 | - | server instead of tearing it down. A clean server exit removes its display | |
| 63 | - | variables and stops its portals; a server crash leaves them in place. | |
| 64 | - | ||
| 65 | - | Programs started by the compositor (`startup`, binds, `do spawn`) already have | |
| 66 | - | the right environment. To start a client yourself, take the display from the | |
| 67 | - | session list or from the user manager: | |
| 68 | - | ||
| 69 | - | ```sh | |
| 70 | - | neferwl session ls # WAYLAND column | |
| 71 | - | export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|DISPLAY|XDG_RUNTIME_DIR)=') | |
| 72 | - | firefox & | |
| 73 | - | ``` | |
| 74 | - | ||
| 75 | - | Logs are in `$XDG_STATE_HOME/neferwl/sessions/<id>/latest.log` with `--session-id`, else in `$XDG_STATE_HOME/neferwl/runs/headless/latest.log`. | |
| 76 | - | ||
| 77 | - | ## Watch and control it | |
| 78 | - | ||
| 79 | - | - **Streaming and recording**: the screen-casting portal shares each virtual | |
| 80 | - | output with [Sunshine](#game-streaming-with-sunshine), OBS or any PipeWire | |
| 81 | - | client. It needs PipeWire, `xdg-desktop-portal` and | |
| 82 | - | `xdg-desktop-portal-gnome` with the packaged `neferwl-portals.conf`; see | |
| 83 | - | [Portals](capture.md#portals). | |
| 84 | - | - **Screenshots**: `neferwl -s server shot --output tv` writes a PNG and prints | |
| 85 | - | its path. `grim -o tv` works too once its executable is in | |
| 86 | - | [the allowlist](capture.md#the-allowlist). | |
| 87 | - | - **Remote desktop**: [wayvnc](#wayvnc) gives a VNC view with keyboard and | |
| 88 | - | pointer. | |
| 89 | - | - **Scripts and agents**: actions, input, state and captures through the | |
| 90 | - | control socket; see [Scripting and agents](control.md). | |
| 91 | - | ||
| 92 | - | ```sh | |
| 93 | - | neferwl -s server state | jq '.windows[] | {id, app_id}' | |
| 94 | - | neferwl -s server do focus-workspace-next | |
| 95 | - | neferwl -s server key Super+Return --until 'window-mapped app_id=foot' | |
| 96 | - | neferwl -s server shot --output tv | |
| 97 | - | ``` | |
| 98 | - | ||
| 99 | - | ### Virtual pointer | |
| 100 | - | ||
| 101 | - | Tools using `zwlr_virtual_pointer_v1` move the pointer like a real mouse, so | |
| 102 | - | focus, hover and drags behave as they would for a person. Run them with the | |
| 103 | - | session's `WAYLAND_DISPLAY`: | |
| 104 | - | ||
| 105 | - | ```sh | |
| 106 | - | neferwl pointer abs 0.5 0.5 click | |
| 107 | - | neferwl pointer move 200 -50 click right | |
| 108 | - | ``` | |
| 109 | - | ||
| 110 | - | - `neferwl pointer` actions: `abs X Y` (fractions 0..1 of the layout, or of one output with `--output <name>`), `move DX DY`, `press`/`release`/`click [BTN]`, `hold [BTN] [DURATION]`, `drag DX DY [BTN]` and `scroll up|down|left|right [N]`. BTN is `left` (default), `right`, `middle`, `side`, `extra`, `forward`, `back`, a `BTN_*` name or an evdev code. `--click-duration` (20ms), `--hold-duration` (500ms), `--drag-steps` (10) and `--drag-step-delay` (10ms) tune the timing. Buttons still pressed at exit are released. See `neferwl pointer --help`. | |
| 111 | - | - [wlrctl](https://git.sr.ht/~brocellous/wlrctl) (AUR: `wlrctl`) works too: `wlrctl pointer move 200 -50`, `wlrctl pointer click left`. | |
| 112 | - | - Absolute motion maps into the whole layout, or into one output when the tool binds it (`create_virtual_pointer_with_output`). | |
| 113 | - | - `ydotool` writes to `/dev/uinput` through `ydotoold` and does not use this protocol; prefer `neferwl pointer`. | |
| 114 | - | - Nothing is injected while the session is locked. Buttons a tool still held when it disconnects are released. | |
| 115 | - | - Flatpak and other sandboxed clients (those on a `wp_security_context_v1` socket) do not see the virtual pointer global. | |
| 116 | - | ||
| 117 | - | ### wayvnc | |
| 118 | - | ||
| 119 | - | [wayvnc](https://github.com/any1/wayvnc) captures an output with wlr-screencopy and injects input through the virtual pointer and keyboard. Add its executable (`/usr/bin/wayvnc`) to `/etc/neferwl/capture-allow`, then run it in the session: | |
| 120 | - | ||
| 121 | - | ```sh | |
| 122 | - | wayvnc -o tv 127.0.0.1 5900 | |
| 123 | - | ``` | |
| 124 | - | ||
| 125 | - | Keep it on localhost and reach it through an SSH tunnel, or configure wayvnc's own authentication and TLS. | |
| 126 | - | ||
| 127 | - | ## Game streaming with Sunshine | |
| 128 | - | ||
| 129 | - | With [Sunshine](https://github.com/LizardByte/Sunshine), a persistent session | |
| 130 | - | turns a machine without a screen into a game streaming host for Moonlight. | |
| 131 | - | ||
| 132 | - | ### Requirements | |
| 133 | - | ||
| 134 | - | - A GPU with a DRM render node (`/dev/dri/renderD*`). | |
| 15 | + | - A GPU with a DRM render node (`/dev/dri/renderD*`). Software rasterizers such as lavapipe are refused. | |
| 135 | 16 | - PipeWire, `xdg-desktop-portal` and `xdg-desktop-portal-gnome`, with the packaged `neferwl-portals.conf` (see [Portals](capture.md#portals)). | |
| 136 | 17 | - Sunshine with portal capture. | |
| 137 | 18 | ||
| 138 | - | ### Account setup | |
| 19 | + | ## Account setup | |
| 139 | 20 | ||
| 140 | 21 | The user service runs without anyone logged in: | |
| 141 | 22 | ||
| @@ -153,7 +34,7 @@ Log out and back in (or reboot) to apply. | |||
| 153 | 34 | ||
| 154 | 35 | **Security.** Membership in `input` lets every program of that user read every keyboard of the machine: it is the same as a keylogger. NeferWL grabs each device exclusively (`EVIOCGRAB`), so a local keyboard types into the server session, not into a console or another session. A device it cannot grab (another program already holds it) is skipped and logged as `input device skipped`. Use a dedicated account, and never run server mode while a desktop NeferWL session is running on the same machine: `neferwl-server.service` conflicts with `neferwl.service` for that reason. | |
| 155 | 36 | ||
| 156 | - | ### Configuration | |
| 37 | + | ## Configuration | |
| 157 | 38 | ||
| 158 | 39 | `~/.config/neferwl/config`: | |
| 159 | 40 | ||
| @@ -167,14 +48,16 @@ startup = steam -gamepadui | |||
| 167 | 48 | ||
| 168 | 49 | Check it with `neferwl validate-config`. See [Virtual outputs](config.md#virtual-outputs) and [GPUs](config.md#gpus). | |
| 169 | 50 | ||
| 170 | - | ### Services | |
| 51 | + | ## Services | |
| 171 | 52 | ||
| 172 | 53 | ```sh | |
| 173 | 54 | systemctl --user enable --now neferwl-server.service | |
| 174 | 55 | systemctl --user enable --now sunshine.service | |
| 175 | 56 | ``` | |
| 176 | 57 | ||
| 177 | - | `neferwl-server.service` binds `graphical-session.target`, so Sunshine and the portals start in the right environment. | |
| 58 | + | `neferwl-server.service` starts `neferwl --backend=server --session`, notifies systemd when ready, exports `WAYLAND_DISPLAY` and `DISPLAY` to the user manager and restarts on failure. It binds `graphical-session.target`, so Sunshine and the portals start in the right environment. | |
| 59 | + | ||
| 60 | + | ## Sunshine | |
| 178 | 61 | ||
| 179 | 62 | `~/.config/sunshine/sunshine.conf`: | |
| 180 | 63 | ||
| @@ -188,7 +71,7 @@ To match the client's resolution and refresh rate, change the virtual output's m | |||
| 188 | 71 | global_prep_cmd = [{"do":"sh -c \"wlr-randr --output tv --custom-mode ${SUNSHINE_CLIENT_WIDTH}x${SUNSHINE_CLIENT_HEIGHT}@${SUNSHINE_CLIENT_FPS}\"","undo":"wlr-randr --output tv --custom-mode 1920x1080@60"}] | |
| 189 | 72 | ``` | |
| 190 | 73 | ||
| 191 | - | ### First portal approval | |
| 74 | + | ## First portal approval | |
| 192 | 75 | ||
| 193 | 76 | The first time Sunshine captures, the portal shows its share dialog on `tv`, with nobody in front of the screen. Accept it once over SSH: | |
| 194 | 77 | ||
| @@ -200,17 +83,46 @@ ydotool key 28:1 28:0 # Return accepts the selected output | |||
| 200 | 83 | ||
| 201 | 84 | Move the selection with Tab (`15:1 15:0`) if needed, and take another screenshot to check. The portal gives Sunshine a restore token: later streams start without the dialog, as long as the output keeps its name. | |
| 202 | 85 | ||
| 203 | - | ### HDR | |
| 86 | + | ## HDR | |
| 204 | 87 | ||
| 205 | 88 | With `output.tv.hdr = on`, the output is HDR (PQ/BT.2020, reported as a 1000-nit display) and the cast offers 10-bit PQ first. Enable HDR in the Moonlight client and in the game. If the renderer cannot do HDR, the output falls back to SDR and the log says why. See [HDR](config.md#hdr) and [Screen capture](capture.md#portals). | |
| 206 | 89 | ||
| 207 | - | ### Input | |
| 90 | + | ## Input | |
| 208 | 91 | ||
| 209 | 92 | Moonlight's keyboard, mouse and gamepads reach the host through Sunshine's virtual devices. Keyboard and mouse events go through NeferWL to the focused window. Gamepads go straight to games: NeferWL does not handle them. | |
| 210 | 93 | ||
| 211 | 94 | Steam's controller rules grant access through `uaccess`, which needs a logind seat. Server mode has none, so the `input` group is what gives Steam its gamepads. | |
| 212 | 95 | ||
| 213 | - | ### Hardening | |
| 96 | + | ## Controlling a NeferWL session (agents) | |
| 97 | + | ||
| 98 | + | An agent or script on the host can watch the session and drive it with standard Wayland tools. Run them as the session user with the session's display: | |
| 99 | + | ||
| 100 | + | ```sh | |
| 101 | + | export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=') | |
| 102 | + | grim -o tv /tmp/screen.png # capture one output (see Screen capture) | |
| 103 | + | neferwl pointer abs 0.5 0.5 click # click the middle of the layout | |
| 104 | + | neferwl pointer move 200 -50 click right # actions run in order | |
| 105 | + | wtype 'hello' # type into the focused window | |
| 106 | + | neferwl state # windows, focus, outputs as JSON | |
| 107 | + | ``` | |
| 108 | + | ||
| 109 | + | - `neferwl pointer` actions: `abs X Y` (fractions 0..1 of the layout, or of one output with `--output <name>`), `move DX DY`, `press`/`release`/`click [BTN]`, `hold [BTN] [DURATION]`, `drag DX DY [BTN]` and `scroll up|down|left|right [N]`. BTN is `left` (default), `right`, `middle`, `side`, `extra`, `forward`, `back`, a `BTN_*` name or an evdev code. `--click-duration` (20ms), `--hold-duration` (500ms), `--drag-steps` (10) and `--drag-step-delay` (10ms) tune the timing. Buttons still pressed at exit are released. See `neferwl pointer --help`. | |
| 110 | + | - [wlrctl](https://git.sr.ht/~brocellous/wlrctl) (AUR: `wlrctl`) works too: `wlrctl pointer move 200 -50`, `wlrctl pointer click left`. | |
| 111 | + | - Both use `zwlr_virtual_pointer_v1`. NeferWL routes their events like a real mouse, so focus, hover and drags behave as they would for a person. Absolute motion maps into the whole layout, or into one output when the tool binds it (`create_virtual_pointer_with_output`). | |
| 112 | + | - `ydotool` writes to `/dev/uinput` through `ydotoold` and does not use this protocol; prefer `neferwl pointer`. | |
| 113 | + | - Nothing is injected while the session is locked. Buttons a tool still held when it disconnects are released. | |
| 114 | + | - Flatpak and other sandboxed clients (those on a `wp_security_context_v1` socket) do not see the virtual pointer global. | |
| 115 | + | - `grim` needs the capture allowlist to admit it; see [the allowlist](capture.md#the-allowlist). | |
| 116 | + | ||
| 117 | + | [wayvnc](https://github.com/any1/wayvnc) works for remote viewing and control: it captures an output with wlr-screencopy and injects input through the virtual pointer and keyboard. Add its executable (`/usr/bin/wayvnc`) to `/etc/neferwl/capture-allow`, then run it in the session: | |
| 118 | + | ||
| 119 | + | ```sh | |
| 120 | + | wayvnc -o tv 127.0.0.1 5900 | |
| 121 | + | ``` | |
| 122 | + | ||
| 123 | + | Keep it on localhost and reach it through an SSH tunnel, or configure wayvnc's own authentication and TLS. | |
| 124 | + | ||
| 125 | + | ## Hardening | |
| 214 | 126 | ||
| 215 | 127 | On a dedicated box, a local keyboard should not reboot or reach a console: | |
| 216 | 128 | ||
| @@ -1,141 +1,22 @@ | |||||
| 1 | - | # Headless and server mode | 1 | + | # Game server |
| 2 | 2 | ||||
| 3 | - | `neferwl --backend=headless` runs the compositor without a screen. Apps connect | 3 | + | `neferwl --backend=server` runs NeferWL without a display: it drives only the virtual outputs declared in the config, reads input devices directly and serves screen casting on the session bus. With [Sunshine](https://github.com/LizardByte/Sunshine), it turns a headless machine into a game streaming host. |
| 4 | - | to its Wayland display as usual and draw into virtual outputs, which you can | |||
| 5 | - | stream, record or capture. Use it for a game streaming host, a remote desktop | |||
| 6 | - | box, demo recordings or tests in CI. | |||
| 7 | 4 | ||||
| 8 | - | ## Profiles | 5 | + | Server mode differs from a desktop session: |
| 9 | 6 | ||||
| 10 | - | | | `ephemeral` (default) | `persistent` | | 7 | + | - No DRM/KMS and no logind session: no physical output lights up, and no VT is taken. |
| 11 | - | |---|---|---| | 8 | + | - Virtual outputs are laid out left to right in config order, starting at 0,0. They take the startup focus and every pointer reaches them, so they are not isolated as on a desktop. |
| 12 | - | | Use | Throwaway sessions: tests, scripts, agents, recordings | A long-running server | | 9 | + | - The screen-casting and screensaver D-Bus services always run. The logind power-key lock does not. |
| 13 | - | | Outputs | `--size` heads (`HEADLESS-1`, default 1920x1080); config virtual outputs stay isolated | Virtual outputs from the config | | 10 | + | - No terminal opens at startup. Scale changes are saved to the config, as on a desktop. |
| 14 | - | | Input devices | None; input comes from the [control socket](control.md) | Reads `/dev/input/event*` directly | | 11 | + | - The test flags (`--screenshot`, `--screenshot-raw`, `--input`, `--size`, `--timeout`, `--headless-hdr`, `--dbus`) are rejected. |
| 15 | - | | `--input-devices` | `grab` reads devices too | `none` reads none | | |||
| 16 | - | | Screen casting and screensaver D-Bus services | Only with `--dbus` | Always | | |||
| 17 | - | | Scale changes | Not saved | Saved to the config | | |||
| 18 | - | | Terminal at startup | Opens | None | | |||
| 19 | - | | GPU | Any Vulkan device | A DRM render node; software rasterizers are refused | | |||
| 20 | 12 | ||||
| 21 | - | Both profiles have no DRM/KMS and no logind session: no physical output lights | 13 | + | ## Requirements |
| 22 | - | up, no VT is taken and the logind power keys are not handled. Both register a | |||
| 23 | - | session with a control socket, so [`neferwl -s ID ...`](control.md) works on | |||
| 24 | - | either. A session ends on `neferwl session rm ID`, on SIGINT or SIGTERM, on the | |||
| 25 | - | `quit` action, or when `--timeout` runs out (`--ttl` for `session new`). | |||
| 26 | 14 | ||||
| 27 | - | In the persistent profile, virtual outputs are laid out left to right in config | 15 | + | - A GPU with a DRM render node (`/dev/dri/renderD*`). Software rasterizers such as lavapipe are refused. |
| 28 | - | order from 0,0. They take the startup focus and every pointer reaches them, | |||
| 29 | - | unlike virtual outputs on a desktop. `--size` also creates fixed `HEADLESS-N` | |||
| 30 | - | heads. | |||
| 31 | - | ||||
| 32 | - | `--backend=server` is a deprecated alias for | |||
| 33 | - | `--backend=headless --profile=persistent`. | |||
| 34 | - | ||||
| 35 | - | ## Run it | |||
| 36 | - | ||||
| 37 | - | Declare at least one virtual output in `~/.config/neferwl/config`: | |||
| 38 | - | ||||
| 39 | - | ```ini | |||
| 40 | - | output.tv = virtual 1920x1080@60 | |||
| 41 | - | startup = foot | |||
| 42 | - | ``` | |||
| 43 | - | ||||
| 44 | - | See [Virtual outputs](config.md#virtual-outputs) for modes, HDR and placement. | |||
| 45 | - | Then start the compositor by hand, for example over SSH: | |||
| 46 | - | ||||
| 47 | - | ```sh | |||
| 48 | - | neferwl --backend=headless --profile=persistent --session-id=box | |||
| 49 | - | ``` | |||
| 50 | - | ||||
| 51 | - | or as the systemd user service: | |||
| 52 | - | ||||
| 53 | - | ```sh | |||
| 54 | - | systemctl --user enable --now neferwl-server.service | |||
| 55 | - | ``` | |||
| 56 | - | ||||
| 57 | - | The service runs `neferwl --backend=headless --profile=persistent --session --session-id=server`. | |||
| 58 | - | It notifies systemd when ready, exports `WAYLAND_DISPLAY` and `DISPLAY` to the | |||
| 59 | - | user manager, binds `graphical-session.target` and restarts on failure. It | |||
| 60 | - | conflicts with `neferwl.service`, so it never runs beside a desktop session. | |||
| 61 | - | Starting it from a desktop session hands the graphical session over to the | |||
| 62 | - | server instead of tearing it down. A clean server exit removes its display | |||
| 63 | - | variables and stops its portals; a server crash leaves them in place. | |||
| 64 | - | ||||
| 65 | - | Programs started by the compositor (`startup`, binds, `do spawn`) already have | |||
| 66 | - | the right environment. To start a client yourself, take the display from the | |||
| 67 | - | session list or from the user manager: | |||
| 68 | - | ||||
| 69 | - | ```sh | |||
| 70 | - | neferwl session ls # WAYLAND column | |||
| 71 | - | export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|DISPLAY|XDG_RUNTIME_DIR)=') | |||
| 72 | - | firefox & | |||
| 73 | - | ``` | |||
| 74 | - | ||||
| 75 | - | Logs are in `$XDG_STATE_HOME/neferwl/sessions/<id>/latest.log` with `--session-id`, else in `$XDG_STATE_HOME/neferwl/runs/headless/latest.log`. | |||
| 76 | - | ||||
| 77 | - | ## Watch and control it | |||
| 78 | - | ||||
| 79 | - | - **Streaming and recording**: the screen-casting portal shares each virtual | |||
| 80 | - | output with [Sunshine](#game-streaming-with-sunshine), OBS or any PipeWire | |||
| 81 | - | client. It needs PipeWire, `xdg-desktop-portal` and | |||
| 82 | - | `xdg-desktop-portal-gnome` with the packaged `neferwl-portals.conf`; see | |||
| 83 | - | [Portals](capture.md#portals). | |||
| 84 | - | - **Screenshots**: `neferwl -s server shot --output tv` writes a PNG and prints | |||
| 85 | - | its path. `grim -o tv` works too once its executable is in | |||
| 86 | - | [the allowlist](capture.md#the-allowlist). | |||
| 87 | - | - **Remote desktop**: [wayvnc](#wayvnc) gives a VNC view with keyboard and | |||
| 88 | - | pointer. | |||
| 89 | - | - **Scripts and agents**: actions, input, state and captures through the | |||
| 90 | - | control socket; see [Scripting and agents](control.md). | |||
| 91 | - | ||||
| 92 | - | ```sh | |||
| 93 | - | neferwl -s server state | jq '.windows[] | {id, app_id}' | |||
| 94 | - | neferwl -s server do focus-workspace-next | |||
| 95 | - | neferwl -s server key Super+Return --until 'window-mapped app_id=foot' | |||
| 96 | - | neferwl -s server shot --output tv | |||
| 97 | - | ``` | |||
| 98 | - | ||||
| 99 | - | ### Virtual pointer | |||
| 100 | - | ||||
| 101 | - | Tools using `zwlr_virtual_pointer_v1` move the pointer like a real mouse, so | |||
| 102 | - | focus, hover and drags behave as they would for a person. Run them with the | |||
| 103 | - | session's `WAYLAND_DISPLAY`: | |||
| 104 | - | ||||
| 105 | - | ```sh | |||
| 106 | - | neferwl pointer abs 0.5 0.5 click | |||
| 107 | - | neferwl pointer move 200 -50 click right | |||
| 108 | - | ``` | |||
| 109 | - | ||||
| 110 | - | - `neferwl pointer` actions: `abs X Y` (fractions 0..1 of the layout, or of one output with `--output <name>`), `move DX DY`, `press`/`release`/`click [BTN]`, `hold [BTN] [DURATION]`, `drag DX DY [BTN]` and `scroll up|down|left|right [N]`. BTN is `left` (default), `right`, `middle`, `side`, `extra`, `forward`, `back`, a `BTN_*` name or an evdev code. `--click-duration` (20ms), `--hold-duration` (500ms), `--drag-steps` (10) and `--drag-step-delay` (10ms) tune the timing. Buttons still pressed at exit are released. See `neferwl pointer --help`. | |||
| 111 | - | - [wlrctl](https://git.sr.ht/~brocellous/wlrctl) (AUR: `wlrctl`) works too: `wlrctl pointer move 200 -50`, `wlrctl pointer click left`. | |||
| 112 | - | - Absolute motion maps into the whole layout, or into one output when the tool binds it (`create_virtual_pointer_with_output`). | |||
| 113 | - | - `ydotool` writes to `/dev/uinput` through `ydotoold` and does not use this protocol; prefer `neferwl pointer`. | |||
| 114 | - | - Nothing is injected while the session is locked. Buttons a tool still held when it disconnects are released. | |||
| 115 | - | - Flatpak and other sandboxed clients (those on a `wp_security_context_v1` socket) do not see the virtual pointer global. | |||
| 116 | - | ||||
| 117 | - | ### wayvnc | |||
| 118 | - | ||||
| 119 | - | [wayvnc](https://github.com/any1/wayvnc) captures an output with wlr-screencopy and injects input through the virtual pointer and keyboard. Add its executable (`/usr/bin/wayvnc`) to `/etc/neferwl/capture-allow`, then run it in the session: | |||
| 120 | - | ||||
| 121 | - | ```sh | |||
| 122 | - | wayvnc -o tv 127.0.0.1 5900 | |||
| 123 | - | ``` | |||
| 124 | - | ||||
| 125 | - | Keep it on localhost and reach it through an SSH tunnel, or configure wayvnc's own authentication and TLS. | |||
| 126 | - | ||||
| 127 | - | ## Game streaming with Sunshine | |||
| 128 | - | ||||
| 129 | - | With [Sunshine](https://github.com/LizardByte/Sunshine), a persistent session | |||
| 130 | - | turns a machine without a screen into a game streaming host for Moonlight. | |||
| 131 | - | ||||
| 132 | - | ### Requirements | |||
| 133 | - | ||||
| 134 | - | - A GPU with a DRM render node (`/dev/dri/renderD*`). | |||
| 135 | - PipeWire, `xdg-desktop-portal` and `xdg-desktop-portal-gnome`, with the packaged `neferwl-portals.conf` (see [Portals](capture.md#portals)). | 16 | - PipeWire, `xdg-desktop-portal` and `xdg-desktop-portal-gnome`, with the packaged `neferwl-portals.conf` (see [Portals](capture.md#portals)). | ||
| 136 | - Sunshine with portal capture. | 17 | - Sunshine with portal capture. | ||
| 137 | 18 | ||||
| 138 | - | ### Account setup | 19 | + | ## Account setup |
| 139 | 20 | ||||
| 140 | The user service runs without anyone logged in: | 21 | The user service runs without anyone logged in: | ||
| 141 | 22 | ||||
| @@ -153,7 +34,7 @@ Log out and back in (or reboot) to apply. | |||||
| 153 | 34 | ||||
| 154 | **Security.** Membership in `input` lets every program of that user read every keyboard of the machine: it is the same as a keylogger. NeferWL grabs each device exclusively (`EVIOCGRAB`), so a local keyboard types into the server session, not into a console or another session. A device it cannot grab (another program already holds it) is skipped and logged as `input device skipped`. Use a dedicated account, and never run server mode while a desktop NeferWL session is running on the same machine: `neferwl-server.service` conflicts with `neferwl.service` for that reason. | 35 | **Security.** Membership in `input` lets every program of that user read every keyboard of the machine: it is the same as a keylogger. NeferWL grabs each device exclusively (`EVIOCGRAB`), so a local keyboard types into the server session, not into a console or another session. A device it cannot grab (another program already holds it) is skipped and logged as `input device skipped`. Use a dedicated account, and never run server mode while a desktop NeferWL session is running on the same machine: `neferwl-server.service` conflicts with `neferwl.service` for that reason. | ||
| 155 | 36 | ||||
| 156 | - | ### Configuration | 37 | + | ## Configuration |
| 157 | 38 | ||||
| 158 | `~/.config/neferwl/config`: | 39 | `~/.config/neferwl/config`: | ||
| 159 | 40 | ||||
| @@ -167,14 +48,16 @@ startup = steam -gamepadui | |||||
| 167 | 48 | ||||
| 168 | Check it with `neferwl validate-config`. See [Virtual outputs](config.md#virtual-outputs) and [GPUs](config.md#gpus). | 49 | Check it with `neferwl validate-config`. See [Virtual outputs](config.md#virtual-outputs) and [GPUs](config.md#gpus). | ||
| 169 | 50 | ||||
| 170 | - | ### Services | 51 | + | ## Services |
| 171 | 52 | ||||
| 172 | ```sh | 53 | ```sh | ||
| 173 | systemctl --user enable --now neferwl-server.service | 54 | systemctl --user enable --now neferwl-server.service | ||
| 174 | systemctl --user enable --now sunshine.service | 55 | systemctl --user enable --now sunshine.service | ||
| 175 | ``` | 56 | ``` | ||
| 176 | 57 | ||||
| 177 | - | `neferwl-server.service` binds `graphical-session.target`, so Sunshine and the portals start in the right environment. | 58 | + | `neferwl-server.service` starts `neferwl --backend=server --session`, notifies systemd when ready, exports `WAYLAND_DISPLAY` and `DISPLAY` to the user manager and restarts on failure. It binds `graphical-session.target`, so Sunshine and the portals start in the right environment. |
| 59 | + | ||||
| 60 | + | ## Sunshine | |||
| 178 | 61 | ||||
| 179 | `~/.config/sunshine/sunshine.conf`: | 62 | `~/.config/sunshine/sunshine.conf`: | ||
| 180 | 63 | ||||
| @@ -188,7 +71,7 @@ To match the client's resolution and refresh rate, change the virtual output's m | |||||
| 188 | global_prep_cmd = [{"do":"sh -c \"wlr-randr --output tv --custom-mode ${SUNSHINE_CLIENT_WIDTH}x${SUNSHINE_CLIENT_HEIGHT}@${SUNSHINE_CLIENT_FPS}\"","undo":"wlr-randr --output tv --custom-mode 1920x1080@60"}] | 71 | global_prep_cmd = [{"do":"sh -c \"wlr-randr --output tv --custom-mode ${SUNSHINE_CLIENT_WIDTH}x${SUNSHINE_CLIENT_HEIGHT}@${SUNSHINE_CLIENT_FPS}\"","undo":"wlr-randr --output tv --custom-mode 1920x1080@60"}] | ||
| 189 | ``` | 72 | ``` | ||
| 190 | 73 | ||||
| 191 | - | ### First portal approval | 74 | + | ## First portal approval |
| 192 | 75 | ||||
| 193 | The first time Sunshine captures, the portal shows its share dialog on `tv`, with nobody in front of the screen. Accept it once over SSH: | 76 | The first time Sunshine captures, the portal shows its share dialog on `tv`, with nobody in front of the screen. Accept it once over SSH: | ||
| 194 | 77 | ||||
| @@ -200,17 +83,46 @@ ydotool key 28:1 28:0 # Return accepts the selected output | |||||
| 200 | 83 | ||||
| 201 | Move the selection with Tab (`15:1 15:0`) if needed, and take another screenshot to check. The portal gives Sunshine a restore token: later streams start without the dialog, as long as the output keeps its name. | 84 | Move the selection with Tab (`15:1 15:0`) if needed, and take another screenshot to check. The portal gives Sunshine a restore token: later streams start without the dialog, as long as the output keeps its name. | ||
| 202 | 85 | ||||
| 203 | - | ### HDR | 86 | + | ## HDR |
| 204 | 87 | ||||
| 205 | With `output.tv.hdr = on`, the output is HDR (PQ/BT.2020, reported as a 1000-nit display) and the cast offers 10-bit PQ first. Enable HDR in the Moonlight client and in the game. If the renderer cannot do HDR, the output falls back to SDR and the log says why. See [HDR](config.md#hdr) and [Screen capture](capture.md#portals). | 88 | With `output.tv.hdr = on`, the output is HDR (PQ/BT.2020, reported as a 1000-nit display) and the cast offers 10-bit PQ first. Enable HDR in the Moonlight client and in the game. If the renderer cannot do HDR, the output falls back to SDR and the log says why. See [HDR](config.md#hdr) and [Screen capture](capture.md#portals). | ||
| 206 | 89 | ||||
| 207 | - | ### Input | 90 | + | ## Input |
| 208 | 91 | ||||
| 209 | Moonlight's keyboard, mouse and gamepads reach the host through Sunshine's virtual devices. Keyboard and mouse events go through NeferWL to the focused window. Gamepads go straight to games: NeferWL does not handle them. | 92 | Moonlight's keyboard, mouse and gamepads reach the host through Sunshine's virtual devices. Keyboard and mouse events go through NeferWL to the focused window. Gamepads go straight to games: NeferWL does not handle them. | ||
| 210 | 93 | ||||
| 211 | Steam's controller rules grant access through `uaccess`, which needs a logind seat. Server mode has none, so the `input` group is what gives Steam its gamepads. | 94 | Steam's controller rules grant access through `uaccess`, which needs a logind seat. Server mode has none, so the `input` group is what gives Steam its gamepads. | ||
| 212 | 95 | ||||
| 213 | - | ### Hardening | 96 | + | ## Controlling a NeferWL session (agents) |
| 97 | + | ||||
| 98 | + | An agent or script on the host can watch the session and drive it with standard Wayland tools. Run them as the session user with the session's display: | |||
| 99 | + | ||||
| 100 | + | ```sh | |||
| 101 | + | export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=') | |||
| 102 | + | grim -o tv /tmp/screen.png # capture one output (see Screen capture) | |||
| 103 | + | neferwl pointer abs 0.5 0.5 click # click the middle of the layout | |||
| 104 | + | neferwl pointer move 200 -50 click right # actions run in order | |||
| 105 | + | wtype 'hello' # type into the focused window | |||
| 106 | + | neferwl state # windows, focus, outputs as JSON | |||
| 107 | + | ``` | |||
| 108 | + | ||||
| 109 | + | - `neferwl pointer` actions: `abs X Y` (fractions 0..1 of the layout, or of one output with `--output <name>`), `move DX DY`, `press`/`release`/`click [BTN]`, `hold [BTN] [DURATION]`, `drag DX DY [BTN]` and `scroll up|down|left|right [N]`. BTN is `left` (default), `right`, `middle`, `side`, `extra`, `forward`, `back`, a `BTN_*` name or an evdev code. `--click-duration` (20ms), `--hold-duration` (500ms), `--drag-steps` (10) and `--drag-step-delay` (10ms) tune the timing. Buttons still pressed at exit are released. See `neferwl pointer --help`. | |||
| 110 | + | - [wlrctl](https://git.sr.ht/~brocellous/wlrctl) (AUR: `wlrctl`) works too: `wlrctl pointer move 200 -50`, `wlrctl pointer click left`. | |||
| 111 | + | - Both use `zwlr_virtual_pointer_v1`. NeferWL routes their events like a real mouse, so focus, hover and drags behave as they would for a person. Absolute motion maps into the whole layout, or into one output when the tool binds it (`create_virtual_pointer_with_output`). | |||
| 112 | + | - `ydotool` writes to `/dev/uinput` through `ydotoold` and does not use this protocol; prefer `neferwl pointer`. | |||
| 113 | + | - Nothing is injected while the session is locked. Buttons a tool still held when it disconnects are released. | |||
| 114 | + | - Flatpak and other sandboxed clients (those on a `wp_security_context_v1` socket) do not see the virtual pointer global. | |||
| 115 | + | - `grim` needs the capture allowlist to admit it; see [the allowlist](capture.md#the-allowlist). | |||
| 116 | + | ||||
| 117 | + | [wayvnc](https://github.com/any1/wayvnc) works for remote viewing and control: it captures an output with wlr-screencopy and injects input through the virtual pointer and keyboard. Add its executable (`/usr/bin/wayvnc`) to `/etc/neferwl/capture-allow`, then run it in the session: | |||
| 118 | + | ||||
| 119 | + | ```sh | |||
| 120 | + | wayvnc -o tv 127.0.0.1 5900 | |||
| 121 | + | ``` | |||
| 122 | + | ||||
| 123 | + | Keep it on localhost and reach it through an SSH tunnel, or configure wayvnc's own authentication and TLS. | |||
| 124 | + | ||||
| 125 | + | ## Hardening | |||
| 214 | 126 | ||||
| 215 | On a dedicated box, a local keyboard should not reboot or reach a console: | 127 | On a dedicated box, a local keyboard should not reboot or reach a console: | ||
| 216 | 128 | ||||
M domainpolicy_test.go +1 -1
| @@ -170,7 +170,7 @@ func TestAdapterImports(t *testing.T) { | |||
| 170 | 170 | const adapters = base + "internal/adapters/" | |
| 171 | 171 | // Keep the shared-library allowlist here, not in the build-tag-sensitive | |
| 172 | 172 | // go list output. All other cross-adapter dependencies must use ports. | |
| 173 | - | libraries := strings.Fields("drm config sched seat watchdog fdwait busretry overlaydraw outputkit/routing outputkit/cursors outputkit/virtuals outputkit/headlessbackend xcursor outputkit/capture outputkit/corewake outputkit/presented outputkit/surfaces captureallow clock hdrcursor logging peerexe sessionsecurity syncfile statewire workspaceid xkb") | |
| 173 | + | libraries := strings.Fields("drm config sched seat watchdog fdwait busretry overlaydraw outputkit/routing outputkit/cursors outputkit/virtuals outputkit/headlessbackend xcursor outputkit/capture outputkit/corewake outputkit/presented outputkit/surfaces captureallow clock hdrcursor logging peerexe sessionsecurity syncfile workspaceid xkb") | |
| 174 | 174 | err := filepath.WalkDir("internal/adapters", func(dir string, entry fs.DirEntry, err error) error { | |
| 175 | 175 | if err != nil { | |
| 176 | 176 | return err | |
| @@ -170,7 +170,7 @@ func TestAdapterImports(t *testing.T) { | |||||
| 170 | const adapters = base + "internal/adapters/" | 170 | const adapters = base + "internal/adapters/" | ||
| 171 | // Keep the shared-library allowlist here, not in the build-tag-sensitive | 171 | // Keep the shared-library allowlist here, not in the build-tag-sensitive | ||
| 172 | // go list output. All other cross-adapter dependencies must use ports. | 172 | // go list output. All other cross-adapter dependencies must use ports. | ||
| 173 | - | libraries := strings.Fields("drm config sched seat watchdog fdwait busretry overlaydraw outputkit/routing outputkit/cursors outputkit/virtuals outputkit/headlessbackend xcursor outputkit/capture outputkit/corewake outputkit/presented outputkit/surfaces captureallow clock hdrcursor logging peerexe sessionsecurity syncfile statewire workspaceid xkb") | 173 | + | libraries := strings.Fields("drm config sched seat watchdog fdwait busretry overlaydraw outputkit/routing outputkit/cursors outputkit/virtuals outputkit/headlessbackend xcursor outputkit/capture outputkit/corewake outputkit/presented outputkit/surfaces captureallow clock hdrcursor logging peerexe sessionsecurity syncfile workspaceid xkb") |
| 174 | err := filepath.WalkDir("internal/adapters", func(dir string, entry fs.DirEntry, err error) error { | 174 | err := filepath.WalkDir("internal/adapters", func(dir string, entry fs.DirEntry, err error) error { | ||
| 175 | if err != nil { | 175 | if err != nil { | ||
| 176 | return err | 176 | return err | ||
D internal/adapters/config/catalog_test.go +0 -48
| @@ -1,48 +0,0 @@ | |||
| 1 | - | package config | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "testing" | |
| 5 | - | ||
| 6 | - | "github.com/bnema/neferwl/internal/domain" | |
| 7 | - | ) | |
| 8 | - | ||
| 9 | - | func TestCatalogBindActions(t *testing.T) { | |
| 10 | - | args := map[string]string{ | |
| 11 | - | "focus-workspace": "2", | |
| 12 | - | "move-column-to-workspace": "2", | |
| 13 | - | "move-window-to-workspace": "2", | |
| 14 | - | "workspace": "dev", | |
| 15 | - | "spawn": "foot --app-id=terminal", | |
| 16 | - | "stash": "foot", | |
| 17 | - | "set-column-width": "+1", | |
| 18 | - | "set-window-height": "-10%", | |
| 19 | - | } | |
| 20 | - | for _, spec := range domain.Commands() { | |
| 21 | - | t.Run(spec.Name, func(t *testing.T) { | |
| 22 | - | text := spec.Name | |
| 23 | - | action := spec.Kind == domain.CommandAction || spec.Kind == domain.CommandActionArg | |
| 24 | - | if spec.Kind == domain.CommandActionArg { | |
| 25 | - | arg, ok := args[spec.Name] | |
| 26 | - | if !ok { | |
| 27 | - | t.Fatalf("add a valid argument fixture for %s", spec.Name) | |
| 28 | - | } | |
| 29 | - | text += " " + arg | |
| 30 | - | if err := checkAction(spec.Name); err == nil { | |
| 31 | - | t.Error("bare argument action accepted") | |
| 32 | - | } | |
| 33 | - | } | |
| 34 | - | err := checkAction(text) | |
| 35 | - | if action && err != nil { | |
| 36 | - | t.Errorf("action rejected: %v", err) | |
| 37 | - | } | |
| 38 | - | if !action && err == nil { | |
| 39 | - | t.Error("non-action accepted as bind") | |
| 40 | - | } | |
| 41 | - | }) | |
| 42 | - | } | |
| 43 | - | for _, text := range []string{"state extra", "key Super+x", "type hello", "pointer 1 2", "swipe down", "shot DP-1", "output-add 1920x1080@60", "output-rm HEADLESS-2"} { | |
| 44 | - | if err := checkAction(text); err == nil { | |
| 45 | - | t.Errorf("non-action %q accepted", text) | |
| 46 | - | } | |
| 47 | - | } | |
| 48 | - | } | |
| @@ -1,48 +0,0 @@ | |||||
| 1 | - | package config | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "testing" | |||
| 5 | - | ||||
| 6 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 7 | - | ) | |||
| 8 | - | ||||
| 9 | - | func TestCatalogBindActions(t *testing.T) { | |||
| 10 | - | args := map[string]string{ | |||
| 11 | - | "focus-workspace": "2", | |||
| 12 | - | "move-column-to-workspace": "2", | |||
| 13 | - | "move-window-to-workspace": "2", | |||
| 14 | - | "workspace": "dev", | |||
| 15 | - | "spawn": "foot --app-id=terminal", | |||
| 16 | - | "stash": "foot", | |||
| 17 | - | "set-column-width": "+1", | |||
| 18 | - | "set-window-height": "-10%", | |||
| 19 | - | } | |||
| 20 | - | for _, spec := range domain.Commands() { | |||
| 21 | - | t.Run(spec.Name, func(t *testing.T) { | |||
| 22 | - | text := spec.Name | |||
| 23 | - | action := spec.Kind == domain.CommandAction || spec.Kind == domain.CommandActionArg | |||
| 24 | - | if spec.Kind == domain.CommandActionArg { | |||
| 25 | - | arg, ok := args[spec.Name] | |||
| 26 | - | if !ok { | |||
| 27 | - | t.Fatalf("add a valid argument fixture for %s", spec.Name) | |||
| 28 | - | } | |||
| 29 | - | text += " " + arg | |||
| 30 | - | if err := checkAction(spec.Name); err == nil { | |||
| 31 | - | t.Error("bare argument action accepted") | |||
| 32 | - | } | |||
| 33 | - | } | |||
| 34 | - | err := checkAction(text) | |||
| 35 | - | if action && err != nil { | |||
| 36 | - | t.Errorf("action rejected: %v", err) | |||
| 37 | - | } | |||
| 38 | - | if !action && err == nil { | |||
| 39 | - | t.Error("non-action accepted as bind") | |||
| 40 | - | } | |||
| 41 | - | }) | |||
| 42 | - | } | |||
| 43 | - | for _, text := range []string{"state extra", "key Super+x", "type hello", "pointer 1 2", "swipe down", "shot DP-1", "output-add 1920x1080@60", "output-rm HEADLESS-2"} { | |||
| 44 | - | if err := checkAction(text); err == nil { | |||
| 45 | - | t.Errorf("non-action %q accepted", text) | |||
| 46 | - | } | |||
| 47 | - | } | |||
| 48 | - | } | |||
M internal/adapters/config/config.go +60 -12
| @@ -22,7 +22,6 @@ import ( | |||
| 22 | 22 | "unicode/utf8" | |
| 23 | 23 | ||
| 24 | 24 | "bnema.dev/kvconf" | |
| 25 | - | "github.com/bnema/neferwl/internal/adapters/logging" | |
| 26 | 25 | "github.com/bnema/neferwl/internal/domain" | |
| 27 | 26 | ) | |
| 28 | 27 | ||
| @@ -75,6 +74,52 @@ var defaultBinds = []struct{ combo, action string }{ | |||
| 75 | 74 | {"cmd+ctrl+shift+down", "move-workspace-next"}, | |
| 76 | 75 | {"cmd+shift+space", "toggle-floating"}, | |
| 77 | 76 | } | |
| 77 | + | var actions = map[string]bool{ | |
| 78 | + | "focus-monitor-left": true, | |
| 79 | + | "focus-monitor-right": true, | |
| 80 | + | "move-workspace-to-monitor-left": true, | |
| 81 | + | "move-workspace-to-monitor-right": true, | |
| 82 | + | "focus-monitor-up": true, | |
| 83 | + | "focus-monitor-down": true, | |
| 84 | + | "move-workspace-to-monitor-up": true, | |
| 85 | + | "move-workspace-to-monitor-down": true, | |
| 86 | + | "scale-up": true, | |
| 87 | + | "scale-down": true, | |
| 88 | + | "focus-workspace-prev": true, | |
| 89 | + | "focus-workspace-next": true, | |
| 90 | + | "move-column-to-workspace-prev": true, | |
| 91 | + | "move-column-to-workspace-next": true, | |
| 92 | + | "move-window-to-workspace-prev": true, | |
| 93 | + | "move-window-to-workspace-next": true, | |
| 94 | + | "none": true, | |
| 95 | + | "consume-or-expel-window-left": true, | |
| 96 | + | "consume-or-expel-window-right": true, | |
| 97 | + | "spawn-terminal": true, | |
| 98 | + | "focus-column-left": true, | |
| 99 | + | "focus-column-right": true, | |
| 100 | + | "focus-window-up": true, | |
| 101 | + | "focus-window-down": true, | |
| 102 | + | "move-column-left": true, | |
| 103 | + | "move-column-right": true, | |
| 104 | + | "cycle-column-width": true, | |
| 105 | + | "maximize-column": true, | |
| 106 | + | "toggle-fullscreen": true, | |
| 107 | + | "toggle-window-stash": true, | |
| 108 | + | "toggle-stash-visible": true, | |
| 109 | + | "toggle-overview": true, | |
| 110 | + | "switch-column-next": true, | |
| 111 | + | "switch-column-prev": true, | |
| 112 | + | "close-window": true, | |
| 113 | + | "quit": true, | |
| 114 | + | "move-window-up": true, | |
| 115 | + | "move-window-down": true, | |
| 116 | + | "move-workspace-prev": true, | |
| 117 | + | "move-workspace-next": true, | |
| 118 | + | "toggle-floating": true, | |
| 119 | + | "hint": true, | |
| 120 | + | "osd-pin": true, | |
| 121 | + | } | |
| 122 | + | var components = map[string]bool{"core": true, "wayland": true, "input": true, "drm": true, "seat": true, "render": true, "sync": true, "config": true, "app": true, "hints": true} | |
| 78 | 123 | var color = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) | |
| 79 | 124 | ||
| 80 | 125 | // columnStep is the +N or -N step of set-column-width, in cells, N from 1 | |
| @@ -540,8 +585,13 @@ func parseBytes(data []byte) (domain.Config, map[string]string, []Warning, error | |||
| 540 | 585 | warn("%s: expected virtual WxH[@Hz]", key) | |
| 541 | 586 | continue | |
| 542 | 587 | } | |
| 543 | - | if _, err := domain.ParseOutputMode(fields[1]); err != nil { | |
| 544 | - | warn("%s: virtual %v", key, err) | |
| 588 | + | w, h, hz, err := ParseMode(fields[1]) | |
| 589 | + | if hz == 0 { | |
| 590 | + | hz = 60 | |
| 591 | + | } | |
| 592 | + | _, representable := domain.RefreshMilli(hz) | |
| 593 | + | if err != nil || w < 1 || h < 1 || w > 16384 || h > 16384 || !representable { | |
| 594 | + | warn("%s: virtual mode must be WxH[@Hz], dimensions 1..16384 and rounded refresh 1..2147483647 mHz", key) | |
| 545 | 595 | continue | |
| 546 | 596 | } | |
| 547 | 597 | o.Virtual, o.Mode = true, fields[1] | |
| @@ -557,7 +607,7 @@ func parseBytes(data []byte) (domain.Config, map[string]string, []Warning, error | |||
| 557 | 607 | e := entry() | |
| 558 | 608 | o.Scale, o.Transform, o.Primary, o.HDR, o.SDRBrightness, o.Anchor = e.Scale, e.Transform, e.Primary, e.HDR, e.SDRBrightness, e.Anchor | |
| 559 | 609 | o.SDRExpand, o.SDRExpandIntensity, o.SDRExpandPeak, o.SDRDecode = e.SDRExpand, e.SDRExpandIntensity, e.SDRExpandPeak, e.SDRDecode | |
| 560 | - | o.Inputs, o.KeepFocus = e.Inputs, e.KeepFocus | |
| 610 | + | o.Inputs = e.Inputs | |
| 561 | 611 | *e = o | |
| 562 | 612 | continue | |
| 563 | 613 | } | |
| @@ -1126,10 +1176,11 @@ func set(c *domain.Config, key, v string) error { | |||
| 1126 | 1176 | } | |
| 1127 | 1177 | c.Log.Level = v | |
| 1128 | 1178 | case "log.debug": | |
| 1129 | - | // The logger owns the component and category names. | |
| 1130 | 1179 | list := splitList(v) | |
| 1131 | - | if _, err := logging.ParseDebug(strings.Join(list, ",")); err != nil { | |
| 1132 | - | return err | |
| 1180 | + | for _, s := range list { | |
| 1181 | + | if !components[s] && s != "all" { | |
| 1182 | + | return fmt.Errorf("unknown component %q", s) | |
| 1183 | + | } | |
| 1133 | 1184 | } | |
| 1134 | 1185 | c.Log.Debug = list | |
| 1135 | 1186 | default: | |
| @@ -1507,14 +1558,11 @@ func checkAction(v string) error { | |||
| 1507 | 1558 | return nil | |
| 1508 | 1559 | } | |
| 1509 | 1560 | for old, repl := range map[string]string{"-workspace-up": "-workspace-prev", "-workspace-down": "-workspace-next"} { | |
| 1510 | - | if base, ok := strings.CutSuffix(v, old); ok { | |
| 1511 | - | if spec, found := domain.LookupCommand(base + repl); !found || spec.Kind != domain.CommandAction { | |
| 1512 | - | continue | |
| 1513 | - | } | |
| 1561 | + | if base, ok := strings.CutSuffix(v, old); ok && actions[base+repl] { | |
| 1514 | 1562 | return fmt.Errorf("action %q was renamed to %q", v, base+repl) | |
| 1515 | 1563 | } | |
| 1516 | 1564 | } | |
| 1517 | - | if spec, ok := domain.LookupCommand(v); !ok || spec.Kind != domain.CommandAction { | |
| 1565 | + | if !actions[v] { | |
| 1518 | 1566 | return fmt.Errorf(`unknown action %q (or "spawn <command>", "stash <command>", "workspace <name>")`, v) | |
| 1519 | 1567 | } | |
| 1520 | 1568 | return nil | |
| @@ -22,7 +22,6 @@ import ( | |||||
| 22 | "unicode/utf8" | 22 | "unicode/utf8" | ||
| 23 | 23 | ||||
| 24 | "bnema.dev/kvconf" | 24 | "bnema.dev/kvconf" | ||
| 25 | - | "github.com/bnema/neferwl/internal/adapters/logging" | |||
| 26 | "github.com/bnema/neferwl/internal/domain" | 25 | "github.com/bnema/neferwl/internal/domain" | ||
| 27 | ) | 26 | ) | ||
| 28 | 27 | ||||
| @@ -75,6 +74,52 @@ var defaultBinds = []struct{ combo, action string }{ | |||||
| 75 | {"cmd+ctrl+shift+down", "move-workspace-next"}, | 74 | {"cmd+ctrl+shift+down", "move-workspace-next"}, | ||
| 76 | {"cmd+shift+space", "toggle-floating"}, | 75 | {"cmd+shift+space", "toggle-floating"}, | ||
| 77 | } | 76 | } | ||
| 77 | + | var actions = map[string]bool{ | |||
| 78 | + | "focus-monitor-left": true, | |||
| 79 | + | "focus-monitor-right": true, | |||
| 80 | + | "move-workspace-to-monitor-left": true, | |||
| 81 | + | "move-workspace-to-monitor-right": true, | |||
| 82 | + | "focus-monitor-up": true, | |||
| 83 | + | "focus-monitor-down": true, | |||
| 84 | + | "move-workspace-to-monitor-up": true, | |||
| 85 | + | "move-workspace-to-monitor-down": true, | |||
| 86 | + | "scale-up": true, | |||
| 87 | + | "scale-down": true, | |||
| 88 | + | "focus-workspace-prev": true, | |||
| 89 | + | "focus-workspace-next": true, | |||
| 90 | + | "move-column-to-workspace-prev": true, | |||
| 91 | + | "move-column-to-workspace-next": true, | |||
| 92 | + | "move-window-to-workspace-prev": true, | |||
| 93 | + | "move-window-to-workspace-next": true, | |||
| 94 | + | "none": true, | |||
| 95 | + | "consume-or-expel-window-left": true, | |||
| 96 | + | "consume-or-expel-window-right": true, | |||
| 97 | + | "spawn-terminal": true, | |||
| 98 | + | "focus-column-left": true, | |||
| 99 | + | "focus-column-right": true, | |||
| 100 | + | "focus-window-up": true, | |||
| 101 | + | "focus-window-down": true, | |||
| 102 | + | "move-column-left": true, | |||
| 103 | + | "move-column-right": true, | |||
| 104 | + | "cycle-column-width": true, | |||
| 105 | + | "maximize-column": true, | |||
| 106 | + | "toggle-fullscreen": true, | |||
| 107 | + | "toggle-window-stash": true, | |||
| 108 | + | "toggle-stash-visible": true, | |||
| 109 | + | "toggle-overview": true, | |||
| 110 | + | "switch-column-next": true, | |||
| 111 | + | "switch-column-prev": true, | |||
| 112 | + | "close-window": true, | |||
| 113 | + | "quit": true, | |||
| 114 | + | "move-window-up": true, | |||
| 115 | + | "move-window-down": true, | |||
| 116 | + | "move-workspace-prev": true, | |||
| 117 | + | "move-workspace-next": true, | |||
| 118 | + | "toggle-floating": true, | |||
| 119 | + | "hint": true, | |||
| 120 | + | "osd-pin": true, | |||
| 121 | + | } | |||
| 122 | + | var components = map[string]bool{"core": true, "wayland": true, "input": true, "drm": true, "seat": true, "render": true, "sync": true, "config": true, "app": true, "hints": true} | |||
| 78 | var color = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) | 123 | var color = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) | ||
| 79 | 124 | ||||
| 80 | // columnStep is the +N or -N step of set-column-width, in cells, N from 1 | 125 | // columnStep is the +N or -N step of set-column-width, in cells, N from 1 | ||
| @@ -540,8 +585,13 @@ func parseBytes(data []byte) (domain.Config, map[string]string, []Warning, error | |||||
| 540 | warn("%s: expected virtual WxH[@Hz]", key) | 585 | warn("%s: expected virtual WxH[@Hz]", key) | ||
| 541 | continue | 586 | continue | ||
| 542 | } | 587 | } | ||
| 543 | - | if _, err := domain.ParseOutputMode(fields[1]); err != nil { | 588 | + | w, h, hz, err := ParseMode(fields[1]) |
| 544 | - | warn("%s: virtual %v", key, err) | 589 | + | if hz == 0 { |
| 590 | + | hz = 60 | |||
| 591 | + | } | |||
| 592 | + | _, representable := domain.RefreshMilli(hz) | |||
| 593 | + | if err != nil || w < 1 || h < 1 || w > 16384 || h > 16384 || !representable { | |||
| 594 | + | warn("%s: virtual mode must be WxH[@Hz], dimensions 1..16384 and rounded refresh 1..2147483647 mHz", key) | |||
| 545 | continue | 595 | continue | ||
| 546 | } | 596 | } | ||
| 547 | o.Virtual, o.Mode = true, fields[1] | 597 | o.Virtual, o.Mode = true, fields[1] | ||
| @@ -557,7 +607,7 @@ func parseBytes(data []byte) (domain.Config, map[string]string, []Warning, error | |||||
| 557 | e := entry() | 607 | e := entry() | ||
| 558 | o.Scale, o.Transform, o.Primary, o.HDR, o.SDRBrightness, o.Anchor = e.Scale, e.Transform, e.Primary, e.HDR, e.SDRBrightness, e.Anchor | 608 | o.Scale, o.Transform, o.Primary, o.HDR, o.SDRBrightness, o.Anchor = e.Scale, e.Transform, e.Primary, e.HDR, e.SDRBrightness, e.Anchor | ||
| 559 | o.SDRExpand, o.SDRExpandIntensity, o.SDRExpandPeak, o.SDRDecode = e.SDRExpand, e.SDRExpandIntensity, e.SDRExpandPeak, e.SDRDecode | 609 | o.SDRExpand, o.SDRExpandIntensity, o.SDRExpandPeak, o.SDRDecode = e.SDRExpand, e.SDRExpandIntensity, e.SDRExpandPeak, e.SDRDecode | ||
| 560 | - | o.Inputs, o.KeepFocus = e.Inputs, e.KeepFocus | 610 | + | o.Inputs = e.Inputs |
| 561 | *e = o | 611 | *e = o | ||
| 562 | continue | 612 | continue | ||
| 563 | } | 613 | } | ||
| @@ -1126,10 +1176,11 @@ func set(c *domain.Config, key, v string) error { | |||||
| 1126 | } | 1176 | } | ||
| 1127 | c.Log.Level = v | 1177 | c.Log.Level = v | ||
| 1128 | case "log.debug": | 1178 | case "log.debug": | ||
| 1129 | - | // The logger owns the component and category names. | |||
| 1130 | list := splitList(v) | 1179 | list := splitList(v) | ||
| 1131 | - | if _, err := logging.ParseDebug(strings.Join(list, ",")); err != nil { | 1180 | + | for _, s := range list { |
| 1132 | - | return err | 1181 | + | if !components[s] && s != "all" { |
| 1182 | + | return fmt.Errorf("unknown component %q", s) | |||
| 1183 | + | } | |||
| 1133 | } | 1184 | } | ||
| 1134 | c.Log.Debug = list | 1185 | c.Log.Debug = list | ||
| 1135 | default: | 1186 | default: | ||
| @@ -1507,14 +1558,11 @@ func checkAction(v string) error { | |||||
| 1507 | return nil | 1558 | return nil | ||
| 1508 | } | 1559 | } | ||
| 1509 | for old, repl := range map[string]string{"-workspace-up": "-workspace-prev", "-workspace-down": "-workspace-next"} { | 1560 | for old, repl := range map[string]string{"-workspace-up": "-workspace-prev", "-workspace-down": "-workspace-next"} { | ||
| 1510 | - | if base, ok := strings.CutSuffix(v, old); ok { | 1561 | + | if base, ok := strings.CutSuffix(v, old); ok && actions[base+repl] { |
| 1511 | - | if spec, found := domain.LookupCommand(base + repl); !found || spec.Kind != domain.CommandAction { | |||
| 1512 | - | continue | |||
| 1513 | - | } | |||
| 1514 | return fmt.Errorf("action %q was renamed to %q", v, base+repl) | 1562 | return fmt.Errorf("action %q was renamed to %q", v, base+repl) | ||
| 1515 | } | 1563 | } | ||
| 1516 | } | 1564 | } | ||
| 1517 | - | if spec, ok := domain.LookupCommand(v); !ok || spec.Kind != domain.CommandAction { | 1565 | + | if !actions[v] { |
| 1518 | return fmt.Errorf(`unknown action %q (or "spawn <command>", "stash <command>", "workspace <name>")`, v) | 1566 | return fmt.Errorf(`unknown action %q (or "spawn <command>", "stash <command>", "workspace <name>")`, v) | ||
| 1519 | } | 1567 | } | ||
| 1520 | return nil | 1568 | return nil | ||
M internal/adapters/config/config_test.go +0 -10
| @@ -1277,13 +1277,3 @@ func TestLineageShells(t *testing.T) { | |||
| 1277 | 1277 | t.Fatal("shell reload compares equal") | |
| 1278 | 1278 | } | |
| 1279 | 1279 | } | |
| 1280 | - | ||
| 1281 | - | // TestLogDebugNames: log.debug accepts every logger component and category. | |
| 1282 | - | func TestLogDebugNames(t *testing.T) { | |
| 1283 | - | for _, v := range []string{"control", "screensaver, powerkey", "sched,screencast", "input-motion", "all"} { | |
| 1284 | - | c, w := parseString(t, "log.debug = "+v) | |
| 1285 | - | if len(w) != 0 || len(c.Log.Debug) == 0 { | |
| 1286 | - | t.Errorf("%q: debug %v warnings %v", v, c.Log.Debug, w) | |
| 1287 | - | } | |
| 1288 | - | } | |
| 1289 | - | } | |
| @@ -1277,13 +1277,3 @@ func TestLineageShells(t *testing.T) { | |||||
| 1277 | t.Fatal("shell reload compares equal") | 1277 | t.Fatal("shell reload compares equal") | ||
| 1278 | } | 1278 | } | ||
| 1279 | } | 1279 | } | ||
| 1280 | - | ||||
| 1281 | - | // TestLogDebugNames: log.debug accepts every logger component and category. | |||
| 1282 | - | func TestLogDebugNames(t *testing.T) { | |||
| 1283 | - | for _, v := range []string{"control", "screensaver, powerkey", "sched,screencast", "input-motion", "all"} { | |||
| 1284 | - | c, w := parseString(t, "log.debug = "+v) | |||
| 1285 | - | if len(w) != 0 || len(c.Log.Debug) == 0 { | |||
| 1286 | - | t.Errorf("%q: debug %v warnings %v", v, c.Log.Debug, w) | |||
| 1287 | - | } | |||
| 1288 | - | } | |||
| 1289 | - | } | |||
M internal/adapters/config/virtual_test.go +0 -24
| @@ -109,27 +109,3 @@ func TestVirtualOutputOverrides(t *testing.T) { | |||
| 109 | 109 | } | |
| 110 | 110 | } | |
| 111 | 111 | } | |
| 112 | - | ||
| 113 | - | func TestVirtualOutputKeepFocusKey(t *testing.T) { | |
| 114 | - | for _, tc := range []struct { | |
| 115 | - | name string | |
| 116 | - | input string | |
| 117 | - | }{ | |
| 118 | - | {"before", "output.tv.keep-focus = on\noutput.tv = virtual 1920x1080\n"}, | |
| 119 | - | {"after", "output.tv = virtual 1920x1080\noutput.tv.keep-focus = on\n"}, | |
| 120 | - | } { | |
| 121 | - | t.Run(tc.name, func(t *testing.T) { | |
| 122 | - | c, raw, warnings, err := parseBytes([]byte(tc.input)) | |
| 123 | - | if err != nil || len(warnings) != 0 || len(c.Outputs) != 1 { | |
| 124 | - | t.Fatalf("outputs=%+v err=%v warnings=%v", c.Outputs, err, warnings) | |
| 125 | - | } | |
| 126 | - | o := c.Outputs[0] | |
| 127 | - | if !o.Virtual || o.Mode != "1920x1080" || !o.KeepFocus || o.ScaleOnly { | |
| 128 | - | t.Fatalf("output=%+v", o) | |
| 129 | - | } | |
| 130 | - | if raw["output.tv.keep-focus"] != "on" { | |
| 131 | - | t.Fatal("keep-focus dropped from effective config") | |
| 132 | - | } | |
| 133 | - | }) | |
| 134 | - | } | |
| 135 | - | } | |
| @@ -109,27 +109,3 @@ func TestVirtualOutputOverrides(t *testing.T) { | |||||
| 109 | } | 109 | } | ||
| 110 | } | 110 | } | ||
| 111 | } | 111 | } | ||
| 112 | - | ||||
| 113 | - | func TestVirtualOutputKeepFocusKey(t *testing.T) { | |||
| 114 | - | for _, tc := range []struct { | |||
| 115 | - | name string | |||
| 116 | - | input string | |||
| 117 | - | }{ | |||
| 118 | - | {"before", "output.tv.keep-focus = on\noutput.tv = virtual 1920x1080\n"}, | |||
| 119 | - | {"after", "output.tv = virtual 1920x1080\noutput.tv.keep-focus = on\n"}, | |||
| 120 | - | } { | |||
| 121 | - | t.Run(tc.name, func(t *testing.T) { | |||
| 122 | - | c, raw, warnings, err := parseBytes([]byte(tc.input)) | |||
| 123 | - | if err != nil || len(warnings) != 0 || len(c.Outputs) != 1 { | |||
| 124 | - | t.Fatalf("outputs=%+v err=%v warnings=%v", c.Outputs, err, warnings) | |||
| 125 | - | } | |||
| 126 | - | o := c.Outputs[0] | |||
| 127 | - | if !o.Virtual || o.Mode != "1920x1080" || !o.KeepFocus || o.ScaleOnly { | |||
| 128 | - | t.Fatalf("output=%+v", o) | |||
| 129 | - | } | |||
| 130 | - | if raw["output.tv.keep-focus"] != "on" { | |||
| 131 | - | t.Fatal("keep-focus dropped from effective config") | |||
| 132 | - | } | |||
| 133 | - | }) | |||
| 134 | - | } | |||
| 135 | - | } | |||
D internal/adapters/control/continuous_test.go +0 -36
| @@ -1,36 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "context" | |
| 5 | - | "testing" | |
| 6 | - | "testing/synctest" | |
| 7 | - | ||
| 8 | - | "github.com/bnema/neferwl/internal/domain" | |
| 9 | - | "github.com/bnema/neferwl/internal/ports" | |
| 10 | - | ) | |
| 11 | - | ||
| 12 | - | // Every-frame capture goes to core as a ControlCapture: the adapter only | |
| 13 | - | // supplies the default directory and relays core's (or the backend's) reply. | |
| 14 | - | func TestContinuousDispatch(t *testing.T) { | |
| 15 | - | synctest.Test(t, func(t *testing.T) { | |
| 16 | - | s := &Server{framesDir: "/session/shots/frames"} | |
| 17 | - | out := make(chan ports.ControlRequest) | |
| 18 | - | for _, tc := range []struct { | |
| 19 | - | stop bool | |
| 20 | - | code string | |
| 21 | - | }{{false, ""}, {true, ""}, {false, ports.ControlErrLocked}} { | |
| 22 | - | go func() { | |
| 23 | - | r := (<-out).(ports.ControlCapture) | |
| 24 | - | if r.Dir != s.framesDir || r.Stop != tc.stop || r.Caps != domain.CapsAll || cap(r.Reply) != 1 { | |
| 25 | - | t.Error(r) | |
| 26 | - | } | |
| 27 | - | r.Reply <- ports.ContinuousCaptureResult{Dir: r.Dir, Err: tc.code} | |
| 28 | - | }() | |
| 29 | - | announced := false | |
| 30 | - | got := s.dispatch(context.Background(), request{Op: "shot", EveryFrame: !tc.stop, Stop: tc.stop}, out, &announced) | |
| 31 | - | if got.OK != (tc.code == "") || got.Error != tc.code || got.Dir != s.framesDir { | |
| 32 | - | t.Fatal(got) | |
| 33 | - | } | |
| 34 | - | } | |
| 35 | - | }) | |
| 36 | - | } | |
| @@ -1,36 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "context" | |||
| 5 | - | "testing" | |||
| 6 | - | "testing/synctest" | |||
| 7 | - | ||||
| 8 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 9 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 10 | - | ) | |||
| 11 | - | ||||
| 12 | - | // Every-frame capture goes to core as a ControlCapture: the adapter only | |||
| 13 | - | // supplies the default directory and relays core's (or the backend's) reply. | |||
| 14 | - | func TestContinuousDispatch(t *testing.T) { | |||
| 15 | - | synctest.Test(t, func(t *testing.T) { | |||
| 16 | - | s := &Server{framesDir: "/session/shots/frames"} | |||
| 17 | - | out := make(chan ports.ControlRequest) | |||
| 18 | - | for _, tc := range []struct { | |||
| 19 | - | stop bool | |||
| 20 | - | code string | |||
| 21 | - | }{{false, ""}, {true, ""}, {false, ports.ControlErrLocked}} { | |||
| 22 | - | go func() { | |||
| 23 | - | r := (<-out).(ports.ControlCapture) | |||
| 24 | - | if r.Dir != s.framesDir || r.Stop != tc.stop || r.Caps != domain.CapsAll || cap(r.Reply) != 1 { | |||
| 25 | - | t.Error(r) | |||
| 26 | - | } | |||
| 27 | - | r.Reply <- ports.ContinuousCaptureResult{Dir: r.Dir, Err: tc.code} | |||
| 28 | - | }() | |||
| 29 | - | announced := false | |||
| 30 | - | got := s.dispatch(context.Background(), request{Op: "shot", EveryFrame: !tc.stop, Stop: tc.stop}, out, &announced) | |||
| 31 | - | if got.OK != (tc.code == "") || got.Error != tc.code || got.Dir != s.framesDir { | |||
| 32 | - | t.Fatal(got) | |||
| 33 | - | } | |||
| 34 | - | } | |||
| 35 | - | }) | |||
| 36 | - | } | |||
D internal/adapters/control/control.go +0 -528
| @@ -1,528 +0,0 @@ | |||
| 1 | - | // Package control serves the v1 JSON-lines control protocol on a Unix socket. | |
| 2 | - | package control | |
| 3 | - | ||
| 4 | - | import ( | |
| 5 | - | "bufio" | |
| 6 | - | "context" | |
| 7 | - | "encoding/json" | |
| 8 | - | "errors" | |
| 9 | - | "fmt" | |
| 10 | - | "net" | |
| 11 | - | "os" | |
| 12 | - | "path/filepath" | |
| 13 | - | "sync" | |
| 14 | - | "syscall" | |
| 15 | - | "time" | |
| 16 | - | ||
| 17 | - | "github.com/bnema/neferwl/internal/adapters/logging" | |
| 18 | - | "github.com/bnema/neferwl/internal/adapters/statewire" | |
| 19 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |
| 20 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |
| 21 | - | "github.com/bnema/neferwl/internal/domain" | |
| 22 | - | "github.com/bnema/neferwl/internal/ports" | |
| 23 | - | "golang.org/x/sys/unix" | |
| 24 | - | ) | |
| 25 | - | ||
| 26 | - | // Server owns a control listener. Requests on each connection are processed in | |
| 27 | - | // order: the next line is read only after the preceding core reply is sent. | |
| 28 | - | // Options supplies a dedicated control keymap, never the physical input map. | |
| 29 | - | // Listen takes ownership of Keymap on success. The server takes ownership of | |
| 30 | - | // each map it receives from Keymaps; producers own any maps left in the channel | |
| 31 | - | // after shutdown. Security is sampled before every translated event. | |
| 32 | - | type Options struct { | |
| 33 | - | FramesDir string | |
| 34 | - | Shooter *Shooter | |
| 35 | - | Keymap *xkb.Keymap | |
| 36 | - | Keymaps <-chan *xkb.Keymap | |
| 37 | - | Security ports.SessionSecurity | |
| 38 | - | } | |
| 39 | - | ||
| 40 | - | type Server struct { | |
| 41 | - | framesDir string | |
| 42 | - | shooter *Shooter | |
| 43 | - | quitMu sync.Mutex | |
| 44 | - | quitReplies map[chan struct{}]struct{} | |
| 45 | - | injectMu sync.Mutex | |
| 46 | - | injector *injector | |
| 47 | - | keymaps <-chan *xkb.Keymap | |
| 48 | - | listener *net.UnixListener | |
| 49 | - | ids *workspaceid.IDs | |
| 50 | - | done chan struct{} | |
| 51 | - | once sync.Once | |
| 52 | - | err error | |
| 53 | - | } | |
| 54 | - | ||
| 55 | - | // Listen creates a private socket using the same workspace IDs as statefile. | |
| 56 | - | // An existing socket is removed only when connecting proves it has no listener. | |
| 57 | - | func Listen(path string, ids *workspaceid.IDs, opts Options) (*Server, error) { | |
| 58 | - | if ids == nil { | |
| 59 | - | return nil, errors.New("workspace IDs are required") | |
| 60 | - | } | |
| 61 | - | if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { | |
| 62 | - | return nil, err | |
| 63 | - | } | |
| 64 | - | if info, err := os.Lstat(path); err == nil { | |
| 65 | - | if info.Mode()&os.ModeSocket == 0 { | |
| 66 | - | return nil, fmt.Errorf("control path is not a socket: %s", path) | |
| 67 | - | } | |
| 68 | - | conn, err := net.DialTimeout("unix", path, time.Second) | |
| 69 | - | if err == nil { | |
| 70 | - | conn.Close() | |
| 71 | - | return nil, fmt.Errorf("control socket already listening: %s", path) | |
| 72 | - | } | |
| 73 | - | if !errors.Is(err, syscall.ECONNREFUSED) { | |
| 74 | - | return nil, err | |
| 75 | - | } | |
| 76 | - | if err := os.Remove(path); err != nil { | |
| 77 | - | return nil, err | |
| 78 | - | } | |
| 79 | - | } else if !errors.Is(err, os.ErrNotExist) { | |
| 80 | - | return nil, err | |
| 81 | - | } | |
| 82 | - | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) | |
| 83 | - | if err != nil { | |
| 84 | - | return nil, err | |
| 85 | - | } | |
| 86 | - | if err := os.Chmod(path, 0o600); err != nil { | |
| 87 | - | listener.Close() | |
| 88 | - | return nil, err | |
| 89 | - | } | |
| 90 | - | s := &Server{listener: listener, ids: ids, done: make(chan struct{})} | |
| 91 | - | s.framesDir = opts.FramesDir | |
| 92 | - | s.shooter = opts.Shooter | |
| 93 | - | s.keymaps = opts.Keymaps | |
| 94 | - | if opts.Keymap != nil { | |
| 95 | - | s.injector = newInjector(opts.Keymap, opts.Security) | |
| 96 | - | } | |
| 97 | - | return s, nil | |
| 98 | - | } | |
| 99 | - | ||
| 100 | - | // Close stops acceptance and all active connections. It is safe to call twice. | |
| 101 | - | func (s *Server) Close() error { | |
| 102 | - | s.once.Do(func() { | |
| 103 | - | close(s.done) | |
| 104 | - | s.err = s.listener.Close() | |
| 105 | - | s.injectMu.Lock() | |
| 106 | - | defer s.injectMu.Unlock() | |
| 107 | - | if s.injector != nil { | |
| 108 | - | s.injector.km.Close() | |
| 109 | - | s.injector = nil | |
| 110 | - | } | |
| 111 | - | }) | |
| 112 | - | return s.err | |
| 113 | - | } | |
| 114 | - | ||
| 115 | - | // WaitQuitReplies lets shutdown flush outstanding quit replies before cancelling | |
| 116 | - | // control connections. The caller bounds the wait in case a peer stops reading. | |
| 117 | - | func (s *Server) WaitQuitReplies(ctx context.Context) { | |
| 118 | - | s.quitMu.Lock() | |
| 119 | - | pending := make([]chan struct{}, 0, len(s.quitReplies)) | |
| 120 | - | for done := range s.quitReplies { | |
| 121 | - | pending = append(pending, done) | |
| 122 | - | } | |
| 123 | - | s.quitMu.Unlock() | |
| 124 | - | for _, done := range pending { | |
| 125 | - | select { | |
| 126 | - | case <-done: | |
| 127 | - | case <-ctx.Done(): | |
| 128 | - | return | |
| 129 | - | } | |
| 130 | - | } | |
| 131 | - | } | |
| 132 | - | ||
| 133 | - | func (s *Server) trackQuit() func() { | |
| 134 | - | done := make(chan struct{}) | |
| 135 | - | s.quitMu.Lock() | |
| 136 | - | if s.quitReplies == nil { | |
| 137 | - | s.quitReplies = make(map[chan struct{}]struct{}) | |
| 138 | - | } | |
| 139 | - | s.quitReplies[done] = struct{}{} | |
| 140 | - | s.quitMu.Unlock() | |
| 141 | - | return func() { | |
| 142 | - | s.quitMu.Lock() | |
| 143 | - | delete(s.quitReplies, done) | |
| 144 | - | close(done) | |
| 145 | - | s.quitMu.Unlock() | |
| 146 | - | } | |
| 147 | - | } | |
| 148 | - | ||
| 149 | - | // Run accepts connections until cancellation or Close, waiting for handlers to exit. | |
| 150 | - | func (s *Server) Run(ctx context.Context, out chan<- ports.ControlRequest) error { | |
| 151 | - | ctx, cancel := context.WithCancel(ctx) | |
| 152 | - | stop := context.AfterFunc(ctx, func() { _ = s.Close() }) | |
| 153 | - | defer stop() | |
| 154 | - | var workers sync.WaitGroup | |
| 155 | - | defer workers.Wait() | |
| 156 | - | defer cancel() | |
| 157 | - | log := logging.For(ctx, "control") | |
| 158 | - | log.Info().Str("path", s.listener.Addr().String()).Msg("listening") | |
| 159 | - | for { | |
| 160 | - | conn, err := s.listener.AcceptUnix() | |
| 161 | - | if err != nil { | |
| 162 | - | if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { | |
| 163 | - | return nil | |
| 164 | - | } | |
| 165 | - | return err | |
| 166 | - | } | |
| 167 | - | workers.Add(1) | |
| 168 | - | go func() { | |
| 169 | - | defer workers.Done() | |
| 170 | - | defer conn.Close() | |
| 171 | - | connCtx, cancel := context.WithCancel(ctx) | |
| 172 | - | defer cancel() | |
| 173 | - | go func() { | |
| 174 | - | select { | |
| 175 | - | case <-s.done: | |
| 176 | - | cancel() | |
| 177 | - | case <-connCtx.Done(): | |
| 178 | - | } | |
| 179 | - | }() | |
| 180 | - | stop := context.AfterFunc(connCtx, func() { _ = conn.Close() }) | |
| 181 | - | defer stop() | |
| 182 | - | if !sameUID(conn) { | |
| 183 | - | log.Warn().Msg("peer rejected") | |
| 184 | - | return | |
| 185 | - | } | |
| 186 | - | s.serve(connCtx, conn, out) | |
| 187 | - | }() | |
| 188 | - | } | |
| 189 | - | } | |
| 190 | - | ||
| 191 | - | func sameUID(conn *net.UnixConn) bool { | |
| 192 | - | raw, err := conn.SyscallConn() | |
| 193 | - | if err != nil { | |
| 194 | - | return false | |
| 195 | - | } | |
| 196 | - | var cred *unix.Ucred | |
| 197 | - | var credErr error | |
| 198 | - | if err := raw.Control(func(fd uintptr) { cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) }); err != nil { | |
| 199 | - | return false | |
| 200 | - | } | |
| 201 | - | return credErr == nil && cred != nil && cred.Uid == uint32(os.Getuid()) | |
| 202 | - | } | |
| 203 | - | ||
| 204 | - | type request struct { | |
| 205 | - | EveryFrame bool `json:"every_frame"` | |
| 206 | - | Stop bool `json:"stop"` | |
| 207 | - | Name string `json:"name"` | |
| 208 | - | Mode string `json:"mode"` | |
| 209 | - | Outputs []string `json:"outputs"` | |
| 210 | - | Inline bool `json:"inline"` | |
| 211 | - | Raw bool `json:"raw"` | |
| 212 | - | Shot json.RawMessage `json:"shot"` | |
| 213 | - | ID json.RawMessage `json:"id"` | |
| 214 | - | Op string `json:"op"` | |
| 215 | - | Action string `json:"action"` | |
| 216 | - | What string `json:"what"` | |
| 217 | - | Wait *string `json:"wait"` | |
| 218 | - | Until *string `json:"until"` | |
| 219 | - | Timeout *string `json:"timeout"` | |
| 220 | - | Kind string `json:"kind"` | |
| 221 | - | Combo string `json:"combo"` | |
| 222 | - | Text string `json:"text"` | |
| 223 | - | Cmd string `json:"cmd"` | |
| 224 | - | Args []string `json:"args"` | |
| 225 | - | Fingers int `json:"fingers"` | |
| 226 | - | Dir string `json:"dir"` | |
| 227 | - | } | |
| 228 | - | ||
| 229 | - | type reply struct { | |
| 230 | - | Dir string `json:"dir,omitempty"` | |
| 231 | - | Shots []Shot `json:"shots,omitempty"` | |
| 232 | - | Detail string `json:"detail,omitempty"` | |
| 233 | - | ID json.RawMessage `json:"id"` | |
| 234 | - | OK bool `json:"ok"` | |
| 235 | - | Done string `json:"done"` | |
| 236 | - | Diff diff `json:"diff"` | |
| 237 | - | State statewire.State `json:"state"` | |
| 238 | - | Late []domain.WindowID `json:"late"` | |
| 239 | - | Error string `json:"error,omitempty"` | |
| 240 | - | } | |
| 241 | - | ||
| 242 | - | type command struct { | |
| 243 | - | Name string `json:"name"` | |
| 244 | - | Arg string `json:"arg"` | |
| 245 | - | Kind string `json:"kind"` | |
| 246 | - | Caps []string `json:"caps"` | |
| 247 | - | Summary string `json:"summary"` | |
| 248 | - | } | |
| 249 | - | ||
| 250 | - | func capNames(c domain.Caps) []string { | |
| 251 | - | names := []string{} | |
| 252 | - | for _, item := range []struct { | |
| 253 | - | bit domain.Caps | |
| 254 | - | name string | |
| 255 | - | }{{domain.CapRead, "read"}, {domain.CapAct, "act"}, {domain.CapInput, "input"}, {domain.CapCapture, "capture"}, {domain.CapAdmin, "admin"}} { | |
| 256 | - | if c&item.bit != 0 { | |
| 257 | - | names = append(names, item.name) | |
| 258 | - | } | |
| 259 | - | } | |
| 260 | - | return names | |
| 261 | - | } | |
| 262 | - | ||
| 263 | - | var nullID = json.RawMessage("null") | |
| 264 | - | ||
| 265 | - | // maxRequestTimeout caps the client-supplied timeout: core and the shooter | |
| 266 | - | // hold a request at most this long. | |
| 267 | - | const maxRequestTimeout = domain.MaxControlTimeout | |
| 268 | - | ||
| 269 | - | func (s *Server) serve(ctx context.Context, conn *net.UnixConn, out chan<- ports.ControlRequest) { | |
| 270 | - | scanner := bufio.NewScanner(conn) | |
| 271 | - | scanner.Buffer(make([]byte, 4096), 1024*1024) | |
| 272 | - | encoder := json.NewEncoder(conn) | |
| 273 | - | announced := false | |
| 274 | - | for scanner.Scan() { | |
| 275 | - | var req request | |
| 276 | - | if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { | |
| 277 | - | if encoder.Encode(reply{ID: nullID, Error: ports.ControlErrBadRequest}) != nil { | |
| 278 | - | return | |
| 279 | - | } | |
| 280 | - | continue | |
| 281 | - | } | |
| 282 | - | // The id is optional: a request without one gets "id": null back. | |
| 283 | - | if len(req.ID) == 0 { | |
| 284 | - | req.ID = nullID | |
| 285 | - | } | |
| 286 | - | if req.Op == "hello" { | |
| 287 | - | commands := []command{} | |
| 288 | - | for _, spec := range domain.Commands() { | |
| 289 | - | commands = append(commands, command{spec.Name, spec.Arg, spec.Kind.String(), capNames(spec.Caps), spec.Summary}) | |
| 290 | - | } | |
| 291 | - | if encoder.Encode(struct { | |
| 292 | - | ID json.RawMessage `json:"id"` | |
| 293 | - | OK bool `json:"ok"` | |
| 294 | - | V int `json:"v"` | |
| 295 | - | Caps []string `json:"caps"` | |
| 296 | - | Commands []command `json:"commands"` | |
| 297 | - | }{req.ID, true, 1, capNames(domain.CapsAll), commands}) != nil { | |
| 298 | - | return | |
| 299 | - | } | |
| 300 | - | continue | |
| 301 | - | } | |
| 302 | - | finish := func() {} | |
| 303 | - | if req.Op == "do" || req.Op == "inject" { | |
| 304 | - | finish = s.trackQuit() | |
| 305 | - | } | |
| 306 | - | response := s.dispatch(ctx, req, out, &announced) | |
| 307 | - | if ctx.Err() != nil { | |
| 308 | - | finish() | |
| 309 | - | return | |
| 310 | - | } | |
| 311 | - | err := encoder.Encode(response) | |
| 312 | - | finish() | |
| 313 | - | if err != nil { | |
| 314 | - | return | |
| 315 | - | } | |
| 316 | - | } | |
| 317 | - | } | |
| 318 | - | ||
| 319 | - | func (s *Server) dispatch(ctx context.Context, req request, out chan<- ports.ControlRequest, announced *bool) reply { | |
| 320 | - | // The request deadline covers the core wait and the capture together. | |
| 321 | - | start := time.Now() | |
| 322 | - | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} | |
| 323 | - | if req.Op == "shot" && (req.EveryFrame || req.Stop) { | |
| 324 | - | return s.continuousCapture(ctx, req, out) | |
| 325 | - | } | |
| 326 | - | ch := make(chan ports.ControlReply, 1) | |
| 327 | - | var message ports.ControlRequest | |
| 328 | - | var admission chan ports.ControlAdmission | |
| 329 | - | var transaction *xkb.Transaction | |
| 330 | - | locked := false | |
| 331 | - | finishTranslation := func(commit bool) { | |
| 332 | - | if !locked { | |
| 333 | - | return | |
| 334 | - | } | |
| 335 | - | if transaction != nil { | |
| 336 | - | if commit { | |
| 337 | - | transaction.Commit() | |
| 338 | - | } else { | |
| 339 | - | transaction.Rollback() | |
| 340 | - | } | |
| 341 | - | } | |
| 342 | - | locked = false | |
| 343 | - | s.injectMu.Unlock() | |
| 344 | - | } | |
| 345 | - | defer func() { finishTranslation(false) }() | |
| 346 | - | timeout := domain.DefaultControlTimeout | |
| 347 | - | switch req.Op { | |
| 348 | - | case "output-add", "output-rm": | |
| 349 | - | mode := domain.OutputMode{} | |
| 350 | - | if req.Op == "output-add" { | |
| 351 | - | var err error | |
| 352 | - | mode, err = domain.ParseOutputMode(req.Mode) | |
| 353 | - | if err != nil { | |
| 354 | - | return response | |
| 355 | - | } | |
| 356 | - | } else if req.Name == "" { | |
| 357 | - | return response | |
| 358 | - | } | |
| 359 | - | message = ports.ControlOutput{Name: req.Name, Mode: mode, Remove: req.Op == "output-rm", Caps: domain.CapsAll, Reply: ch} | |
| 360 | - | ||
| 361 | - | case "do", "inject", "shot": | |
| 362 | - | shots, err := requestShots(req) | |
| 363 | - | if err != nil { | |
| 364 | - | response.Detail = err.Error() | |
| 365 | - | return response | |
| 366 | - | } | |
| 367 | - | if len(shots) > 0 && s.shooter == nil { | |
| 368 | - | response.Detail = "capture unavailable" | |
| 369 | - | return response | |
| 370 | - | } | |
| 371 | - | wait := domain.DefaultWait | |
| 372 | - | if req.Wait != nil { | |
| 373 | - | var err error | |
| 374 | - | wait, err = domain.ParseWaitLevel(*req.Wait) | |
| 375 | - | if err != nil { | |
| 376 | - | return response | |
| 377 | - | } | |
| 378 | - | } | |
| 379 | - | var until *domain.Until | |
| 380 | - | if req.Until != nil { | |
| 381 | - | parsed, err := domain.ParseUntil(*req.Until) | |
| 382 | - | if err != nil { | |
| 383 | - | return response | |
| 384 | - | } | |
| 385 | - | until = &parsed | |
| 386 | - | } | |
| 387 | - | if req.Timeout != nil { | |
| 388 | - | var err error | |
| 389 | - | timeout, err = time.ParseDuration(*req.Timeout) | |
| 390 | - | if err != nil || timeout <= 0 { | |
| 391 | - | return response | |
| 392 | - | } | |
| 393 | - | if timeout > maxRequestTimeout { | |
| 394 | - | response.Detail = "timeout exceeds 5m" | |
| 395 | - | return response | |
| 396 | - | } | |
| 397 | - | } | |
| 398 | - | if len(shots) > 0 { | |
| 399 | - | wait = domain.WaitPresented | |
| 400 | - | } | |
| 401 | - | if req.Op == "inject" { | |
| 402 | - | s.injectMu.Lock() | |
| 403 | - | locked = true | |
| 404 | - | events, tx, err := s.translate(req, !*announced) | |
| 405 | - | transaction = tx | |
| 406 | - | if err != nil { | |
| 407 | - | return response | |
| 408 | - | } | |
| 409 | - | admission = make(chan ports.ControlAdmission, 1) | |
| 410 | - | message = ports.ControlInject{Admission: admission, Shots: shots, Events: events, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} | |
| 411 | - | } else { | |
| 412 | - | if req.Op == "shot" { | |
| 413 | - | req.Action = "none" | |
| 414 | - | } | |
| 415 | - | if req.Action == "" { | |
| 416 | - | return response | |
| 417 | - | } | |
| 418 | - | message = ports.ControlDo{Shots: shots, Action: req.Action, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} | |
| 419 | - | } | |
| 420 | - | case "query": | |
| 421 | - | if req.What == "" { | |
| 422 | - | return response | |
| 423 | - | } | |
| 424 | - | message = ports.ControlQuery{What: req.What, Caps: domain.CapsAll, Reply: ch} | |
| 425 | - | default: | |
| 426 | - | return response | |
| 427 | - | } | |
| 428 | - | select { | |
| 429 | - | case out <- message: | |
| 430 | - | case <-ctx.Done(): | |
| 431 | - | return response | |
| 432 | - | } | |
| 433 | - | if admission != nil { | |
| 434 | - | select { | |
| 435 | - | case admitted := <-admission: | |
| 436 | - | finishTranslation(admitted.Err == "") | |
| 437 | - | if admitted.Err == "" { | |
| 438 | - | *announced = true | |
| 439 | - | } | |
| 440 | - | case <-ctx.Done(): | |
| 441 | - | return response | |
| 442 | - | } | |
| 443 | - | } | |
| 444 | - | var result ports.ControlReply | |
| 445 | - | select { | |
| 446 | - | case result = <-ch: | |
| 447 | - | case <-ctx.Done(): | |
| 448 | - | return response | |
| 449 | - | } | |
| 450 | - | code := result.Err | |
| 451 | - | response = reply{ID: req.ID, OK: code == "", Done: result.Done.String(), Diff: wireDiff(result.Diff), State: statewire.FromDomain(result.State, s.ids), Late: result.Late, Error: code} | |
| 452 | - | if len(result.Shots) > 0 { | |
| 453 | - | if s.shooter == nil { | |
| 454 | - | response.OK = false | |
| 455 | - | response.Error = ports.ControlErrBadRequest | |
| 456 | - | response.Detail = "capture unavailable" | |
| 457 | - | return response | |
| 458 | - | } | |
| 459 | - | // The capture gets what the core wait left of the request deadline. | |
| 460 | - | shotCtx, cancel := context.WithDeadline(ctx, start.Add(timeout)) | |
| 461 | - | shots, err := s.shooter.Shoot(shotCtx, result.Shots, req.Inline) | |
| 462 | - | cancel() | |
| 463 | - | response.Shots = shots | |
| 464 | - | if err != nil { | |
| 465 | - | response.OK = false | |
| 466 | - | response.Error = ports.ControlErrCaptureFailed | |
| 467 | - | response.Detail = err.Error() | |
| 468 | - | } | |
| 469 | - | } | |
| 470 | - | return response | |
| 471 | - | } | |
| 472 | - | ||
| 473 | - | func requestShots(req request) ([]domain.ShotRequest, error) { | |
| 474 | - | var outputs []string | |
| 475 | - | if req.Op == "shot" { | |
| 476 | - | if req.Raw { | |
| 477 | - | return nil, errors.New("raw shots need --every-frame") | |
| 478 | - | } | |
| 479 | - | outputs = req.Outputs | |
| 480 | - | if len(outputs) == 0 { | |
| 481 | - | outputs = []string{""} | |
| 482 | - | } | |
| 483 | - | } else if len(req.Shot) > 0 { | |
| 484 | - | var enabled bool | |
| 485 | - | if err := json.Unmarshal(req.Shot, &enabled); err == nil { | |
| 486 | - | if !enabled { | |
| 487 | - | return nil, nil | |
| 488 | - | } | |
| 489 | - | outputs = []string{""} | |
| 490 | - | } else { | |
| 491 | - | if err := json.Unmarshal(req.Shot, &outputs); err != nil || outputs == nil { | |
| 492 | - | return nil, errors.New("shot must be true, false or an output list") | |
| 493 | - | } | |
| 494 | - | } | |
| 495 | - | } | |
| 496 | - | shots := make([]domain.ShotRequest, 0, len(outputs)) | |
| 497 | - | for _, output := range outputs { | |
| 498 | - | shots = append(shots, domain.ShotRequest{Output: output}) | |
| 499 | - | } | |
| 500 | - | return shots, nil | |
| 501 | - | } | |
| 502 | - | ||
| 503 | - | // continuousCapture forwards an every-frame start or stop to core, which | |
| 504 | - | // decides it; the default directory is the session's frames directory. | |
| 505 | - | func (s *Server) continuousCapture(ctx context.Context, req request, out chan<- ports.ControlRequest) reply { | |
| 506 | - | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} | |
| 507 | - | if (req.EveryFrame && req.Stop) || req.Inline { | |
| 508 | - | return response | |
| 509 | - | } | |
| 510 | - | dir := req.Dir | |
| 511 | - | if dir == "" { | |
| 512 | - | dir = s.framesDir | |
| 513 | - | } | |
| 514 | - | ack := make(chan ports.ContinuousCaptureResult, 1) | |
| 515 | - | select { | |
| 516 | - | case out <- ports.ControlCapture{Outputs: req.Outputs, Dir: dir, Raw: req.Raw, Stop: req.Stop, Caps: domain.CapsAll, Reply: ack}: | |
| 517 | - | case <-ctx.Done(): | |
| 518 | - | return response | |
| 519 | - | } | |
| 520 | - | select { | |
| 521 | - | case result := <-ack: | |
| 522 | - | response.OK = result.Err == "" | |
| 523 | - | response.Error = result.Err | |
| 524 | - | response.Dir = result.Dir | |
| 525 | - | case <-ctx.Done(): | |
| 526 | - | } | |
| 527 | - | return response | |
| 528 | - | } | |
| @@ -1,528 +0,0 @@ | |||||
| 1 | - | // Package control serves the v1 JSON-lines control protocol on a Unix socket. | |||
| 2 | - | package control | |||
| 3 | - | ||||
| 4 | - | import ( | |||
| 5 | - | "bufio" | |||
| 6 | - | "context" | |||
| 7 | - | "encoding/json" | |||
| 8 | - | "errors" | |||
| 9 | - | "fmt" | |||
| 10 | - | "net" | |||
| 11 | - | "os" | |||
| 12 | - | "path/filepath" | |||
| 13 | - | "sync" | |||
| 14 | - | "syscall" | |||
| 15 | - | "time" | |||
| 16 | - | ||||
| 17 | - | "github.com/bnema/neferwl/internal/adapters/logging" | |||
| 18 | - | "github.com/bnema/neferwl/internal/adapters/statewire" | |||
| 19 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |||
| 20 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |||
| 21 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 22 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 23 | - | "golang.org/x/sys/unix" | |||
| 24 | - | ) | |||
| 25 | - | ||||
| 26 | - | // Server owns a control listener. Requests on each connection are processed in | |||
| 27 | - | // order: the next line is read only after the preceding core reply is sent. | |||
| 28 | - | // Options supplies a dedicated control keymap, never the physical input map. | |||
| 29 | - | // Listen takes ownership of Keymap on success. The server takes ownership of | |||
| 30 | - | // each map it receives from Keymaps; producers own any maps left in the channel | |||
| 31 | - | // after shutdown. Security is sampled before every translated event. | |||
| 32 | - | type Options struct { | |||
| 33 | - | FramesDir string | |||
| 34 | - | Shooter *Shooter | |||
| 35 | - | Keymap *xkb.Keymap | |||
| 36 | - | Keymaps <-chan *xkb.Keymap | |||
| 37 | - | Security ports.SessionSecurity | |||
| 38 | - | } | |||
| 39 | - | ||||
| 40 | - | type Server struct { | |||
| 41 | - | framesDir string | |||
| 42 | - | shooter *Shooter | |||
| 43 | - | quitMu sync.Mutex | |||
| 44 | - | quitReplies map[chan struct{}]struct{} | |||
| 45 | - | injectMu sync.Mutex | |||
| 46 | - | injector *injector | |||
| 47 | - | keymaps <-chan *xkb.Keymap | |||
| 48 | - | listener *net.UnixListener | |||
| 49 | - | ids *workspaceid.IDs | |||
| 50 | - | done chan struct{} | |||
| 51 | - | once sync.Once | |||
| 52 | - | err error | |||
| 53 | - | } | |||
| 54 | - | ||||
| 55 | - | // Listen creates a private socket using the same workspace IDs as statefile. | |||
| 56 | - | // An existing socket is removed only when connecting proves it has no listener. | |||
| 57 | - | func Listen(path string, ids *workspaceid.IDs, opts Options) (*Server, error) { | |||
| 58 | - | if ids == nil { | |||
| 59 | - | return nil, errors.New("workspace IDs are required") | |||
| 60 | - | } | |||
| 61 | - | if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { | |||
| 62 | - | return nil, err | |||
| 63 | - | } | |||
| 64 | - | if info, err := os.Lstat(path); err == nil { | |||
| 65 | - | if info.Mode()&os.ModeSocket == 0 { | |||
| 66 | - | return nil, fmt.Errorf("control path is not a socket: %s", path) | |||
| 67 | - | } | |||
| 68 | - | conn, err := net.DialTimeout("unix", path, time.Second) | |||
| 69 | - | if err == nil { | |||
| 70 | - | conn.Close() | |||
| 71 | - | return nil, fmt.Errorf("control socket already listening: %s", path) | |||
| 72 | - | } | |||
| 73 | - | if !errors.Is(err, syscall.ECONNREFUSED) { | |||
| 74 | - | return nil, err | |||
| 75 | - | } | |||
| 76 | - | if err := os.Remove(path); err != nil { | |||
| 77 | - | return nil, err | |||
| 78 | - | } | |||
| 79 | - | } else if !errors.Is(err, os.ErrNotExist) { | |||
| 80 | - | return nil, err | |||
| 81 | - | } | |||
| 82 | - | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) | |||
| 83 | - | if err != nil { | |||
| 84 | - | return nil, err | |||
| 85 | - | } | |||
| 86 | - | if err := os.Chmod(path, 0o600); err != nil { | |||
| 87 | - | listener.Close() | |||
| 88 | - | return nil, err | |||
| 89 | - | } | |||
| 90 | - | s := &Server{listener: listener, ids: ids, done: make(chan struct{})} | |||
| 91 | - | s.framesDir = opts.FramesDir | |||
| 92 | - | s.shooter = opts.Shooter | |||
| 93 | - | s.keymaps = opts.Keymaps | |||
| 94 | - | if opts.Keymap != nil { | |||
| 95 | - | s.injector = newInjector(opts.Keymap, opts.Security) | |||
| 96 | - | } | |||
| 97 | - | return s, nil | |||
| 98 | - | } | |||
| 99 | - | ||||
| 100 | - | // Close stops acceptance and all active connections. It is safe to call twice. | |||
| 101 | - | func (s *Server) Close() error { | |||
| 102 | - | s.once.Do(func() { | |||
| 103 | - | close(s.done) | |||
| 104 | - | s.err = s.listener.Close() | |||
| 105 | - | s.injectMu.Lock() | |||
| 106 | - | defer s.injectMu.Unlock() | |||
| 107 | - | if s.injector != nil { | |||
| 108 | - | s.injector.km.Close() | |||
| 109 | - | s.injector = nil | |||
| 110 | - | } | |||
| 111 | - | }) | |||
| 112 | - | return s.err | |||
| 113 | - | } | |||
| 114 | - | ||||
| 115 | - | // WaitQuitReplies lets shutdown flush outstanding quit replies before cancelling | |||
| 116 | - | // control connections. The caller bounds the wait in case a peer stops reading. | |||
| 117 | - | func (s *Server) WaitQuitReplies(ctx context.Context) { | |||
| 118 | - | s.quitMu.Lock() | |||
| 119 | - | pending := make([]chan struct{}, 0, len(s.quitReplies)) | |||
| 120 | - | for done := range s.quitReplies { | |||
| 121 | - | pending = append(pending, done) | |||
| 122 | - | } | |||
| 123 | - | s.quitMu.Unlock() | |||
| 124 | - | for _, done := range pending { | |||
| 125 | - | select { | |||
| 126 | - | case <-done: | |||
| 127 | - | case <-ctx.Done(): | |||
| 128 | - | return | |||
| 129 | - | } | |||
| 130 | - | } | |||
| 131 | - | } | |||
| 132 | - | ||||
| 133 | - | func (s *Server) trackQuit() func() { | |||
| 134 | - | done := make(chan struct{}) | |||
| 135 | - | s.quitMu.Lock() | |||
| 136 | - | if s.quitReplies == nil { | |||
| 137 | - | s.quitReplies = make(map[chan struct{}]struct{}) | |||
| 138 | - | } | |||
| 139 | - | s.quitReplies[done] = struct{}{} | |||
| 140 | - | s.quitMu.Unlock() | |||
| 141 | - | return func() { | |||
| 142 | - | s.quitMu.Lock() | |||
| 143 | - | delete(s.quitReplies, done) | |||
| 144 | - | close(done) | |||
| 145 | - | s.quitMu.Unlock() | |||
| 146 | - | } | |||
| 147 | - | } | |||
| 148 | - | ||||
| 149 | - | // Run accepts connections until cancellation or Close, waiting for handlers to exit. | |||
| 150 | - | func (s *Server) Run(ctx context.Context, out chan<- ports.ControlRequest) error { | |||
| 151 | - | ctx, cancel := context.WithCancel(ctx) | |||
| 152 | - | stop := context.AfterFunc(ctx, func() { _ = s.Close() }) | |||
| 153 | - | defer stop() | |||
| 154 | - | var workers sync.WaitGroup | |||
| 155 | - | defer workers.Wait() | |||
| 156 | - | defer cancel() | |||
| 157 | - | log := logging.For(ctx, "control") | |||
| 158 | - | log.Info().Str("path", s.listener.Addr().String()).Msg("listening") | |||
| 159 | - | for { | |||
| 160 | - | conn, err := s.listener.AcceptUnix() | |||
| 161 | - | if err != nil { | |||
| 162 | - | if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { | |||
| 163 | - | return nil | |||
| 164 | - | } | |||
| 165 | - | return err | |||
| 166 | - | } | |||
| 167 | - | workers.Add(1) | |||
| 168 | - | go func() { | |||
| 169 | - | defer workers.Done() | |||
| 170 | - | defer conn.Close() | |||
| 171 | - | connCtx, cancel := context.WithCancel(ctx) | |||
| 172 | - | defer cancel() | |||
| 173 | - | go func() { | |||
| 174 | - | select { | |||
| 175 | - | case <-s.done: | |||
| 176 | - | cancel() | |||
| 177 | - | case <-connCtx.Done(): | |||
| 178 | - | } | |||
| 179 | - | }() | |||
| 180 | - | stop := context.AfterFunc(connCtx, func() { _ = conn.Close() }) | |||
| 181 | - | defer stop() | |||
| 182 | - | if !sameUID(conn) { | |||
| 183 | - | log.Warn().Msg("peer rejected") | |||
| 184 | - | return | |||
| 185 | - | } | |||
| 186 | - | s.serve(connCtx, conn, out) | |||
| 187 | - | }() | |||
| 188 | - | } | |||
| 189 | - | } | |||
| 190 | - | ||||
| 191 | - | func sameUID(conn *net.UnixConn) bool { | |||
| 192 | - | raw, err := conn.SyscallConn() | |||
| 193 | - | if err != nil { | |||
| 194 | - | return false | |||
| 195 | - | } | |||
| 196 | - | var cred *unix.Ucred | |||
| 197 | - | var credErr error | |||
| 198 | - | if err := raw.Control(func(fd uintptr) { cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) }); err != nil { | |||
| 199 | - | return false | |||
| 200 | - | } | |||
| 201 | - | return credErr == nil && cred != nil && cred.Uid == uint32(os.Getuid()) | |||
| 202 | - | } | |||
| 203 | - | ||||
| 204 | - | type request struct { | |||
| 205 | - | EveryFrame bool `json:"every_frame"` | |||
| 206 | - | Stop bool `json:"stop"` | |||
| 207 | - | Name string `json:"name"` | |||
| 208 | - | Mode string `json:"mode"` | |||
| 209 | - | Outputs []string `json:"outputs"` | |||
| 210 | - | Inline bool `json:"inline"` | |||
| 211 | - | Raw bool `json:"raw"` | |||
| 212 | - | Shot json.RawMessage `json:"shot"` | |||
| 213 | - | ID json.RawMessage `json:"id"` | |||
| 214 | - | Op string `json:"op"` | |||
| 215 | - | Action string `json:"action"` | |||
| 216 | - | What string `json:"what"` | |||
| 217 | - | Wait *string `json:"wait"` | |||
| 218 | - | Until *string `json:"until"` | |||
| 219 | - | Timeout *string `json:"timeout"` | |||
| 220 | - | Kind string `json:"kind"` | |||
| 221 | - | Combo string `json:"combo"` | |||
| 222 | - | Text string `json:"text"` | |||
| 223 | - | Cmd string `json:"cmd"` | |||
| 224 | - | Args []string `json:"args"` | |||
| 225 | - | Fingers int `json:"fingers"` | |||
| 226 | - | Dir string `json:"dir"` | |||
| 227 | - | } | |||
| 228 | - | ||||
| 229 | - | type reply struct { | |||
| 230 | - | Dir string `json:"dir,omitempty"` | |||
| 231 | - | Shots []Shot `json:"shots,omitempty"` | |||
| 232 | - | Detail string `json:"detail,omitempty"` | |||
| 233 | - | ID json.RawMessage `json:"id"` | |||
| 234 | - | OK bool `json:"ok"` | |||
| 235 | - | Done string `json:"done"` | |||
| 236 | - | Diff diff `json:"diff"` | |||
| 237 | - | State statewire.State `json:"state"` | |||
| 238 | - | Late []domain.WindowID `json:"late"` | |||
| 239 | - | Error string `json:"error,omitempty"` | |||
| 240 | - | } | |||
| 241 | - | ||||
| 242 | - | type command struct { | |||
| 243 | - | Name string `json:"name"` | |||
| 244 | - | Arg string `json:"arg"` | |||
| 245 | - | Kind string `json:"kind"` | |||
| 246 | - | Caps []string `json:"caps"` | |||
| 247 | - | Summary string `json:"summary"` | |||
| 248 | - | } | |||
| 249 | - | ||||
| 250 | - | func capNames(c domain.Caps) []string { | |||
| 251 | - | names := []string{} | |||
| 252 | - | for _, item := range []struct { | |||
| 253 | - | bit domain.Caps | |||
| 254 | - | name string | |||
| 255 | - | }{{domain.CapRead, "read"}, {domain.CapAct, "act"}, {domain.CapInput, "input"}, {domain.CapCapture, "capture"}, {domain.CapAdmin, "admin"}} { | |||
| 256 | - | if c&item.bit != 0 { | |||
| 257 | - | names = append(names, item.name) | |||
| 258 | - | } | |||
| 259 | - | } | |||
| 260 | - | return names | |||
| 261 | - | } | |||
| 262 | - | ||||
| 263 | - | var nullID = json.RawMessage("null") | |||
| 264 | - | ||||
| 265 | - | // maxRequestTimeout caps the client-supplied timeout: core and the shooter | |||
| 266 | - | // hold a request at most this long. | |||
| 267 | - | const maxRequestTimeout = domain.MaxControlTimeout | |||
| 268 | - | ||||
| 269 | - | func (s *Server) serve(ctx context.Context, conn *net.UnixConn, out chan<- ports.ControlRequest) { | |||
| 270 | - | scanner := bufio.NewScanner(conn) | |||
| 271 | - | scanner.Buffer(make([]byte, 4096), 1024*1024) | |||
| 272 | - | encoder := json.NewEncoder(conn) | |||
| 273 | - | announced := false | |||
| 274 | - | for scanner.Scan() { | |||
| 275 | - | var req request | |||
| 276 | - | if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { | |||
| 277 | - | if encoder.Encode(reply{ID: nullID, Error: ports.ControlErrBadRequest}) != nil { | |||
| 278 | - | return | |||
| 279 | - | } | |||
| 280 | - | continue | |||
| 281 | - | } | |||
| 282 | - | // The id is optional: a request without one gets "id": null back. | |||
| 283 | - | if len(req.ID) == 0 { | |||
| 284 | - | req.ID = nullID | |||
| 285 | - | } | |||
| 286 | - | if req.Op == "hello" { | |||
| 287 | - | commands := []command{} | |||
| 288 | - | for _, spec := range domain.Commands() { | |||
| 289 | - | commands = append(commands, command{spec.Name, spec.Arg, spec.Kind.String(), capNames(spec.Caps), spec.Summary}) | |||
| 290 | - | } | |||
| 291 | - | if encoder.Encode(struct { | |||
| 292 | - | ID json.RawMessage `json:"id"` | |||
| 293 | - | OK bool `json:"ok"` | |||
| 294 | - | V int `json:"v"` | |||
| 295 | - | Caps []string `json:"caps"` | |||
| 296 | - | Commands []command `json:"commands"` | |||
| 297 | - | }{req.ID, true, 1, capNames(domain.CapsAll), commands}) != nil { | |||
| 298 | - | return | |||
| 299 | - | } | |||
| 300 | - | continue | |||
| 301 | - | } | |||
| 302 | - | finish := func() {} | |||
| 303 | - | if req.Op == "do" || req.Op == "inject" { | |||
| 304 | - | finish = s.trackQuit() | |||
| 305 | - | } | |||
| 306 | - | response := s.dispatch(ctx, req, out, &announced) | |||
| 307 | - | if ctx.Err() != nil { | |||
| 308 | - | finish() | |||
| 309 | - | return | |||
| 310 | - | } | |||
| 311 | - | err := encoder.Encode(response) | |||
| 312 | - | finish() | |||
| 313 | - | if err != nil { | |||
| 314 | - | return | |||
| 315 | - | } | |||
| 316 | - | } | |||
| 317 | - | } | |||
| 318 | - | ||||
| 319 | - | func (s *Server) dispatch(ctx context.Context, req request, out chan<- ports.ControlRequest, announced *bool) reply { | |||
| 320 | - | // The request deadline covers the core wait and the capture together. | |||
| 321 | - | start := time.Now() | |||
| 322 | - | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} | |||
| 323 | - | if req.Op == "shot" && (req.EveryFrame || req.Stop) { | |||
| 324 | - | return s.continuousCapture(ctx, req, out) | |||
| 325 | - | } | |||
| 326 | - | ch := make(chan ports.ControlReply, 1) | |||
| 327 | - | var message ports.ControlRequest | |||
| 328 | - | var admission chan ports.ControlAdmission | |||
| 329 | - | var transaction *xkb.Transaction | |||
| 330 | - | locked := false | |||
| 331 | - | finishTranslation := func(commit bool) { | |||
| 332 | - | if !locked { | |||
| 333 | - | return | |||
| 334 | - | } | |||
| 335 | - | if transaction != nil { | |||
| 336 | - | if commit { | |||
| 337 | - | transaction.Commit() | |||
| 338 | - | } else { | |||
| 339 | - | transaction.Rollback() | |||
| 340 | - | } | |||
| 341 | - | } | |||
| 342 | - | locked = false | |||
| 343 | - | s.injectMu.Unlock() | |||
| 344 | - | } | |||
| 345 | - | defer func() { finishTranslation(false) }() | |||
| 346 | - | timeout := domain.DefaultControlTimeout | |||
| 347 | - | switch req.Op { | |||
| 348 | - | case "output-add", "output-rm": | |||
| 349 | - | mode := domain.OutputMode{} | |||
| 350 | - | if req.Op == "output-add" { | |||
| 351 | - | var err error | |||
| 352 | - | mode, err = domain.ParseOutputMode(req.Mode) | |||
| 353 | - | if err != nil { | |||
| 354 | - | return response | |||
| 355 | - | } | |||
| 356 | - | } else if req.Name == "" { | |||
| 357 | - | return response | |||
| 358 | - | } | |||
| 359 | - | message = ports.ControlOutput{Name: req.Name, Mode: mode, Remove: req.Op == "output-rm", Caps: domain.CapsAll, Reply: ch} | |||
| 360 | - | ||||
| 361 | - | case "do", "inject", "shot": | |||
| 362 | - | shots, err := requestShots(req) | |||
| 363 | - | if err != nil { | |||
| 364 | - | response.Detail = err.Error() | |||
| 365 | - | return response | |||
| 366 | - | } | |||
| 367 | - | if len(shots) > 0 && s.shooter == nil { | |||
| 368 | - | response.Detail = "capture unavailable" | |||
| 369 | - | return response | |||
| 370 | - | } | |||
| 371 | - | wait := domain.DefaultWait | |||
| 372 | - | if req.Wait != nil { | |||
| 373 | - | var err error | |||
| 374 | - | wait, err = domain.ParseWaitLevel(*req.Wait) | |||
| 375 | - | if err != nil { | |||
| 376 | - | return response | |||
| 377 | - | } | |||
| 378 | - | } | |||
| 379 | - | var until *domain.Until | |||
| 380 | - | if req.Until != nil { | |||
| 381 | - | parsed, err := domain.ParseUntil(*req.Until) | |||
| 382 | - | if err != nil { | |||
| 383 | - | return response | |||
| 384 | - | } | |||
| 385 | - | until = &parsed | |||
| 386 | - | } | |||
| 387 | - | if req.Timeout != nil { | |||
| 388 | - | var err error | |||
| 389 | - | timeout, err = time.ParseDuration(*req.Timeout) | |||
| 390 | - | if err != nil || timeout <= 0 { | |||
| 391 | - | return response | |||
| 392 | - | } | |||
| 393 | - | if timeout > maxRequestTimeout { | |||
| 394 | - | response.Detail = "timeout exceeds 5m" | |||
| 395 | - | return response | |||
| 396 | - | } | |||
| 397 | - | } | |||
| 398 | - | if len(shots) > 0 { | |||
| 399 | - | wait = domain.WaitPresented | |||
| 400 | - | } | |||
| 401 | - | if req.Op == "inject" { | |||
| 402 | - | s.injectMu.Lock() | |||
| 403 | - | locked = true | |||
| 404 | - | events, tx, err := s.translate(req, !*announced) | |||
| 405 | - | transaction = tx | |||
| 406 | - | if err != nil { | |||
| 407 | - | return response | |||
| 408 | - | } | |||
| 409 | - | admission = make(chan ports.ControlAdmission, 1) | |||
| 410 | - | message = ports.ControlInject{Admission: admission, Shots: shots, Events: events, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} | |||
| 411 | - | } else { | |||
| 412 | - | if req.Op == "shot" { | |||
| 413 | - | req.Action = "none" | |||
| 414 | - | } | |||
| 415 | - | if req.Action == "" { | |||
| 416 | - | return response | |||
| 417 | - | } | |||
| 418 | - | message = ports.ControlDo{Shots: shots, Action: req.Action, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} | |||
| 419 | - | } | |||
| 420 | - | case "query": | |||
| 421 | - | if req.What == "" { | |||
| 422 | - | return response | |||
| 423 | - | } | |||
| 424 | - | message = ports.ControlQuery{What: req.What, Caps: domain.CapsAll, Reply: ch} | |||
| 425 | - | default: | |||
| 426 | - | return response | |||
| 427 | - | } | |||
| 428 | - | select { | |||
| 429 | - | case out <- message: | |||
| 430 | - | case <-ctx.Done(): | |||
| 431 | - | return response | |||
| 432 | - | } | |||
| 433 | - | if admission != nil { | |||
| 434 | - | select { | |||
| 435 | - | case admitted := <-admission: | |||
| 436 | - | finishTranslation(admitted.Err == "") | |||
| 437 | - | if admitted.Err == "" { | |||
| 438 | - | *announced = true | |||
| 439 | - | } | |||
| 440 | - | case <-ctx.Done(): | |||
| 441 | - | return response | |||
| 442 | - | } | |||
| 443 | - | } | |||
| 444 | - | var result ports.ControlReply | |||
| 445 | - | select { | |||
| 446 | - | case result = <-ch: | |||
| 447 | - | case <-ctx.Done(): | |||
| 448 | - | return response | |||
| 449 | - | } | |||
| 450 | - | code := result.Err | |||
| 451 | - | response = reply{ID: req.ID, OK: code == "", Done: result.Done.String(), Diff: wireDiff(result.Diff), State: statewire.FromDomain(result.State, s.ids), Late: result.Late, Error: code} | |||
| 452 | - | if len(result.Shots) > 0 { | |||
| 453 | - | if s.shooter == nil { | |||
| 454 | - | response.OK = false | |||
| 455 | - | response.Error = ports.ControlErrBadRequest | |||
| 456 | - | response.Detail = "capture unavailable" | |||
| 457 | - | return response | |||
| 458 | - | } | |||
| 459 | - | // The capture gets what the core wait left of the request deadline. | |||
| 460 | - | shotCtx, cancel := context.WithDeadline(ctx, start.Add(timeout)) | |||
| 461 | - | shots, err := s.shooter.Shoot(shotCtx, result.Shots, req.Inline) | |||
| 462 | - | cancel() | |||
| 463 | - | response.Shots = shots | |||
| 464 | - | if err != nil { | |||
| 465 | - | response.OK = false | |||
| 466 | - | response.Error = ports.ControlErrCaptureFailed | |||
| 467 | - | response.Detail = err.Error() | |||
| 468 | - | } | |||
| 469 | - | } | |||
| 470 | - | return response | |||
| 471 | - | } | |||
| 472 | - | ||||
| 473 | - | func requestShots(req request) ([]domain.ShotRequest, error) { | |||
| 474 | - | var outputs []string | |||
| 475 | - | if req.Op == "shot" { | |||
| 476 | - | if req.Raw { | |||
| 477 | - | return nil, errors.New("raw shots need --every-frame") | |||
| 478 | - | } | |||
| 479 | - | outputs = req.Outputs | |||
| 480 | - | if len(outputs) == 0 { | |||
| 481 | - | outputs = []string{""} | |||
| 482 | - | } | |||
| 483 | - | } else if len(req.Shot) > 0 { | |||
| 484 | - | var enabled bool | |||
| 485 | - | if err := json.Unmarshal(req.Shot, &enabled); err == nil { | |||
| 486 | - | if !enabled { | |||
| 487 | - | return nil, nil | |||
| 488 | - | } | |||
| 489 | - | outputs = []string{""} | |||
| 490 | - | } else { | |||
| 491 | - | if err := json.Unmarshal(req.Shot, &outputs); err != nil || outputs == nil { | |||
| 492 | - | return nil, errors.New("shot must be true, false or an output list") | |||
| 493 | - | } | |||
| 494 | - | } | |||
| 495 | - | } | |||
| 496 | - | shots := make([]domain.ShotRequest, 0, len(outputs)) | |||
| 497 | - | for _, output := range outputs { | |||
| 498 | - | shots = append(shots, domain.ShotRequest{Output: output}) | |||
| 499 | - | } | |||
| 500 | - | return shots, nil | |||
| 501 | - | } | |||
| 502 | - | ||||
| 503 | - | // continuousCapture forwards an every-frame start or stop to core, which | |||
| 504 | - | // decides it; the default directory is the session's frames directory. | |||
| 505 | - | func (s *Server) continuousCapture(ctx context.Context, req request, out chan<- ports.ControlRequest) reply { | |||
| 506 | - | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} | |||
| 507 | - | if (req.EveryFrame && req.Stop) || req.Inline { | |||
| 508 | - | return response | |||
| 509 | - | } | |||
| 510 | - | dir := req.Dir | |||
| 511 | - | if dir == "" { | |||
| 512 | - | dir = s.framesDir | |||
| 513 | - | } | |||
| 514 | - | ack := make(chan ports.ContinuousCaptureResult, 1) | |||
| 515 | - | select { | |||
| 516 | - | case out <- ports.ControlCapture{Outputs: req.Outputs, Dir: dir, Raw: req.Raw, Stop: req.Stop, Caps: domain.CapsAll, Reply: ack}: | |||
| 517 | - | case <-ctx.Done(): | |||
| 518 | - | return response | |||
| 519 | - | } | |||
| 520 | - | select { | |||
| 521 | - | case result := <-ack: | |||
| 522 | - | response.OK = result.Err == "" | |||
| 523 | - | response.Error = result.Err | |||
| 524 | - | response.Dir = result.Dir | |||
| 525 | - | case <-ctx.Done(): | |||
| 526 | - | } | |||
| 527 | - | return response | |||
| 528 | - | } | |||
D internal/adapters/control/control_test.go +0 -361
| @@ -1,361 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "bufio" | |
| 5 | - | "context" | |
| 6 | - | "encoding/json" | |
| 7 | - | "net" | |
| 8 | - | "os" | |
| 9 | - | "path/filepath" | |
| 10 | - | "reflect" | |
| 11 | - | "testing" | |
| 12 | - | "time" | |
| 13 | - | ||
| 14 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |
| 15 | - | "github.com/bnema/neferwl/internal/domain" | |
| 16 | - | "github.com/bnema/neferwl/internal/ports" | |
| 17 | - | ) | |
| 18 | - | ||
| 19 | - | //testpolicy:realtime Unix socket exchanges and server shutdown need bounded waits outside synctest. | |
| 20 | - | func TestProtocol(t *testing.T) { | |
| 21 | - | path := filepath.Join(t.TempDir(), "session", "control.sock") | |
| 22 | - | s, err := Listen(path, workspaceid.WithPrefix("test"), Options{}) | |
| 23 | - | if err != nil { | |
| 24 | - | t.Fatal(err) | |
| 25 | - | } | |
| 26 | - | defer s.Close() | |
| 27 | - | for path, want := range map[string]os.FileMode{filepath.Dir(path): 0o700, path: 0o600} { | |
| 28 | - | info, err := os.Stat(path) | |
| 29 | - | if err != nil || info.Mode().Perm() != want { | |
| 30 | - | t.Fatalf("permissions %s: %v %v", path, info, err) | |
| 31 | - | } | |
| 32 | - | } | |
| 33 | - | ctx, cancel := context.WithCancel(context.Background()) | |
| 34 | - | defer cancel() | |
| 35 | - | out := make(chan ports.ControlRequest) | |
| 36 | - | done := make(chan error, 1) | |
| 37 | - | go func() { done <- s.Run(ctx, out) }() | |
| 38 | - | conn, err := net.Dial("unix", path) | |
| 39 | - | if err != nil { | |
| 40 | - | t.Fatal(err) | |
| 41 | - | } | |
| 42 | - | defer conn.Close() | |
| 43 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |
| 44 | - | t.Fatal(err) | |
| 45 | - | } | |
| 46 | - | reader := bufio.NewReader(conn) | |
| 47 | - | exchange := func(line string) map[string]json.RawMessage { | |
| 48 | - | t.Helper() | |
| 49 | - | if _, err := conn.Write([]byte(line + "\n")); err != nil { | |
| 50 | - | t.Fatal(err) | |
| 51 | - | } | |
| 52 | - | data, err := reader.ReadBytes('\n') | |
| 53 | - | if err != nil { | |
| 54 | - | t.Fatal(err) | |
| 55 | - | } | |
| 56 | - | var got map[string]json.RawMessage | |
| 57 | - | if err := json.Unmarshal(data, &got); err != nil { | |
| 58 | - | t.Fatal(err) | |
| 59 | - | } | |
| 60 | - | return got | |
| 61 | - | } | |
| 62 | - | hello := exchange(`{"id":"hello","op":"hello"}`) | |
| 63 | - | if string(hello["id"]) != `"hello"` || string(hello["ok"]) != "true" || string(hello["v"]) != "1" { | |
| 64 | - | t.Fatal(hello) | |
| 65 | - | } | |
| 66 | - | // A line that is not JSON has no id to echo: null. | |
| 67 | - | if bad := exchange(`{broken`); string(bad["id"]) != "null" || string(bad["error"]) != `"bad-request"` { | |
| 68 | - | t.Fatal(bad) | |
| 69 | - | } | |
| 70 | - | if long := exchange(`{"id":9,"op":"do","action":"none","timeout":"6m"}`); string(long["detail"]) != `"timeout exceeds 5m"` { | |
| 71 | - | t.Fatal(long) | |
| 72 | - | } | |
| 73 | - | // The id is optional and echoed as null. | |
| 74 | - | if anon := exchange(`{"op":"hello"}`); string(anon["id"]) != "null" || string(anon["ok"]) != "true" { | |
| 75 | - | t.Fatal(anon) | |
| 76 | - | } | |
| 77 | - | var commands []command | |
| 78 | - | if err := json.Unmarshal(hello["commands"], &commands); err != nil { | |
| 79 | - | t.Fatal(err) | |
| 80 | - | } | |
| 81 | - | if len(commands) != len(domain.Commands()) || commands[0].Name != domain.Commands()[0].Name || len(commands[0].Caps) == 0 { | |
| 82 | - | t.Fatal(commands) | |
| 83 | - | } | |
| 84 | - | for i, spec := range domain.Commands() { | |
| 85 | - | if commands[i].Kind != spec.Kind.String() { | |
| 86 | - | t.Errorf("command %q kind = %q, want %q", spec.Name, commands[i].Kind, spec.Kind.String()) | |
| 87 | - | } | |
| 88 | - | } | |
| 89 | - | var caps []string | |
| 90 | - | if err := json.Unmarshal(hello["caps"], &caps); err != nil { | |
| 91 | - | t.Fatal(err) | |
| 92 | - | } | |
| 93 | - | if !reflect.DeepEqual(caps, []string{"read", "act", "input", "capture", "admin"}) { | |
| 94 | - | t.Fatal(caps) | |
| 95 | - | } | |
| 96 | - | for _, line := range []string{`{broken`, `{"id":2,"op":"unknown"}`, `{"id":3,"op":"do","action":"none","wait":"bad"}`, `{"id":4,"op":"do","action":"none","until":"bad"}`, `{"id":5,"op":"do","action":"none","timeout":"bad"}`, `{"id":5,"op":"do","action":"none","timeout":"6m"}`, `{"op":"do"}`} { | |
| 97 | - | got := exchange(line) | |
| 98 | - | if string(got["error"]) != `"bad-request"` || string(got["ok"]) != "false" { | |
| 99 | - | t.Fatal(got) | |
| 100 | - | } | |
| 101 | - | } | |
| 102 | - | coreDone := make(chan struct{}) | |
| 103 | - | go func() { | |
| 104 | - | defer close(coreDone) | |
| 105 | - | for i := 0; i < 3; i++ { | |
| 106 | - | select { | |
| 107 | - | case message := <-out: | |
| 108 | - | switch req := message.(type) { | |
| 109 | - | case ports.ControlDo: | |
| 110 | - | if req.Action != "none" || req.Caps != domain.CapsAll || cap(req.Reply) != 1 { | |
| 111 | - | t.Errorf("do: %+v", req) | |
| 112 | - | } | |
| 113 | - | if i == 0 { | |
| 114 | - | if req.Wait != domain.WaitPresented || req.Timeout != 2*time.Second || req.Until == nil || req.Until.Kind != domain.UntilFocused || req.Until.AppID != "foot" { | |
| 115 | - | t.Errorf("explicit: %+v", req) | |
| 116 | - | } | |
| 117 | - | } else if req.Wait != domain.DefaultWait || req.Timeout != 10*time.Second || req.Until != nil { | |
| 118 | - | t.Errorf("defaults: %+v", req) | |
| 119 | - | } | |
| 120 | - | // Core may reach less than the requested level; preserve its report. | |
| 121 | - | timedOut := "" | |
| 122 | - | if i == 1 { | |
| 123 | - | timedOut = ports.ControlErrTimeout | |
| 124 | - | } | |
| 125 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted, Err: timedOut, Diff: domain.StateDiff{FocusFrom: 1, FocusTo: 2, FocusChanged: true}, Late: []domain.WindowID{3}} | |
| 126 | - | case ports.ControlQuery: | |
| 127 | - | if req.What != "state" || req.Caps != domain.CapsAll || cap(req.Reply) != 1 { | |
| 128 | - | t.Errorf("query: %+v", req) | |
| 129 | - | } | |
| 130 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted, State: domain.State{Outputs: []domain.OutputState{{Name: "A", WorkspaceID: 7}}}} | |
| 131 | - | default: | |
| 132 | - | t.Errorf("unexpected %T", message) | |
| 133 | - | } | |
| 134 | - | case <-ctx.Done(): | |
| 135 | - | return | |
| 136 | - | } | |
| 137 | - | } | |
| 138 | - | }() | |
| 139 | - | got := exchange(`{"id":6,"op":"do","action":"none","wait":"presented","until":"focused app_id=foot","timeout":"2s"}`) | |
| 140 | - | if string(got["id"]) != "6" || string(got["done"]) != `"committed"` || string(got["ok"]) != "true" { | |
| 141 | - | t.Fatal(got) | |
| 142 | - | } | |
| 143 | - | if _, present := got["error"]; present { | |
| 144 | - | t.Fatalf("successful reply includes error: %s", got["error"]) | |
| 145 | - | } | |
| 146 | - | var d map[string]any | |
| 147 | - | if err := json.Unmarshal(got["diff"], &d); err != nil { | |
| 148 | - | t.Fatal(err) | |
| 149 | - | } | |
| 150 | - | if d["focus_from"] != float64(1) || d["focus_to"] != float64(2) || d["focus_changed"] != true { | |
| 151 | - | t.Fatal(d) | |
| 152 | - | } | |
| 153 | - | got = exchange(`{"id":7,"op":"do","action":"none"}`) | |
| 154 | - | if string(got["error"]) != `"timeout"` || string(got["late"]) != "[3]" { | |
| 155 | - | t.Fatal(got) | |
| 156 | - | } | |
| 157 | - | got = exchange(`{"id":8,"op":"query","what":"state"}`) | |
| 158 | - | var state struct { | |
| 159 | - | Outputs []struct { | |
| 160 | - | WorkspaceID string `json:"workspace_id"` | |
| 161 | - | } | |
| 162 | - | } | |
| 163 | - | if err := json.Unmarshal(got["state"], &state); err != nil { | |
| 164 | - | t.Fatal(err) | |
| 165 | - | } | |
| 166 | - | if len(state.Outputs) != 1 || state.Outputs[0].WorkspaceID != "test-7" { | |
| 167 | - | t.Fatal(state) | |
| 168 | - | } | |
| 169 | - | <-coreDone | |
| 170 | - | // Leave one request awaiting core forever; cancellation must release it. | |
| 171 | - | if _, err := conn.Write([]byte("{\"id\":9,\"op\":\"query\",\"what\":\"state\"}\n")); err != nil { | |
| 172 | - | t.Fatal(err) | |
| 173 | - | } | |
| 174 | - | select { | |
| 175 | - | case <-out: | |
| 176 | - | case <-time.After(10 * time.Second): | |
| 177 | - | t.Fatal("request not received") | |
| 178 | - | } | |
| 179 | - | cancel() | |
| 180 | - | select { | |
| 181 | - | case err := <-done: | |
| 182 | - | if err != nil { | |
| 183 | - | t.Fatal(err) | |
| 184 | - | } | |
| 185 | - | case <-time.After(10 * time.Second): | |
| 186 | - | t.Fatal("Run did not stop") | |
| 187 | - | } | |
| 188 | - | } | |
| 189 | - | ||
| 190 | - | func TestListenPreservesLiveSocketAndFiles(t *testing.T) { | |
| 191 | - | path := filepath.Join(t.TempDir(), "control.sock") | |
| 192 | - | ids := workspaceid.WithPrefix("test") | |
| 193 | - | s, err := Listen(path, ids, Options{}) | |
| 194 | - | if err != nil { | |
| 195 | - | t.Fatal(err) | |
| 196 | - | } | |
| 197 | - | defer s.Close() | |
| 198 | - | if other, err := Listen(path, ids, Options{}); err == nil { | |
| 199 | - | other.Close() | |
| 200 | - | t.Fatal("replaced live listener") | |
| 201 | - | } | |
| 202 | - | if err := s.Close(); err != nil { | |
| 203 | - | t.Fatal(err) | |
| 204 | - | } | |
| 205 | - | if err := os.WriteFile(path, []byte("keep"), 0o600); err != nil { | |
| 206 | - | t.Fatal(err) | |
| 207 | - | } | |
| 208 | - | if other, err := Listen(path, ids, Options{}); err == nil { | |
| 209 | - | other.Close() | |
| 210 | - | t.Fatal("replaced regular file") | |
| 211 | - | } | |
| 212 | - | data, err := os.ReadFile(path) | |
| 213 | - | if err != nil || string(data) != "keep" { | |
| 214 | - | t.Fatal(string(data), err) | |
| 215 | - | } | |
| 216 | - | } | |
| 217 | - | ||
| 218 | - | func TestListenRemovesStaleSocket(t *testing.T) { | |
| 219 | - | path := filepath.Join(t.TempDir(), "control.sock") | |
| 220 | - | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) | |
| 221 | - | if err != nil { | |
| 222 | - | t.Fatal(err) | |
| 223 | - | } | |
| 224 | - | listener.SetUnlinkOnClose(false) | |
| 225 | - | if err := listener.Close(); err != nil { | |
| 226 | - | t.Fatal(err) | |
| 227 | - | } | |
| 228 | - | s, err := Listen(path, workspaceid.WithPrefix("test"), Options{}) | |
| 229 | - | if err != nil { | |
| 230 | - | t.Fatal(err) | |
| 231 | - | } | |
| 232 | - | if err := s.Close(); err != nil { | |
| 233 | - | t.Fatal(err) | |
| 234 | - | } | |
| 235 | - | } | |
| 236 | - | ||
| 237 | - | //testpolicy:realtime Socket reads and cancellation completion are bounded real I/O waits. | |
| 238 | - | func TestConnectionOrderingAndClose(t *testing.T) { | |
| 239 | - | s, err := Listen(filepath.Join(t.TempDir(), "control.sock"), workspaceid.WithPrefix("test"), Options{}) | |
| 240 | - | if err != nil { | |
| 241 | - | t.Fatal(err) | |
| 242 | - | } | |
| 243 | - | defer s.Close() | |
| 244 | - | ctx, cancel := context.WithCancel(context.Background()) | |
| 245 | - | defer cancel() | |
| 246 | - | out := make(chan ports.ControlRequest, 2) | |
| 247 | - | done := make(chan error, 1) | |
| 248 | - | go func() { done <- s.Run(ctx, out) }() | |
| 249 | - | conn, err := net.Dial("unix", s.listener.Addr().String()) | |
| 250 | - | if err != nil { | |
| 251 | - | t.Fatal(err) | |
| 252 | - | } | |
| 253 | - | defer conn.Close() | |
| 254 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |
| 255 | - | t.Fatal(err) | |
| 256 | - | } | |
| 257 | - | if _, err := conn.Write([]byte("{\"id\":1,\"op\":\"query\",\"what\":\"state\"}\n{\"id\":2,\"op\":\"query\",\"what\":\"state\"}\n")); err != nil { | |
| 258 | - | t.Fatal(err) | |
| 259 | - | } | |
| 260 | - | var first ports.ControlQuery | |
| 261 | - | select { | |
| 262 | - | case req := <-out: | |
| 263 | - | first = req.(ports.ControlQuery) | |
| 264 | - | case <-time.After(10 * time.Second): | |
| 265 | - | t.Fatal("first request missing") | |
| 266 | - | } | |
| 267 | - | // A second connection's hello is an I/O barrier while the first awaits core. | |
| 268 | - | barrier, err := net.Dial("unix", s.listener.Addr().String()) | |
| 269 | - | if err != nil { | |
| 270 | - | t.Fatal(err) | |
| 271 | - | } | |
| 272 | - | defer barrier.Close() | |
| 273 | - | if err := barrier.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |
| 274 | - | t.Fatal(err) | |
| 275 | - | } | |
| 276 | - | if _, err := barrier.Write([]byte("{\"id\":0,\"op\":\"hello\"}\n")); err != nil { | |
| 277 | - | t.Fatal(err) | |
| 278 | - | } | |
| 279 | - | if _, err := bufio.NewReader(barrier).ReadBytes('\n'); err != nil { | |
| 280 | - | t.Fatal(err) | |
| 281 | - | } | |
| 282 | - | select { | |
| 283 | - | case <-out: | |
| 284 | - | t.Fatal("read next request before core replied") | |
| 285 | - | default: | |
| 286 | - | } | |
| 287 | - | first.Reply <- ports.ControlReply{} | |
| 288 | - | reader := bufio.NewReader(conn) | |
| 289 | - | if _, err := reader.ReadBytes('\n'); err != nil { | |
| 290 | - | t.Fatal(err) | |
| 291 | - | } | |
| 292 | - | select { | |
| 293 | - | case req := <-out: | |
| 294 | - | req.(ports.ControlQuery).Reply <- ports.ControlReply{} | |
| 295 | - | case <-time.After(10 * time.Second): | |
| 296 | - | t.Fatal("second request missing") | |
| 297 | - | } | |
| 298 | - | if _, err := reader.ReadBytes('\n'); err != nil { | |
| 299 | - | t.Fatal(err) | |
| 300 | - | } | |
| 301 | - | // Both handlers now block reading; Close must release them and the accept loop. | |
| 302 | - | if err := s.Close(); err != nil { | |
| 303 | - | t.Fatal(err) | |
| 304 | - | } | |
| 305 | - | select { | |
| 306 | - | case err := <-done: | |
| 307 | - | if err != nil { | |
| 308 | - | t.Fatal(err) | |
| 309 | - | } | |
| 310 | - | case <-time.After(10 * time.Second): | |
| 311 | - | t.Fatal("Close did not stop Run") | |
| 312 | - | } | |
| 313 | - | } | |
| 314 | - | ||
| 315 | - | //testpolicy:realtime A real Unix socket verifies the reply is written before shutdown cancellation. | |
| 316 | - | func TestQuitReplyBeforeShutdown(t *testing.T) { | |
| 317 | - | s, err := Listen(filepath.Join(t.TempDir(), "control.sock"), workspaceid.WithPrefix("quit"), Options{}) | |
| 318 | - | if err != nil { | |
| 319 | - | t.Fatal(err) | |
| 320 | - | } | |
| 321 | - | defer s.Close() | |
| 322 | - | ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) | |
| 323 | - | defer cancel() | |
| 324 | - | out := make(chan ports.ControlRequest) | |
| 325 | - | done := make(chan error, 1) | |
| 326 | - | go func() { done <- s.Run(ctx, out) }() | |
| 327 | - | conn, err := net.Dial("unix", s.listener.Addr().String()) | |
| 328 | - | if err != nil { | |
| 329 | - | t.Fatal(err) | |
| 330 | - | } | |
| 331 | - | defer conn.Close() | |
| 332 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |
| 333 | - | t.Fatal(err) | |
| 334 | - | } | |
| 335 | - | if _, err := conn.Write([]byte("{\"op\":\"do\",\"action\":\"quit\"}\n")); err != nil { | |
| 336 | - | t.Fatal(err) | |
| 337 | - | } | |
| 338 | - | var req ports.ControlDo | |
| 339 | - | select { | |
| 340 | - | case message := <-out: | |
| 341 | - | req = message.(ports.ControlDo) | |
| 342 | - | case <-ctx.Done(): | |
| 343 | - | t.Fatal(ctx.Err()) | |
| 344 | - | } | |
| 345 | - | if req.Wait != domain.DefaultWait { | |
| 346 | - | t.Fatalf("wait: %v", req.Wait) | |
| 347 | - | } | |
| 348 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted} | |
| 349 | - | s.WaitQuitReplies(ctx) | |
| 350 | - | cancel() | |
| 351 | - | var response reply | |
| 352 | - | if err := json.NewDecoder(conn).Decode(&response); err != nil { | |
| 353 | - | t.Fatal(err) | |
| 354 | - | } | |
| 355 | - | if !response.OK || response.Done != "committed" { | |
| 356 | - | t.Fatalf("reply: %+v", response) | |
| 357 | - | } | |
| 358 | - | if err := <-done; err != nil { | |
| 359 | - | t.Fatal(err) | |
| 360 | - | } | |
| 361 | - | } | |
| @@ -1,361 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "bufio" | |||
| 5 | - | "context" | |||
| 6 | - | "encoding/json" | |||
| 7 | - | "net" | |||
| 8 | - | "os" | |||
| 9 | - | "path/filepath" | |||
| 10 | - | "reflect" | |||
| 11 | - | "testing" | |||
| 12 | - | "time" | |||
| 13 | - | ||||
| 14 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |||
| 15 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 16 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 17 | - | ) | |||
| 18 | - | ||||
| 19 | - | //testpolicy:realtime Unix socket exchanges and server shutdown need bounded waits outside synctest. | |||
| 20 | - | func TestProtocol(t *testing.T) { | |||
| 21 | - | path := filepath.Join(t.TempDir(), "session", "control.sock") | |||
| 22 | - | s, err := Listen(path, workspaceid.WithPrefix("test"), Options{}) | |||
| 23 | - | if err != nil { | |||
| 24 | - | t.Fatal(err) | |||
| 25 | - | } | |||
| 26 | - | defer s.Close() | |||
| 27 | - | for path, want := range map[string]os.FileMode{filepath.Dir(path): 0o700, path: 0o600} { | |||
| 28 | - | info, err := os.Stat(path) | |||
| 29 | - | if err != nil || info.Mode().Perm() != want { | |||
| 30 | - | t.Fatalf("permissions %s: %v %v", path, info, err) | |||
| 31 | - | } | |||
| 32 | - | } | |||
| 33 | - | ctx, cancel := context.WithCancel(context.Background()) | |||
| 34 | - | defer cancel() | |||
| 35 | - | out := make(chan ports.ControlRequest) | |||
| 36 | - | done := make(chan error, 1) | |||
| 37 | - | go func() { done <- s.Run(ctx, out) }() | |||
| 38 | - | conn, err := net.Dial("unix", path) | |||
| 39 | - | if err != nil { | |||
| 40 | - | t.Fatal(err) | |||
| 41 | - | } | |||
| 42 | - | defer conn.Close() | |||
| 43 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |||
| 44 | - | t.Fatal(err) | |||
| 45 | - | } | |||
| 46 | - | reader := bufio.NewReader(conn) | |||
| 47 | - | exchange := func(line string) map[string]json.RawMessage { | |||
| 48 | - | t.Helper() | |||
| 49 | - | if _, err := conn.Write([]byte(line + "\n")); err != nil { | |||
| 50 | - | t.Fatal(err) | |||
| 51 | - | } | |||
| 52 | - | data, err := reader.ReadBytes('\n') | |||
| 53 | - | if err != nil { | |||
| 54 | - | t.Fatal(err) | |||
| 55 | - | } | |||
| 56 | - | var got map[string]json.RawMessage | |||
| 57 | - | if err := json.Unmarshal(data, &got); err != nil { | |||
| 58 | - | t.Fatal(err) | |||
| 59 | - | } | |||
| 60 | - | return got | |||
| 61 | - | } | |||
| 62 | - | hello := exchange(`{"id":"hello","op":"hello"}`) | |||
| 63 | - | if string(hello["id"]) != `"hello"` || string(hello["ok"]) != "true" || string(hello["v"]) != "1" { | |||
| 64 | - | t.Fatal(hello) | |||
| 65 | - | } | |||
| 66 | - | // A line that is not JSON has no id to echo: null. | |||
| 67 | - | if bad := exchange(`{broken`); string(bad["id"]) != "null" || string(bad["error"]) != `"bad-request"` { | |||
| 68 | - | t.Fatal(bad) | |||
| 69 | - | } | |||
| 70 | - | if long := exchange(`{"id":9,"op":"do","action":"none","timeout":"6m"}`); string(long["detail"]) != `"timeout exceeds 5m"` { | |||
| 71 | - | t.Fatal(long) | |||
| 72 | - | } | |||
| 73 | - | // The id is optional and echoed as null. | |||
| 74 | - | if anon := exchange(`{"op":"hello"}`); string(anon["id"]) != "null" || string(anon["ok"]) != "true" { | |||
| 75 | - | t.Fatal(anon) | |||
| 76 | - | } | |||
| 77 | - | var commands []command | |||
| 78 | - | if err := json.Unmarshal(hello["commands"], &commands); err != nil { | |||
| 79 | - | t.Fatal(err) | |||
| 80 | - | } | |||
| 81 | - | if len(commands) != len(domain.Commands()) || commands[0].Name != domain.Commands()[0].Name || len(commands[0].Caps) == 0 { | |||
| 82 | - | t.Fatal(commands) | |||
| 83 | - | } | |||
| 84 | - | for i, spec := range domain.Commands() { | |||
| 85 | - | if commands[i].Kind != spec.Kind.String() { | |||
| 86 | - | t.Errorf("command %q kind = %q, want %q", spec.Name, commands[i].Kind, spec.Kind.String()) | |||
| 87 | - | } | |||
| 88 | - | } | |||
| 89 | - | var caps []string | |||
| 90 | - | if err := json.Unmarshal(hello["caps"], &caps); err != nil { | |||
| 91 | - | t.Fatal(err) | |||
| 92 | - | } | |||
| 93 | - | if !reflect.DeepEqual(caps, []string{"read", "act", "input", "capture", "admin"}) { | |||
| 94 | - | t.Fatal(caps) | |||
| 95 | - | } | |||
| 96 | - | for _, line := range []string{`{broken`, `{"id":2,"op":"unknown"}`, `{"id":3,"op":"do","action":"none","wait":"bad"}`, `{"id":4,"op":"do","action":"none","until":"bad"}`, `{"id":5,"op":"do","action":"none","timeout":"bad"}`, `{"id":5,"op":"do","action":"none","timeout":"6m"}`, `{"op":"do"}`} { | |||
| 97 | - | got := exchange(line) | |||
| 98 | - | if string(got["error"]) != `"bad-request"` || string(got["ok"]) != "false" { | |||
| 99 | - | t.Fatal(got) | |||
| 100 | - | } | |||
| 101 | - | } | |||
| 102 | - | coreDone := make(chan struct{}) | |||
| 103 | - | go func() { | |||
| 104 | - | defer close(coreDone) | |||
| 105 | - | for i := 0; i < 3; i++ { | |||
| 106 | - | select { | |||
| 107 | - | case message := <-out: | |||
| 108 | - | switch req := message.(type) { | |||
| 109 | - | case ports.ControlDo: | |||
| 110 | - | if req.Action != "none" || req.Caps != domain.CapsAll || cap(req.Reply) != 1 { | |||
| 111 | - | t.Errorf("do: %+v", req) | |||
| 112 | - | } | |||
| 113 | - | if i == 0 { | |||
| 114 | - | if req.Wait != domain.WaitPresented || req.Timeout != 2*time.Second || req.Until == nil || req.Until.Kind != domain.UntilFocused || req.Until.AppID != "foot" { | |||
| 115 | - | t.Errorf("explicit: %+v", req) | |||
| 116 | - | } | |||
| 117 | - | } else if req.Wait != domain.DefaultWait || req.Timeout != 10*time.Second || req.Until != nil { | |||
| 118 | - | t.Errorf("defaults: %+v", req) | |||
| 119 | - | } | |||
| 120 | - | // Core may reach less than the requested level; preserve its report. | |||
| 121 | - | timedOut := "" | |||
| 122 | - | if i == 1 { | |||
| 123 | - | timedOut = ports.ControlErrTimeout | |||
| 124 | - | } | |||
| 125 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted, Err: timedOut, Diff: domain.StateDiff{FocusFrom: 1, FocusTo: 2, FocusChanged: true}, Late: []domain.WindowID{3}} | |||
| 126 | - | case ports.ControlQuery: | |||
| 127 | - | if req.What != "state" || req.Caps != domain.CapsAll || cap(req.Reply) != 1 { | |||
| 128 | - | t.Errorf("query: %+v", req) | |||
| 129 | - | } | |||
| 130 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted, State: domain.State{Outputs: []domain.OutputState{{Name: "A", WorkspaceID: 7}}}} | |||
| 131 | - | default: | |||
| 132 | - | t.Errorf("unexpected %T", message) | |||
| 133 | - | } | |||
| 134 | - | case <-ctx.Done(): | |||
| 135 | - | return | |||
| 136 | - | } | |||
| 137 | - | } | |||
| 138 | - | }() | |||
| 139 | - | got := exchange(`{"id":6,"op":"do","action":"none","wait":"presented","until":"focused app_id=foot","timeout":"2s"}`) | |||
| 140 | - | if string(got["id"]) != "6" || string(got["done"]) != `"committed"` || string(got["ok"]) != "true" { | |||
| 141 | - | t.Fatal(got) | |||
| 142 | - | } | |||
| 143 | - | if _, present := got["error"]; present { | |||
| 144 | - | t.Fatalf("successful reply includes error: %s", got["error"]) | |||
| 145 | - | } | |||
| 146 | - | var d map[string]any | |||
| 147 | - | if err := json.Unmarshal(got["diff"], &d); err != nil { | |||
| 148 | - | t.Fatal(err) | |||
| 149 | - | } | |||
| 150 | - | if d["focus_from"] != float64(1) || d["focus_to"] != float64(2) || d["focus_changed"] != true { | |||
| 151 | - | t.Fatal(d) | |||
| 152 | - | } | |||
| 153 | - | got = exchange(`{"id":7,"op":"do","action":"none"}`) | |||
| 154 | - | if string(got["error"]) != `"timeout"` || string(got["late"]) != "[3]" { | |||
| 155 | - | t.Fatal(got) | |||
| 156 | - | } | |||
| 157 | - | got = exchange(`{"id":8,"op":"query","what":"state"}`) | |||
| 158 | - | var state struct { | |||
| 159 | - | Outputs []struct { | |||
| 160 | - | WorkspaceID string `json:"workspace_id"` | |||
| 161 | - | } | |||
| 162 | - | } | |||
| 163 | - | if err := json.Unmarshal(got["state"], &state); err != nil { | |||
| 164 | - | t.Fatal(err) | |||
| 165 | - | } | |||
| 166 | - | if len(state.Outputs) != 1 || state.Outputs[0].WorkspaceID != "test-7" { | |||
| 167 | - | t.Fatal(state) | |||
| 168 | - | } | |||
| 169 | - | <-coreDone | |||
| 170 | - | // Leave one request awaiting core forever; cancellation must release it. | |||
| 171 | - | if _, err := conn.Write([]byte("{\"id\":9,\"op\":\"query\",\"what\":\"state\"}\n")); err != nil { | |||
| 172 | - | t.Fatal(err) | |||
| 173 | - | } | |||
| 174 | - | select { | |||
| 175 | - | case <-out: | |||
| 176 | - | case <-time.After(10 * time.Second): | |||
| 177 | - | t.Fatal("request not received") | |||
| 178 | - | } | |||
| 179 | - | cancel() | |||
| 180 | - | select { | |||
| 181 | - | case err := <-done: | |||
| 182 | - | if err != nil { | |||
| 183 | - | t.Fatal(err) | |||
| 184 | - | } | |||
| 185 | - | case <-time.After(10 * time.Second): | |||
| 186 | - | t.Fatal("Run did not stop") | |||
| 187 | - | } | |||
| 188 | - | } | |||
| 189 | - | ||||
| 190 | - | func TestListenPreservesLiveSocketAndFiles(t *testing.T) { | |||
| 191 | - | path := filepath.Join(t.TempDir(), "control.sock") | |||
| 192 | - | ids := workspaceid.WithPrefix("test") | |||
| 193 | - | s, err := Listen(path, ids, Options{}) | |||
| 194 | - | if err != nil { | |||
| 195 | - | t.Fatal(err) | |||
| 196 | - | } | |||
| 197 | - | defer s.Close() | |||
| 198 | - | if other, err := Listen(path, ids, Options{}); err == nil { | |||
| 199 | - | other.Close() | |||
| 200 | - | t.Fatal("replaced live listener") | |||
| 201 | - | } | |||
| 202 | - | if err := s.Close(); err != nil { | |||
| 203 | - | t.Fatal(err) | |||
| 204 | - | } | |||
| 205 | - | if err := os.WriteFile(path, []byte("keep"), 0o600); err != nil { | |||
| 206 | - | t.Fatal(err) | |||
| 207 | - | } | |||
| 208 | - | if other, err := Listen(path, ids, Options{}); err == nil { | |||
| 209 | - | other.Close() | |||
| 210 | - | t.Fatal("replaced regular file") | |||
| 211 | - | } | |||
| 212 | - | data, err := os.ReadFile(path) | |||
| 213 | - | if err != nil || string(data) != "keep" { | |||
| 214 | - | t.Fatal(string(data), err) | |||
| 215 | - | } | |||
| 216 | - | } | |||
| 217 | - | ||||
| 218 | - | func TestListenRemovesStaleSocket(t *testing.T) { | |||
| 219 | - | path := filepath.Join(t.TempDir(), "control.sock") | |||
| 220 | - | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) | |||
| 221 | - | if err != nil { | |||
| 222 | - | t.Fatal(err) | |||
| 223 | - | } | |||
| 224 | - | listener.SetUnlinkOnClose(false) | |||
| 225 | - | if err := listener.Close(); err != nil { | |||
| 226 | - | t.Fatal(err) | |||
| 227 | - | } | |||
| 228 | - | s, err := Listen(path, workspaceid.WithPrefix("test"), Options{}) | |||
| 229 | - | if err != nil { | |||
| 230 | - | t.Fatal(err) | |||
| 231 | - | } | |||
| 232 | - | if err := s.Close(); err != nil { | |||
| 233 | - | t.Fatal(err) | |||
| 234 | - | } | |||
| 235 | - | } | |||
| 236 | - | ||||
| 237 | - | //testpolicy:realtime Socket reads and cancellation completion are bounded real I/O waits. | |||
| 238 | - | func TestConnectionOrderingAndClose(t *testing.T) { | |||
| 239 | - | s, err := Listen(filepath.Join(t.TempDir(), "control.sock"), workspaceid.WithPrefix("test"), Options{}) | |||
| 240 | - | if err != nil { | |||
| 241 | - | t.Fatal(err) | |||
| 242 | - | } | |||
| 243 | - | defer s.Close() | |||
| 244 | - | ctx, cancel := context.WithCancel(context.Background()) | |||
| 245 | - | defer cancel() | |||
| 246 | - | out := make(chan ports.ControlRequest, 2) | |||
| 247 | - | done := make(chan error, 1) | |||
| 248 | - | go func() { done <- s.Run(ctx, out) }() | |||
| 249 | - | conn, err := net.Dial("unix", s.listener.Addr().String()) | |||
| 250 | - | if err != nil { | |||
| 251 | - | t.Fatal(err) | |||
| 252 | - | } | |||
| 253 | - | defer conn.Close() | |||
| 254 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |||
| 255 | - | t.Fatal(err) | |||
| 256 | - | } | |||
| 257 | - | if _, err := conn.Write([]byte("{\"id\":1,\"op\":\"query\",\"what\":\"state\"}\n{\"id\":2,\"op\":\"query\",\"what\":\"state\"}\n")); err != nil { | |||
| 258 | - | t.Fatal(err) | |||
| 259 | - | } | |||
| 260 | - | var first ports.ControlQuery | |||
| 261 | - | select { | |||
| 262 | - | case req := <-out: | |||
| 263 | - | first = req.(ports.ControlQuery) | |||
| 264 | - | case <-time.After(10 * time.Second): | |||
| 265 | - | t.Fatal("first request missing") | |||
| 266 | - | } | |||
| 267 | - | // A second connection's hello is an I/O barrier while the first awaits core. | |||
| 268 | - | barrier, err := net.Dial("unix", s.listener.Addr().String()) | |||
| 269 | - | if err != nil { | |||
| 270 | - | t.Fatal(err) | |||
| 271 | - | } | |||
| 272 | - | defer barrier.Close() | |||
| 273 | - | if err := barrier.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |||
| 274 | - | t.Fatal(err) | |||
| 275 | - | } | |||
| 276 | - | if _, err := barrier.Write([]byte("{\"id\":0,\"op\":\"hello\"}\n")); err != nil { | |||
| 277 | - | t.Fatal(err) | |||
| 278 | - | } | |||
| 279 | - | if _, err := bufio.NewReader(barrier).ReadBytes('\n'); err != nil { | |||
| 280 | - | t.Fatal(err) | |||
| 281 | - | } | |||
| 282 | - | select { | |||
| 283 | - | case <-out: | |||
| 284 | - | t.Fatal("read next request before core replied") | |||
| 285 | - | default: | |||
| 286 | - | } | |||
| 287 | - | first.Reply <- ports.ControlReply{} | |||
| 288 | - | reader := bufio.NewReader(conn) | |||
| 289 | - | if _, err := reader.ReadBytes('\n'); err != nil { | |||
| 290 | - | t.Fatal(err) | |||
| 291 | - | } | |||
| 292 | - | select { | |||
| 293 | - | case req := <-out: | |||
| 294 | - | req.(ports.ControlQuery).Reply <- ports.ControlReply{} | |||
| 295 | - | case <-time.After(10 * time.Second): | |||
| 296 | - | t.Fatal("second request missing") | |||
| 297 | - | } | |||
| 298 | - | if _, err := reader.ReadBytes('\n'); err != nil { | |||
| 299 | - | t.Fatal(err) | |||
| 300 | - | } | |||
| 301 | - | // Both handlers now block reading; Close must release them and the accept loop. | |||
| 302 | - | if err := s.Close(); err != nil { | |||
| 303 | - | t.Fatal(err) | |||
| 304 | - | } | |||
| 305 | - | select { | |||
| 306 | - | case err := <-done: | |||
| 307 | - | if err != nil { | |||
| 308 | - | t.Fatal(err) | |||
| 309 | - | } | |||
| 310 | - | case <-time.After(10 * time.Second): | |||
| 311 | - | t.Fatal("Close did not stop Run") | |||
| 312 | - | } | |||
| 313 | - | } | |||
| 314 | - | ||||
| 315 | - | //testpolicy:realtime A real Unix socket verifies the reply is written before shutdown cancellation. | |||
| 316 | - | func TestQuitReplyBeforeShutdown(t *testing.T) { | |||
| 317 | - | s, err := Listen(filepath.Join(t.TempDir(), "control.sock"), workspaceid.WithPrefix("quit"), Options{}) | |||
| 318 | - | if err != nil { | |||
| 319 | - | t.Fatal(err) | |||
| 320 | - | } | |||
| 321 | - | defer s.Close() | |||
| 322 | - | ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) | |||
| 323 | - | defer cancel() | |||
| 324 | - | out := make(chan ports.ControlRequest) | |||
| 325 | - | done := make(chan error, 1) | |||
| 326 | - | go func() { done <- s.Run(ctx, out) }() | |||
| 327 | - | conn, err := net.Dial("unix", s.listener.Addr().String()) | |||
| 328 | - | if err != nil { | |||
| 329 | - | t.Fatal(err) | |||
| 330 | - | } | |||
| 331 | - | defer conn.Close() | |||
| 332 | - | if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { | |||
| 333 | - | t.Fatal(err) | |||
| 334 | - | } | |||
| 335 | - | if _, err := conn.Write([]byte("{\"op\":\"do\",\"action\":\"quit\"}\n")); err != nil { | |||
| 336 | - | t.Fatal(err) | |||
| 337 | - | } | |||
| 338 | - | var req ports.ControlDo | |||
| 339 | - | select { | |||
| 340 | - | case message := <-out: | |||
| 341 | - | req = message.(ports.ControlDo) | |||
| 342 | - | case <-ctx.Done(): | |||
| 343 | - | t.Fatal(ctx.Err()) | |||
| 344 | - | } | |||
| 345 | - | if req.Wait != domain.DefaultWait { | |||
| 346 | - | t.Fatalf("wait: %v", req.Wait) | |||
| 347 | - | } | |||
| 348 | - | req.Reply <- ports.ControlReply{Done: domain.WaitCommitted} | |||
| 349 | - | s.WaitQuitReplies(ctx) | |||
| 350 | - | cancel() | |||
| 351 | - | var response reply | |||
| 352 | - | if err := json.NewDecoder(conn).Decode(&response); err != nil { | |||
| 353 | - | t.Fatal(err) | |||
| 354 | - | } | |||
| 355 | - | if !response.OK || response.Done != "committed" { | |||
| 356 | - | t.Fatalf("reply: %+v", response) | |||
| 357 | - | } | |||
| 358 | - | if err := <-done; err != nil { | |||
| 359 | - | t.Fatal(err) | |||
| 360 | - | } | |||
| 361 | - | } | |||
D internal/adapters/control/inject.go +0 -261
| @@ -1,261 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "errors" | |
| 5 | - | "math" | |
| 6 | - | "slices" | |
| 7 | - | "strconv" | |
| 8 | - | "strings" | |
| 9 | - | "time" | |
| 10 | - | "unicode" | |
| 11 | - | ||
| 12 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |
| 13 | - | "github.com/bnema/neferwl/internal/domain" | |
| 14 | - | "github.com/bnema/neferwl/internal/ports" | |
| 15 | - | "golang.org/x/sys/unix" | |
| 16 | - | ) | |
| 17 | - | ||
| 18 | - | const controlDeviceID = domain.ControlDeviceID | |
| 19 | - | ||
| 20 | - | // injector translates commands on its owner's goroutine. It borrows km; the | |
| 21 | - | // caller owns its lifetime and announces Device once before delivering input. | |
| 22 | - | // Coordinates are global logical coordinates; layout clamping belongs to core. | |
| 23 | - | type injector struct { | |
| 24 | - | km *xkb.Keymap | |
| 25 | - | security ports.SessionSecurity | |
| 26 | - | } | |
| 27 | - | ||
| 28 | - | func newInjector(km *xkb.Keymap, security ports.SessionSecurity) *injector { | |
| 29 | - | return &injector{km: km, security: security} | |
| 30 | - | } | |
| 31 | - | ||
| 32 | - | func injectTime() time.Duration { | |
| 33 | - | var ts unix.Timespec | |
| 34 | - | _ = unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts) | |
| 35 | - | return time.Duration(ts.Nano()) | |
| 36 | - | } | |
| 37 | - | ||
| 38 | - | func (i *injector) snapshot() domain.SecurityState { | |
| 39 | - | if i.security != nil { | |
| 40 | - | return i.security.Snapshot() | |
| 41 | - | } | |
| 42 | - | return domain.SecurityState{} | |
| 43 | - | } | |
| 44 | - | ||
| 45 | - | func (i *injector) stamp(ev ports.InputEvent, state domain.SecurityState) ports.InputEvent { | |
| 46 | - | if i.security != nil { | |
| 47 | - | return ports.SecurityInput{State: state, Event: ev} | |
| 48 | - | } | |
| 49 | - | return ev | |
| 50 | - | } | |
| 51 | - | ||
| 52 | - | // Device returns the announcement to send once for this synthetic producer. | |
| 53 | - | func (i *injector) Device() ports.InputEvent { | |
| 54 | - | return i.stamp(ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}, i.snapshot()) | |
| 55 | - | } | |
| 56 | - | ||
| 57 | - | func (i *injector) keyEdge(events []ports.InputEvent, code uint32, down bool) ([]ports.InputEvent, error) { | |
| 58 | - | state := i.snapshot() // Must precede KeySecure's epoch-aware translation. | |
| 59 | - | var key ports.KeyEvent | |
| 60 | - | if i.security != nil { | |
| 61 | - | var deliver bool | |
| 62 | - | var err error | |
| 63 | - | key, deliver, err = i.km.KeySecure(code, down, injectTime(), state) | |
| 64 | - | if err != nil { | |
| 65 | - | return nil, err | |
| 66 | - | } | |
| 67 | - | if !deliver { | |
| 68 | - | return events, nil | |
| 69 | - | } | |
| 70 | - | } else { | |
| 71 | - | key = i.km.Key(code, down, injectTime()) | |
| 72 | - | } | |
| 73 | - | key.Device = controlDeviceID | |
| 74 | - | return append(events, i.stamp(key, state)), nil | |
| 75 | - | } | |
| 76 | - | ||
| 77 | - | func injectModifier(name string) uint32 { | |
| 78 | - | switch name { | |
| 79 | - | case "Super": | |
| 80 | - | return 125 | |
| 81 | - | case "Shift": | |
| 82 | - | return 42 | |
| 83 | - | case "Ctrl": | |
| 84 | - | return 29 | |
| 85 | - | case "Alt": | |
| 86 | - | return 56 | |
| 87 | - | } | |
| 88 | - | return 0 | |
| 89 | - | } | |
| 90 | - | ||
| 91 | - | // combo resolves all keys before any keymap state is changed. | |
| 92 | - | func (i *injector) combo(combo string) ([]uint32, error) { | |
| 93 | - | parts := strings.Split(combo, "+") | |
| 94 | - | var codes []uint32 | |
| 95 | - | for _, name := range parts[:len(parts)-1] { | |
| 96 | - | code := injectModifier(name) | |
| 97 | - | if code == 0 { | |
| 98 | - | return nil, errors.New("unknown modifier") | |
| 99 | - | } | |
| 100 | - | codes = append(codes, code) | |
| 101 | - | } | |
| 102 | - | name := parts[len(parts)-1] | |
| 103 | - | // Modifier-only presses use the same evdev identities as script press/release. | |
| 104 | - | if code := injectModifier(name); code != 0 { | |
| 105 | - | return append(codes, code), nil | |
| 106 | - | } | |
| 107 | - | code, shift, ok := i.km.KeycodeFor(name) | |
| 108 | - | if !ok { | |
| 109 | - | return nil, errors.New("unknown key") | |
| 110 | - | } | |
| 111 | - | if shift && !slices.Contains(codes, uint32(42)) && !slices.Contains(codes, uint32(54)) { | |
| 112 | - | codes = append(codes, 42) | |
| 113 | - | } | |
| 114 | - | return append(codes, code), nil | |
| 115 | - | } | |
| 116 | - | ||
| 117 | - | func (i *injector) edges(codes []uint32, down bool, events []ports.InputEvent) ([]ports.InputEvent, error) { | |
| 118 | - | for n := range codes { | |
| 119 | - | at := n | |
| 120 | - | if !down { | |
| 121 | - | at = len(codes) - 1 - n | |
| 122 | - | } | |
| 123 | - | var err error | |
| 124 | - | events, err = i.keyEdge(events, codes[at], down) | |
| 125 | - | if err != nil { | |
| 126 | - | return nil, err | |
| 127 | - | } | |
| 128 | - | } | |
| 129 | - | return events, nil | |
| 130 | - | } | |
| 131 | - | ||
| 132 | - | func (i *injector) Key(combo string) ([]ports.InputEvent, error) { | |
| 133 | - | codes, err := i.combo(combo) | |
| 134 | - | if err != nil { | |
| 135 | - | return nil, err | |
| 136 | - | } | |
| 137 | - | events, err := i.edges(codes, true, nil) | |
| 138 | - | if err != nil { | |
| 139 | - | return nil, err | |
| 140 | - | } | |
| 141 | - | return i.edges(codes, false, events) | |
| 142 | - | } | |
| 143 | - | ||
| 144 | - | func (i *injector) Press(combo string) ([]ports.InputEvent, error) { | |
| 145 | - | codes, err := i.combo(combo) | |
| 146 | - | if err != nil { | |
| 147 | - | return nil, err | |
| 148 | - | } | |
| 149 | - | return i.edges(codes, true, nil) | |
| 150 | - | } | |
| 151 | - | ||
| 152 | - | func (i *injector) Release(combo string) ([]ports.InputEvent, error) { | |
| 153 | - | codes, err := i.combo(combo) | |
| 154 | - | if err != nil { | |
| 155 | - | return nil, err | |
| 156 | - | } | |
| 157 | - | return i.edges(codes, false, nil) | |
| 158 | - | } | |
| 159 | - | ||
| 160 | - | var injectPunctuation = map[rune]string{' ': "space", '\n': "Return", '.': "period", ',': "comma", '-': "minus", '_': "underscore", '/': "slash", ':': "colon", ';': "semicolon", '!': "exclam", '?': "question", '\'': "apostrophe", '"': "quotedbl", '(': "parenleft", ')': "parenright", '=': "equal", '+': "plus", '\\': "backslash", '@': "at", '#': "numbersign", '$': "dollar", '%': "percent", '&': "ampersand", '*': "asterisk", '[': "bracketleft", ']': "bracketright", '{': "braceleft", '}': "braceright", '<': "less", '>': "greater", '|': "bar", '`': "grave", '~': "asciitilde", '^': "asciicircum"} | |
| 161 | - | ||
| 162 | - | func (i *injector) Type(text string) ([]ports.InputEvent, error) { | |
| 163 | - | var strokes [][]uint32 | |
| 164 | - | for _, r := range text { | |
| 165 | - | name := injectPunctuation[r] | |
| 166 | - | if name == "" && (unicode.IsLetter(r) || unicode.IsDigit(r)) { | |
| 167 | - | name = string(r) | |
| 168 | - | } | |
| 169 | - | if name == "" { | |
| 170 | - | return nil, errors.New("unknown rune") | |
| 171 | - | } | |
| 172 | - | codes, err := i.combo(name) | |
| 173 | - | if err != nil { | |
| 174 | - | return nil, err | |
| 175 | - | } | |
| 176 | - | strokes = append(strokes, codes) | |
| 177 | - | } | |
| 178 | - | var events []ports.InputEvent | |
| 179 | - | for _, codes := range strokes { | |
| 180 | - | var err error | |
| 181 | - | events, err = i.edges(codes, true, events) | |
| 182 | - | if err != nil { | |
| 183 | - | return nil, err | |
| 184 | - | } | |
| 185 | - | events, err = i.edges(codes, false, events) | |
| 186 | - | if err != nil { | |
| 187 | - | return nil, err | |
| 188 | - | } | |
| 189 | - | } | |
| 190 | - | return events, nil | |
| 191 | - | } | |
| 192 | - | ||
| 193 | - | func (i *injector) Pointer(cmd string, args []string) ([]ports.InputEvent, error) { | |
| 194 | - | now := injectTime() | |
| 195 | - | if cmd == "move" { | |
| 196 | - | if len(args) != 2 { | |
| 197 | - | return nil, errors.New("move requires x y") | |
| 198 | - | } | |
| 199 | - | x, ex := strconv.ParseFloat(args[0], 64) | |
| 200 | - | y, ey := strconv.ParseFloat(args[1], 64) | |
| 201 | - | if ex != nil || ey != nil || math.IsNaN(x) || math.IsNaN(y) || math.IsInf(x, 0) || math.IsInf(y, 0) { | |
| 202 | - | return nil, errors.New("invalid move coordinates") | |
| 203 | - | } | |
| 204 | - | return []ports.InputEvent{i.stamp(ports.PointerMotion{Device: controlDeviceID, X: x, Y: y, Time: now}, i.snapshot())}, nil | |
| 205 | - | } | |
| 206 | - | if cmd != "click" && cmd != "down" && cmd != "up" { | |
| 207 | - | return nil, errors.New("unknown pointer command") | |
| 208 | - | } | |
| 209 | - | if len(args) > 1 || len(args) == 0 && cmd != "click" { | |
| 210 | - | return nil, errors.New("invalid button arguments") | |
| 211 | - | } | |
| 212 | - | name := "left" | |
| 213 | - | if len(args) == 1 { | |
| 214 | - | name = args[0] | |
| 215 | - | } | |
| 216 | - | var button uint32 | |
| 217 | - | switch name { | |
| 218 | - | case "left": | |
| 219 | - | button = 0x110 | |
| 220 | - | case "right": | |
| 221 | - | button = 0x111 | |
| 222 | - | case "middle": | |
| 223 | - | button = 0x112 | |
| 224 | - | default: | |
| 225 | - | return nil, errors.New("unknown button") | |
| 226 | - | } | |
| 227 | - | var events []ports.InputEvent | |
| 228 | - | if cmd != "up" { | |
| 229 | - | events = append(events, i.stamp(ports.PointerButton{Device: controlDeviceID, Button: button, Pressed: true, Time: now}, i.snapshot())) | |
| 230 | - | } | |
| 231 | - | if cmd != "down" { | |
| 232 | - | events = append(events, i.stamp(ports.PointerButton{Device: controlDeviceID, Button: button, Time: now}, i.snapshot())) | |
| 233 | - | } | |
| 234 | - | return events, nil | |
| 235 | - | } | |
| 236 | - | ||
| 237 | - | func (i *injector) Swipe(fingers int, dir string) ([]ports.InputEvent, error) { | |
| 238 | - | if fingers != 3 && fingers != 4 { | |
| 239 | - | return nil, errors.New("swipe requires three or four fingers") | |
| 240 | - | } | |
| 241 | - | var dx, dy float64 | |
| 242 | - | switch dir { | |
| 243 | - | case "up": | |
| 244 | - | dy = -40 | |
| 245 | - | case "down": | |
| 246 | - | dy = 40 | |
| 247 | - | case "left": | |
| 248 | - | dx = -40 | |
| 249 | - | case "right": | |
| 250 | - | dx = 40 | |
| 251 | - | default: | |
| 252 | - | return nil, errors.New("invalid swipe direction") | |
| 253 | - | } | |
| 254 | - | at := injectTime() | |
| 255 | - | events := []ports.InputEvent{i.stamp(ports.SwipeBegin{Device: controlDeviceID, Fingers: fingers, Time: at}, i.snapshot())} | |
| 256 | - | for range 10 { | |
| 257 | - | at += 8 * time.Millisecond | |
| 258 | - | events = append(events, i.stamp(ports.SwipeUpdate{Device: controlDeviceID, DX: dx, DY: dy, Time: at}, i.snapshot())) | |
| 259 | - | } | |
| 260 | - | return append(events, i.stamp(ports.SwipeEnd{Device: controlDeviceID, Time: at}, i.snapshot())), nil | |
| 261 | - | } | |
| @@ -1,261 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "errors" | |||
| 5 | - | "math" | |||
| 6 | - | "slices" | |||
| 7 | - | "strconv" | |||
| 8 | - | "strings" | |||
| 9 | - | "time" | |||
| 10 | - | "unicode" | |||
| 11 | - | ||||
| 12 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |||
| 13 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 14 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 15 | - | "golang.org/x/sys/unix" | |||
| 16 | - | ) | |||
| 17 | - | ||||
| 18 | - | const controlDeviceID = domain.ControlDeviceID | |||
| 19 | - | ||||
| 20 | - | // injector translates commands on its owner's goroutine. It borrows km; the | |||
| 21 | - | // caller owns its lifetime and announces Device once before delivering input. | |||
| 22 | - | // Coordinates are global logical coordinates; layout clamping belongs to core. | |||
| 23 | - | type injector struct { | |||
| 24 | - | km *xkb.Keymap | |||
| 25 | - | security ports.SessionSecurity | |||
| 26 | - | } | |||
| 27 | - | ||||
| 28 | - | func newInjector(km *xkb.Keymap, security ports.SessionSecurity) *injector { | |||
| 29 | - | return &injector{km: km, security: security} | |||
| 30 | - | } | |||
| 31 | - | ||||
| 32 | - | func injectTime() time.Duration { | |||
| 33 | - | var ts unix.Timespec | |||
| 34 | - | _ = unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts) | |||
| 35 | - | return time.Duration(ts.Nano()) | |||
| 36 | - | } | |||
| 37 | - | ||||
| 38 | - | func (i *injector) snapshot() domain.SecurityState { | |||
| 39 | - | if i.security != nil { | |||
| 40 | - | return i.security.Snapshot() | |||
| 41 | - | } | |||
| 42 | - | return domain.SecurityState{} | |||
| 43 | - | } | |||
| 44 | - | ||||
| 45 | - | func (i *injector) stamp(ev ports.InputEvent, state domain.SecurityState) ports.InputEvent { | |||
| 46 | - | if i.security != nil { | |||
| 47 | - | return ports.SecurityInput{State: state, Event: ev} | |||
| 48 | - | } | |||
| 49 | - | return ev | |||
| 50 | - | } | |||
| 51 | - | ||||
| 52 | - | // Device returns the announcement to send once for this synthetic producer. | |||
| 53 | - | func (i *injector) Device() ports.InputEvent { | |||
| 54 | - | return i.stamp(ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}, i.snapshot()) | |||
| 55 | - | } | |||
| 56 | - | ||||
| 57 | - | func (i *injector) keyEdge(events []ports.InputEvent, code uint32, down bool) ([]ports.InputEvent, error) { | |||
| 58 | - | state := i.snapshot() // Must precede KeySecure's epoch-aware translation. | |||
| 59 | - | var key ports.KeyEvent | |||
| 60 | - | if i.security != nil { | |||
| 61 | - | var deliver bool | |||
| 62 | - | var err error | |||
| 63 | - | key, deliver, err = i.km.KeySecure(code, down, injectTime(), state) | |||
| 64 | - | if err != nil { | |||
| 65 | - | return nil, err | |||
| 66 | - | } | |||
| 67 | - | if !deliver { | |||
| 68 | - | return events, nil | |||
| 69 | - | } | |||
| 70 | - | } else { | |||
| 71 | - | key = i.km.Key(code, down, injectTime()) | |||
| 72 | - | } | |||
| 73 | - | key.Device = controlDeviceID | |||
| 74 | - | return append(events, i.stamp(key, state)), nil | |||
| 75 | - | } | |||
| 76 | - | ||||
| 77 | - | func injectModifier(name string) uint32 { | |||
| 78 | - | switch name { | |||
| 79 | - | case "Super": | |||
| 80 | - | return 125 | |||
| 81 | - | case "Shift": | |||
| 82 | - | return 42 | |||
| 83 | - | case "Ctrl": | |||
| 84 | - | return 29 | |||
| 85 | - | case "Alt": | |||
| 86 | - | return 56 | |||
| 87 | - | } | |||
| 88 | - | return 0 | |||
| 89 | - | } | |||
| 90 | - | ||||
| 91 | - | // combo resolves all keys before any keymap state is changed. | |||
| 92 | - | func (i *injector) combo(combo string) ([]uint32, error) { | |||
| 93 | - | parts := strings.Split(combo, "+") | |||
| 94 | - | var codes []uint32 | |||
| 95 | - | for _, name := range parts[:len(parts)-1] { | |||
| 96 | - | code := injectModifier(name) | |||
| 97 | - | if code == 0 { | |||
| 98 | - | return nil, errors.New("unknown modifier") | |||
| 99 | - | } | |||
| 100 | - | codes = append(codes, code) | |||
| 101 | - | } | |||
| 102 | - | name := parts[len(parts)-1] | |||
| 103 | - | // Modifier-only presses use the same evdev identities as script press/release. | |||
| 104 | - | if code := injectModifier(name); code != 0 { | |||
| 105 | - | return append(codes, code), nil | |||
| 106 | - | } | |||
| 107 | - | code, shift, ok := i.km.KeycodeFor(name) | |||
| 108 | - | if !ok { | |||
| 109 | - | return nil, errors.New("unknown key") | |||
| 110 | - | } | |||
| 111 | - | if shift && !slices.Contains(codes, uint32(42)) && !slices.Contains(codes, uint32(54)) { | |||
| 112 | - | codes = append(codes, 42) | |||
| 113 | - | } | |||
| 114 | - | return append(codes, code), nil | |||
| 115 | - | } | |||
| 116 | - | ||||
| 117 | - | func (i *injector) edges(codes []uint32, down bool, events []ports.InputEvent) ([]ports.InputEvent, error) { | |||
| 118 | - | for n := range codes { | |||
| 119 | - | at := n | |||
| 120 | - | if !down { | |||
| 121 | - | at = len(codes) - 1 - n | |||
| 122 | - | } | |||
| 123 | - | var err error | |||
| 124 | - | events, err = i.keyEdge(events, codes[at], down) | |||
| 125 | - | if err != nil { | |||
| 126 | - | return nil, err | |||
| 127 | - | } | |||
| 128 | - | } | |||
| 129 | - | return events, nil | |||
| 130 | - | } | |||
| 131 | - | ||||
| 132 | - | func (i *injector) Key(combo string) ([]ports.InputEvent, error) { | |||
| 133 | - | codes, err := i.combo(combo) | |||
| 134 | - | if err != nil { | |||
| 135 | - | return nil, err | |||
| 136 | - | } | |||
| 137 | - | events, err := i.edges(codes, true, nil) | |||
| 138 | - | if err != nil { | |||
| 139 | - | return nil, err | |||
| 140 | - | } | |||
| 141 | - | return i.edges(codes, false, events) | |||
| 142 | - | } | |||
| 143 | - | ||||
| 144 | - | func (i *injector) Press(combo string) ([]ports.InputEvent, error) { | |||
| 145 | - | codes, err := i.combo(combo) | |||
| 146 | - | if err != nil { | |||
| 147 | - | return nil, err | |||
| 148 | - | } | |||
| 149 | - | return i.edges(codes, true, nil) | |||
| 150 | - | } | |||
| 151 | - | ||||
| 152 | - | func (i *injector) Release(combo string) ([]ports.InputEvent, error) { | |||
| 153 | - | codes, err := i.combo(combo) | |||
| 154 | - | if err != nil { | |||
| 155 | - | return nil, err | |||
| 156 | - | } | |||
| 157 | - | return i.edges(codes, false, nil) | |||
| 158 | - | } | |||
| 159 | - | ||||
| 160 | - | var injectPunctuation = map[rune]string{' ': "space", '\n': "Return", '.': "period", ',': "comma", '-': "minus", '_': "underscore", '/': "slash", ':': "colon", ';': "semicolon", '!': "exclam", '?': "question", '\'': "apostrophe", '"': "quotedbl", '(': "parenleft", ')': "parenright", '=': "equal", '+': "plus", '\\': "backslash", '@': "at", '#': "numbersign", '$': "dollar", '%': "percent", '&': "ampersand", '*': "asterisk", '[': "bracketleft", ']': "bracketright", '{': "braceleft", '}': "braceright", '<': "less", '>': "greater", '|': "bar", '`': "grave", '~': "asciitilde", '^': "asciicircum"} | |||
| 161 | - | ||||
| 162 | - | func (i *injector) Type(text string) ([]ports.InputEvent, error) { | |||
| 163 | - | var strokes [][]uint32 | |||
| 164 | - | for _, r := range text { | |||
| 165 | - | name := injectPunctuation[r] | |||
| 166 | - | if name == "" && (unicode.IsLetter(r) || unicode.IsDigit(r)) { | |||
| 167 | - | name = string(r) | |||
| 168 | - | } | |||
| 169 | - | if name == "" { | |||
| 170 | - | return nil, errors.New("unknown rune") | |||
| 171 | - | } | |||
| 172 | - | codes, err := i.combo(name) | |||
| 173 | - | if err != nil { | |||
| 174 | - | return nil, err | |||
| 175 | - | } | |||
| 176 | - | strokes = append(strokes, codes) | |||
| 177 | - | } | |||
| 178 | - | var events []ports.InputEvent | |||
| 179 | - | for _, codes := range strokes { | |||
| 180 | - | var err error | |||
| 181 | - | events, err = i.edges(codes, true, events) | |||
| 182 | - | if err != nil { | |||
| 183 | - | return nil, err | |||
| 184 | - | } | |||
| 185 | - | events, err = i.edges(codes, false, events) | |||
| 186 | - | if err != nil { | |||
| 187 | - | return nil, err | |||
| 188 | - | } | |||
| 189 | - | } | |||
| 190 | - | return events, nil | |||
| 191 | - | } | |||
| 192 | - | ||||
| 193 | - | func (i *injector) Pointer(cmd string, args []string) ([]ports.InputEvent, error) { | |||
| 194 | - | now := injectTime() | |||
| 195 | - | if cmd == "move" { | |||
| 196 | - | if len(args) != 2 { | |||
| 197 | - | return nil, errors.New("move requires x y") | |||
| 198 | - | } | |||
| 199 | - | x, ex := strconv.ParseFloat(args[0], 64) | |||
| 200 | - | y, ey := strconv.ParseFloat(args[1], 64) | |||
| 201 | - | if ex != nil || ey != nil || math.IsNaN(x) || math.IsNaN(y) || math.IsInf(x, 0) || math.IsInf(y, 0) { | |||
| 202 | - | return nil, errors.New("invalid move coordinates") | |||
| 203 | - | } | |||
| 204 | - | return []ports.InputEvent{i.stamp(ports.PointerMotion{Device: controlDeviceID, X: x, Y: y, Time: now}, i.snapshot())}, nil | |||
| 205 | - | } | |||
| 206 | - | if cmd != "click" && cmd != "down" && cmd != "up" { | |||
| 207 | - | return nil, errors.New("unknown pointer command") | |||
| 208 | - | } | |||
| 209 | - | if len(args) > 1 || len(args) == 0 && cmd != "click" { | |||
| 210 | - | return nil, errors.New("invalid button arguments") | |||
| 211 | - | } | |||
| 212 | - | name := "left" | |||
| 213 | - | if len(args) == 1 { | |||
| 214 | - | name = args[0] | |||
| 215 | - | } | |||
| 216 | - | var button uint32 | |||
| 217 | - | switch name { | |||
| 218 | - | case "left": | |||
| 219 | - | button = 0x110 | |||
| 220 | - | case "right": | |||
| 221 | - | button = 0x111 | |||
| 222 | - | case "middle": | |||
| 223 | - | button = 0x112 | |||
| 224 | - | default: | |||
| 225 | - | return nil, errors.New("unknown button") | |||
| 226 | - | } | |||
| 227 | - | var events []ports.InputEvent | |||
| 228 | - | if cmd != "up" { | |||
| 229 | - | events = append(events, i.stamp(ports.PointerButton{Device: controlDeviceID, Button: button, Pressed: true, Time: now}, i.snapshot())) | |||
| 230 | - | } | |||
| 231 | - | if cmd != "down" { | |||
| 232 | - | events = append(events, i.stamp(ports.PointerButton{Device: controlDeviceID, Button: button, Time: now}, i.snapshot())) | |||
| 233 | - | } | |||
| 234 | - | return events, nil | |||
| 235 | - | } | |||
| 236 | - | ||||
| 237 | - | func (i *injector) Swipe(fingers int, dir string) ([]ports.InputEvent, error) { | |||
| 238 | - | if fingers != 3 && fingers != 4 { | |||
| 239 | - | return nil, errors.New("swipe requires three or four fingers") | |||
| 240 | - | } | |||
| 241 | - | var dx, dy float64 | |||
| 242 | - | switch dir { | |||
| 243 | - | case "up": | |||
| 244 | - | dy = -40 | |||
| 245 | - | case "down": | |||
| 246 | - | dy = 40 | |||
| 247 | - | case "left": | |||
| 248 | - | dx = -40 | |||
| 249 | - | case "right": | |||
| 250 | - | dx = 40 | |||
| 251 | - | default: | |||
| 252 | - | return nil, errors.New("invalid swipe direction") | |||
| 253 | - | } | |||
| 254 | - | at := injectTime() | |||
| 255 | - | events := []ports.InputEvent{i.stamp(ports.SwipeBegin{Device: controlDeviceID, Fingers: fingers, Time: at}, i.snapshot())} | |||
| 256 | - | for range 10 { | |||
| 257 | - | at += 8 * time.Millisecond | |||
| 258 | - | events = append(events, i.stamp(ports.SwipeUpdate{Device: controlDeviceID, DX: dx, DY: dy, Time: at}, i.snapshot())) | |||
| 259 | - | } | |||
| 260 | - | return append(events, i.stamp(ports.SwipeEnd{Device: controlDeviceID, Time: at}, i.snapshot())), nil | |||
| 261 | - | } | |||
D internal/adapters/control/inject_test.go +0 -312
| @@ -1,312 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "reflect" | |
| 5 | - | "strings" | |
| 6 | - | "testing" | |
| 7 | - | "time" | |
| 8 | - | ||
| 9 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |
| 10 | - | "github.com/bnema/neferwl/internal/domain" | |
| 11 | - | portsmocks "github.com/bnema/neferwl/internal/mocks/ports" | |
| 12 | - | "github.com/bnema/neferwl/internal/ports" | |
| 13 | - | ) | |
| 14 | - | ||
| 15 | - | func injectKeymap(t *testing.T) *xkb.Keymap { | |
| 16 | - | t.Helper() | |
| 17 | - | km, err := xkb.New(xkb.RMLVO{Layout: "us"}) | |
| 18 | - | if err != nil { | |
| 19 | - | if strings.Contains(err.Error(), "libxkbcommon.so.0") { | |
| 20 | - | t.Skip(err) | |
| 21 | - | } | |
| 22 | - | t.Fatal(err) | |
| 23 | - | } | |
| 24 | - | t.Cleanup(km.Close) | |
| 25 | - | return km | |
| 26 | - | } | |
| 27 | - | ||
| 28 | - | func TestInjectKeys(t *testing.T) { | |
| 29 | - | for _, tt := range []struct { | |
| 30 | - | method, text string | |
| 31 | - | names []string | |
| 32 | - | codes []uint32 | |
| 33 | - | }{ | |
| 34 | - | {"type", "Hi!", []string{"Shift_L", "H", "H", "Shift_L", "i", "i", "Shift_L", "exclam", "exclam", "Shift_L"}, nil}, | |
| 35 | - | {"key", "Shift+A", []string{"Shift_L", "A", "A", "Shift_L"}, []uint32{42, 30, 30, 42}}, | |
| 36 | - | {"key", "Super+Return", []string{"Super_L", "Return", "Return", "Super_L"}, []uint32{125, 28, 28, 125}}, | |
| 37 | - | {"press", "Super", []string{"Super_L"}, []uint32{125}}, | |
| 38 | - | {"release", "Super", []string{"Super_L"}, []uint32{125}}, | |
| 39 | - | {"press", "Shift", []string{"Shift_L"}, []uint32{42}}, | |
| 40 | - | {"press", "Ctrl", []string{"Control_L"}, []uint32{29}}, | |
| 41 | - | {"press", "Alt", []string{"Alt_L"}, []uint32{56}}, | |
| 42 | - | } { | |
| 43 | - | t.Run(tt.method+tt.text, func(t *testing.T) { | |
| 44 | - | i := newInjector(injectKeymap(t), nil) | |
| 45 | - | methods := map[string]func(string) ([]ports.InputEvent, error){"type": i.Type, "key": i.Key, "press": i.Press, "release": i.Release} | |
| 46 | - | events, err := methods[tt.method](tt.text) | |
| 47 | - | if err != nil { | |
| 48 | - | t.Fatal(err) | |
| 49 | - | } | |
| 50 | - | if len(events) != len(tt.names) { | |
| 51 | - | t.Fatalf("events %v", events) | |
| 52 | - | } | |
| 53 | - | for n, raw := range events { | |
| 54 | - | ev := raw.(ports.KeyEvent) | |
| 55 | - | if ev.Device != controlDeviceID || ev.Keysym != tt.names[n] || tt.codes != nil && ev.Keycode != tt.codes[n] { | |
| 56 | - | t.Fatalf("event %d: %+v", n, ev) | |
| 57 | - | } | |
| 58 | - | if tt.text == "Super+Return" && (n == 1 && ev.Mods&domain.ModSuper == 0 || n == 3 && ev.Mods&domain.ModSuper != 0) { | |
| 59 | - | t.Fatal(ev) | |
| 60 | - | } | |
| 61 | - | } | |
| 62 | - | }) | |
| 63 | - | } | |
| 64 | - | } | |
| 65 | - | ||
| 66 | - | func TestInjectModifierAcrossPointer(t *testing.T) { | |
| 67 | - | i := newInjector(injectKeymap(t), nil) | |
| 68 | - | events, err := i.Press("Super") | |
| 69 | - | if err != nil || !events[0].(ports.KeyEvent).Pressed { | |
| 70 | - | t.Fatal(events, err) | |
| 71 | - | } | |
| 72 | - | for _, cmd := range []struct { | |
| 73 | - | name string | |
| 74 | - | args []string | |
| 75 | - | }{{"move", []string{"500", "100"}}, {"down", []string{"right"}}, {"move", []string{"700", "100"}}, {"up", []string{"right"}}} { | |
| 76 | - | if _, err := i.Pointer(cmd.name, cmd.args); err != nil { | |
| 77 | - | t.Fatal(err) | |
| 78 | - | } | |
| 79 | - | } | |
| 80 | - | events, err = i.Press("h") | |
| 81 | - | if err != nil || events[0].(ports.KeyEvent).Mods&domain.ModSuper == 0 { | |
| 82 | - | t.Fatal(events, err) | |
| 83 | - | } | |
| 84 | - | if _, err := i.Release("h"); err != nil { | |
| 85 | - | t.Fatal(err) | |
| 86 | - | } | |
| 87 | - | events, err = i.Release("Super") | |
| 88 | - | if err != nil || events[0].(ports.KeyEvent).Mods&domain.ModSuper != 0 { | |
| 89 | - | t.Fatal(events, err) | |
| 90 | - | } | |
| 91 | - | events, err = i.Press("Super+Shift+a") | |
| 92 | - | if err != nil || len(events) != 3 { | |
| 93 | - | t.Fatal(events, err) | |
| 94 | - | } | |
| 95 | - | events, err = i.Release("Super+Shift+a") | |
| 96 | - | if err != nil || len(events) != 3 { | |
| 97 | - | t.Fatal(events, err) | |
| 98 | - | } | |
| 99 | - | for n, code := range []uint32{30, 42, 125} { | |
| 100 | - | if ev := events[n].(ports.KeyEvent); ev.Pressed || ev.Keycode != code { | |
| 101 | - | t.Fatal(ev) | |
| 102 | - | } | |
| 103 | - | } | |
| 104 | - | } | |
| 105 | - | ||
| 106 | - | func TestInjectPointerAndSwipe(t *testing.T) { | |
| 107 | - | i := newInjector(injectKeymap(t), nil) | |
| 108 | - | if got := i.Device(); got != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |
| 109 | - | t.Fatal(got) | |
| 110 | - | } | |
| 111 | - | events, err := i.Pointer("move", []string{"12.5", "45"}) | |
| 112 | - | if err != nil { | |
| 113 | - | t.Fatal(err) | |
| 114 | - | } | |
| 115 | - | m := events[0].(ports.PointerMotion) | |
| 116 | - | if m.Device != controlDeviceID || m.X != 12.5 || m.Y != 45 || m.DX != 0 || m.DY != 0 { | |
| 117 | - | t.Fatal(m) | |
| 118 | - | } | |
| 119 | - | for _, name := range []string{"left", "right", "middle"} { | |
| 120 | - | var args []string | |
| 121 | - | if name != "left" { | |
| 122 | - | args = []string{name} | |
| 123 | - | } | |
| 124 | - | events, err = i.Pointer("click", args) | |
| 125 | - | if err != nil || len(events) != 2 { | |
| 126 | - | t.Fatal(events, err) | |
| 127 | - | } | |
| 128 | - | down, up := events[0].(ports.PointerButton), events[1].(ports.PointerButton) | |
| 129 | - | code := map[string]uint32{"left": 0x110, "right": 0x111, "middle": 0x112}[name] | |
| 130 | - | if down.Device != controlDeviceID || down.Button != code || !down.Pressed || up.Pressed || up.Button != code || up.Time != down.Time { | |
| 131 | - | t.Fatal(events) | |
| 132 | - | } | |
| 133 | - | } | |
| 134 | - | for _, fingers := range []int{3, 4} { | |
| 135 | - | for dir, delta := range map[string][2]float64{"left": {-40, 0}, "right": {40, 0}, "up": {0, -40}, "down": {0, 40}} { | |
| 136 | - | events, err := i.Swipe(fingers, dir) | |
| 137 | - | if err != nil || len(events) != 12 { | |
| 138 | - | t.Fatal(events, err) | |
| 139 | - | } | |
| 140 | - | begin := events[0].(ports.SwipeBegin) | |
| 141 | - | if begin.Device != controlDeviceID || begin.Fingers != fingers { | |
| 142 | - | t.Fatal(begin) | |
| 143 | - | } | |
| 144 | - | at := begin.Time | |
| 145 | - | for _, raw := range events[1:11] { | |
| 146 | - | u := raw.(ports.SwipeUpdate) | |
| 147 | - | if u.Device != controlDeviceID || u.DX != delta[0] || u.DY != delta[1] || u.Time-at != 8*time.Millisecond { | |
| 148 | - | t.Fatal(u) | |
| 149 | - | } | |
| 150 | - | at = u.Time | |
| 151 | - | } | |
| 152 | - | if end := events[11].(ports.SwipeEnd); end.Device != controlDeviceID || end.Cancelled || end.Time != at { | |
| 153 | - | t.Fatal(end) | |
| 154 | - | } | |
| 155 | - | } | |
| 156 | - | } | |
| 157 | - | } | |
| 158 | - | ||
| 159 | - | func TestInjectInvalid(t *testing.T) { | |
| 160 | - | i := newInjector(injectKeymap(t), nil) | |
| 161 | - | for _, text := range []string{"", "Super+", "Unknown+a", "Super+not-a-key", "Super extra"} { | |
| 162 | - | for _, f := range []func(string) ([]ports.InputEvent, error){i.Key, i.Press, i.Release} { | |
| 163 | - | if ev, err := f(text); err == nil || len(ev) != 0 { | |
| 164 | - | t.Fatalf("%q: %v %v", text, ev, err) | |
| 165 | - | } | |
| 166 | - | } | |
| 167 | - | } | |
| 168 | - | if ev, err := i.Type("ok🔐"); err == nil || len(ev) != 0 { | |
| 169 | - | t.Fatal(ev, err) | |
| 170 | - | } | |
| 171 | - | for _, cmd := range []struct { | |
| 172 | - | name string | |
| 173 | - | args []string | |
| 174 | - | }{{"move", nil}, {"move", []string{"NaN", "1"}}, {"move", []string{"1", "Inf"}}, {"move", []string{"x", "2"}}, {"move", []string{"1", "2", "3"}}, {"click", []string{"bad"}}, {"down", nil}, {"up", []string{"left", "right"}}, {"bad", nil}} { | |
| 175 | - | if ev, err := i.Pointer(cmd.name, cmd.args); err == nil || len(ev) != 0 { | |
| 176 | - | t.Fatal(ev, err) | |
| 177 | - | } | |
| 178 | - | } | |
| 179 | - | for _, args := range []struct { | |
| 180 | - | f int | |
| 181 | - | d string | |
| 182 | - | }{{2, "left"}, {3, "sideways"}, {5, "up"}} { | |
| 183 | - | if ev, err := i.Swipe(args.f, args.d); err == nil || len(ev) != 0 { | |
| 184 | - | t.Fatal(ev, err) | |
| 185 | - | } | |
| 186 | - | } | |
| 187 | - | // Validation did not leave Super or an implicit Shift pressed. | |
| 188 | - | ev, err := i.Key("a") | |
| 189 | - | if err != nil || ev[0].(ports.KeyEvent).Mods != 0 { | |
| 190 | - | t.Fatal(ev, err) | |
| 191 | - | } | |
| 192 | - | } | |
| 193 | - | ||
| 194 | - | func TestInjectSecuritySnapshots(t *testing.T) { | |
| 195 | - | security := portsmocks.NewMockSessionSecurity(t) | |
| 196 | - | state := domain.SecurityState{Generation: 7, Protected: true} | |
| 197 | - | security.EXPECT().Snapshot().Return(state).Maybe() | |
| 198 | - | i := newInjector(injectKeymap(t), security) | |
| 199 | - | device := i.Device().(ports.SecurityInput) | |
| 200 | - | if device.State != state || device.Event != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |
| 201 | - | t.Fatal(device) | |
| 202 | - | } | |
| 203 | - | var events []ports.InputEvent | |
| 204 | - | key, err := i.Key("A") | |
| 205 | - | if err != nil { | |
| 206 | - | t.Fatal(err) | |
| 207 | - | } | |
| 208 | - | events = append(events, key...) | |
| 209 | - | move, err := i.Pointer("move", []string{"10", "20"}) | |
| 210 | - | if err != nil { | |
| 211 | - | t.Fatal(err) | |
| 212 | - | } | |
| 213 | - | events = append(events, move...) | |
| 214 | - | click, err := i.Pointer("click", nil) | |
| 215 | - | if err != nil { | |
| 216 | - | t.Fatal(err) | |
| 217 | - | } | |
| 218 | - | events = append(events, click...) | |
| 219 | - | swipe, err := i.Swipe(3, "left") | |
| 220 | - | if err != nil { | |
| 221 | - | t.Fatal(err) | |
| 222 | - | } | |
| 223 | - | events = append(events, swipe...) | |
| 224 | - | for _, raw := range events { | |
| 225 | - | ev, ok := raw.(ports.SecurityInput) | |
| 226 | - | if !ok || ev.State != state || reflect.ValueOf(ev.Event).FieldByName("Device").Uint() != uint64(controlDeviceID) { | |
| 227 | - | t.Fatal(raw) | |
| 228 | - | } | |
| 229 | - | } | |
| 230 | - | } | |
| 231 | - | ||
| 232 | - | func TestInjectSecurityQuarantine(t *testing.T) { | |
| 233 | - | km := injectKeymap(t) | |
| 234 | - | security := portsmocks.NewMockSessionSecurity(t) | |
| 235 | - | initial := domain.SecurityState{} | |
| 236 | - | locked := domain.SecurityState{Generation: 1, Protected: true} | |
| 237 | - | security.EXPECT().Snapshot().Return(initial).Once() | |
| 238 | - | i := newInjector(km, security) | |
| 239 | - | if _, err := i.Press("Super"); err != nil { | |
| 240 | - | t.Fatal(err) | |
| 241 | - | } | |
| 242 | - | security.EXPECT().Snapshot().Return(locked).Times(5) | |
| 243 | - | events, err := i.Key("q") | |
| 244 | - | if err != nil { | |
| 245 | - | t.Fatal(err) | |
| 246 | - | } | |
| 247 | - | for _, raw := range events { | |
| 248 | - | if ev := raw.(ports.SecurityInput).Event.(ports.KeyEvent); ev.Mods&domain.ModSuper != 0 { | |
| 249 | - | t.Fatal(ev) | |
| 250 | - | } | |
| 251 | - | } | |
| 252 | - | events, err = i.Release("Super") | |
| 253 | - | if err != nil || len(events) != 0 { | |
| 254 | - | t.Fatal("held modifier was not quarantined", events, err) | |
| 255 | - | } | |
| 256 | - | events, err = i.Key("q") | |
| 257 | - | if err != nil || len(events) != 2 { | |
| 258 | - | t.Fatal(events, err) | |
| 259 | - | } | |
| 260 | - | } | |
| 261 | - | ||
| 262 | - | func TestInjectPunctuation(t *testing.T) { | |
| 263 | - | i := newInjector(injectKeymap(t), nil) | |
| 264 | - | for r := range injectPunctuation { | |
| 265 | - | events, err := i.Type(string(r)) | |
| 266 | - | if err != nil || len(events) < 2 { | |
| 267 | - | t.Fatalf("rune %q: %v %v", r, events, err) | |
| 268 | - | } | |
| 269 | - | } | |
| 270 | - | if events, err := i.Type(""); err != nil || len(events) != 0 { | |
| 271 | - | t.Fatal(events, err) | |
| 272 | - | } | |
| 273 | - | } | |
| 274 | - | ||
| 275 | - | func TestInjectSecuritySnapshotBeforeTranslation(t *testing.T) { | |
| 276 | - | km := injectKeymap(t) | |
| 277 | - | security := portsmocks.NewMockSessionSecurity(t) | |
| 278 | - | initial := domain.SecurityState{} | |
| 279 | - | locked := domain.SecurityState{Generation: 1, Protected: true} | |
| 280 | - | security.EXPECT().Snapshot().Return(initial).Once() | |
| 281 | - | i := newInjector(km, security) | |
| 282 | - | if _, err := i.Press("Super"); err != nil { | |
| 283 | - | t.Fatal(err) | |
| 284 | - | } | |
| 285 | - | // The epoch changes between the key's press and release. The release is | |
| 286 | - | // quarantined, rather than translated using the previous modifier state. | |
| 287 | - | security.EXPECT().Snapshot().Return(initial).Once() | |
| 288 | - | security.EXPECT().Snapshot().Return(locked).Once() | |
| 289 | - | events, err := i.Key("q") | |
| 290 | - | if err != nil || len(events) != 1 { | |
| 291 | - | t.Fatal(events, err) | |
| 292 | - | } | |
| 293 | - | ev := events[0].(ports.SecurityInput) | |
| 294 | - | if ev.State != initial || ev.Event.(ports.KeyEvent).Mods&domain.ModSuper == 0 { | |
| 295 | - | t.Fatal(ev) | |
| 296 | - | } | |
| 297 | - | security.EXPECT().Snapshot().Return(locked).Times(3) | |
| 298 | - | events, err = i.Release("Super") | |
| 299 | - | if err != nil || len(events) != 0 { | |
| 300 | - | t.Fatal(events, err) | |
| 301 | - | } | |
| 302 | - | events, err = i.Key("q") | |
| 303 | - | if err != nil || len(events) != 2 { | |
| 304 | - | t.Fatal(events, err) | |
| 305 | - | } | |
| 306 | - | for _, raw := range events { | |
| 307 | - | ev := raw.(ports.SecurityInput) | |
| 308 | - | if ev.State != locked || ev.Event.(ports.KeyEvent).Mods&domain.ModSuper != 0 { | |
| 309 | - | t.Fatal(ev) | |
| 310 | - | } | |
| 311 | - | } | |
| 312 | - | } | |
| @@ -1,312 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "reflect" | |||
| 5 | - | "strings" | |||
| 6 | - | "testing" | |||
| 7 | - | "time" | |||
| 8 | - | ||||
| 9 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |||
| 10 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 11 | - | portsmocks "github.com/bnema/neferwl/internal/mocks/ports" | |||
| 12 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 13 | - | ) | |||
| 14 | - | ||||
| 15 | - | func injectKeymap(t *testing.T) *xkb.Keymap { | |||
| 16 | - | t.Helper() | |||
| 17 | - | km, err := xkb.New(xkb.RMLVO{Layout: "us"}) | |||
| 18 | - | if err != nil { | |||
| 19 | - | if strings.Contains(err.Error(), "libxkbcommon.so.0") { | |||
| 20 | - | t.Skip(err) | |||
| 21 | - | } | |||
| 22 | - | t.Fatal(err) | |||
| 23 | - | } | |||
| 24 | - | t.Cleanup(km.Close) | |||
| 25 | - | return km | |||
| 26 | - | } | |||
| 27 | - | ||||
| 28 | - | func TestInjectKeys(t *testing.T) { | |||
| 29 | - | for _, tt := range []struct { | |||
| 30 | - | method, text string | |||
| 31 | - | names []string | |||
| 32 | - | codes []uint32 | |||
| 33 | - | }{ | |||
| 34 | - | {"type", "Hi!", []string{"Shift_L", "H", "H", "Shift_L", "i", "i", "Shift_L", "exclam", "exclam", "Shift_L"}, nil}, | |||
| 35 | - | {"key", "Shift+A", []string{"Shift_L", "A", "A", "Shift_L"}, []uint32{42, 30, 30, 42}}, | |||
| 36 | - | {"key", "Super+Return", []string{"Super_L", "Return", "Return", "Super_L"}, []uint32{125, 28, 28, 125}}, | |||
| 37 | - | {"press", "Super", []string{"Super_L"}, []uint32{125}}, | |||
| 38 | - | {"release", "Super", []string{"Super_L"}, []uint32{125}}, | |||
| 39 | - | {"press", "Shift", []string{"Shift_L"}, []uint32{42}}, | |||
| 40 | - | {"press", "Ctrl", []string{"Control_L"}, []uint32{29}}, | |||
| 41 | - | {"press", "Alt", []string{"Alt_L"}, []uint32{56}}, | |||
| 42 | - | } { | |||
| 43 | - | t.Run(tt.method+tt.text, func(t *testing.T) { | |||
| 44 | - | i := newInjector(injectKeymap(t), nil) | |||
| 45 | - | methods := map[string]func(string) ([]ports.InputEvent, error){"type": i.Type, "key": i.Key, "press": i.Press, "release": i.Release} | |||
| 46 | - | events, err := methods[tt.method](tt.text) | |||
| 47 | - | if err != nil { | |||
| 48 | - | t.Fatal(err) | |||
| 49 | - | } | |||
| 50 | - | if len(events) != len(tt.names) { | |||
| 51 | - | t.Fatalf("events %v", events) | |||
| 52 | - | } | |||
| 53 | - | for n, raw := range events { | |||
| 54 | - | ev := raw.(ports.KeyEvent) | |||
| 55 | - | if ev.Device != controlDeviceID || ev.Keysym != tt.names[n] || tt.codes != nil && ev.Keycode != tt.codes[n] { | |||
| 56 | - | t.Fatalf("event %d: %+v", n, ev) | |||
| 57 | - | } | |||
| 58 | - | if tt.text == "Super+Return" && (n == 1 && ev.Mods&domain.ModSuper == 0 || n == 3 && ev.Mods&domain.ModSuper != 0) { | |||
| 59 | - | t.Fatal(ev) | |||
| 60 | - | } | |||
| 61 | - | } | |||
| 62 | - | }) | |||
| 63 | - | } | |||
| 64 | - | } | |||
| 65 | - | ||||
| 66 | - | func TestInjectModifierAcrossPointer(t *testing.T) { | |||
| 67 | - | i := newInjector(injectKeymap(t), nil) | |||
| 68 | - | events, err := i.Press("Super") | |||
| 69 | - | if err != nil || !events[0].(ports.KeyEvent).Pressed { | |||
| 70 | - | t.Fatal(events, err) | |||
| 71 | - | } | |||
| 72 | - | for _, cmd := range []struct { | |||
| 73 | - | name string | |||
| 74 | - | args []string | |||
| 75 | - | }{{"move", []string{"500", "100"}}, {"down", []string{"right"}}, {"move", []string{"700", "100"}}, {"up", []string{"right"}}} { | |||
| 76 | - | if _, err := i.Pointer(cmd.name, cmd.args); err != nil { | |||
| 77 | - | t.Fatal(err) | |||
| 78 | - | } | |||
| 79 | - | } | |||
| 80 | - | events, err = i.Press("h") | |||
| 81 | - | if err != nil || events[0].(ports.KeyEvent).Mods&domain.ModSuper == 0 { | |||
| 82 | - | t.Fatal(events, err) | |||
| 83 | - | } | |||
| 84 | - | if _, err := i.Release("h"); err != nil { | |||
| 85 | - | t.Fatal(err) | |||
| 86 | - | } | |||
| 87 | - | events, err = i.Release("Super") | |||
| 88 | - | if err != nil || events[0].(ports.KeyEvent).Mods&domain.ModSuper != 0 { | |||
| 89 | - | t.Fatal(events, err) | |||
| 90 | - | } | |||
| 91 | - | events, err = i.Press("Super+Shift+a") | |||
| 92 | - | if err != nil || len(events) != 3 { | |||
| 93 | - | t.Fatal(events, err) | |||
| 94 | - | } | |||
| 95 | - | events, err = i.Release("Super+Shift+a") | |||
| 96 | - | if err != nil || len(events) != 3 { | |||
| 97 | - | t.Fatal(events, err) | |||
| 98 | - | } | |||
| 99 | - | for n, code := range []uint32{30, 42, 125} { | |||
| 100 | - | if ev := events[n].(ports.KeyEvent); ev.Pressed || ev.Keycode != code { | |||
| 101 | - | t.Fatal(ev) | |||
| 102 | - | } | |||
| 103 | - | } | |||
| 104 | - | } | |||
| 105 | - | ||||
| 106 | - | func TestInjectPointerAndSwipe(t *testing.T) { | |||
| 107 | - | i := newInjector(injectKeymap(t), nil) | |||
| 108 | - | if got := i.Device(); got != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |||
| 109 | - | t.Fatal(got) | |||
| 110 | - | } | |||
| 111 | - | events, err := i.Pointer("move", []string{"12.5", "45"}) | |||
| 112 | - | if err != nil { | |||
| 113 | - | t.Fatal(err) | |||
| 114 | - | } | |||
| 115 | - | m := events[0].(ports.PointerMotion) | |||
| 116 | - | if m.Device != controlDeviceID || m.X != 12.5 || m.Y != 45 || m.DX != 0 || m.DY != 0 { | |||
| 117 | - | t.Fatal(m) | |||
| 118 | - | } | |||
| 119 | - | for _, name := range []string{"left", "right", "middle"} { | |||
| 120 | - | var args []string | |||
| 121 | - | if name != "left" { | |||
| 122 | - | args = []string{name} | |||
| 123 | - | } | |||
| 124 | - | events, err = i.Pointer("click", args) | |||
| 125 | - | if err != nil || len(events) != 2 { | |||
| 126 | - | t.Fatal(events, err) | |||
| 127 | - | } | |||
| 128 | - | down, up := events[0].(ports.PointerButton), events[1].(ports.PointerButton) | |||
| 129 | - | code := map[string]uint32{"left": 0x110, "right": 0x111, "middle": 0x112}[name] | |||
| 130 | - | if down.Device != controlDeviceID || down.Button != code || !down.Pressed || up.Pressed || up.Button != code || up.Time != down.Time { | |||
| 131 | - | t.Fatal(events) | |||
| 132 | - | } | |||
| 133 | - | } | |||
| 134 | - | for _, fingers := range []int{3, 4} { | |||
| 135 | - | for dir, delta := range map[string][2]float64{"left": {-40, 0}, "right": {40, 0}, "up": {0, -40}, "down": {0, 40}} { | |||
| 136 | - | events, err := i.Swipe(fingers, dir) | |||
| 137 | - | if err != nil || len(events) != 12 { | |||
| 138 | - | t.Fatal(events, err) | |||
| 139 | - | } | |||
| 140 | - | begin := events[0].(ports.SwipeBegin) | |||
| 141 | - | if begin.Device != controlDeviceID || begin.Fingers != fingers { | |||
| 142 | - | t.Fatal(begin) | |||
| 143 | - | } | |||
| 144 | - | at := begin.Time | |||
| 145 | - | for _, raw := range events[1:11] { | |||
| 146 | - | u := raw.(ports.SwipeUpdate) | |||
| 147 | - | if u.Device != controlDeviceID || u.DX != delta[0] || u.DY != delta[1] || u.Time-at != 8*time.Millisecond { | |||
| 148 | - | t.Fatal(u) | |||
| 149 | - | } | |||
| 150 | - | at = u.Time | |||
| 151 | - | } | |||
| 152 | - | if end := events[11].(ports.SwipeEnd); end.Device != controlDeviceID || end.Cancelled || end.Time != at { | |||
| 153 | - | t.Fatal(end) | |||
| 154 | - | } | |||
| 155 | - | } | |||
| 156 | - | } | |||
| 157 | - | } | |||
| 158 | - | ||||
| 159 | - | func TestInjectInvalid(t *testing.T) { | |||
| 160 | - | i := newInjector(injectKeymap(t), nil) | |||
| 161 | - | for _, text := range []string{"", "Super+", "Unknown+a", "Super+not-a-key", "Super extra"} { | |||
| 162 | - | for _, f := range []func(string) ([]ports.InputEvent, error){i.Key, i.Press, i.Release} { | |||
| 163 | - | if ev, err := f(text); err == nil || len(ev) != 0 { | |||
| 164 | - | t.Fatalf("%q: %v %v", text, ev, err) | |||
| 165 | - | } | |||
| 166 | - | } | |||
| 167 | - | } | |||
| 168 | - | if ev, err := i.Type("ok🔐"); err == nil || len(ev) != 0 { | |||
| 169 | - | t.Fatal(ev, err) | |||
| 170 | - | } | |||
| 171 | - | for _, cmd := range []struct { | |||
| 172 | - | name string | |||
| 173 | - | args []string | |||
| 174 | - | }{{"move", nil}, {"move", []string{"NaN", "1"}}, {"move", []string{"1", "Inf"}}, {"move", []string{"x", "2"}}, {"move", []string{"1", "2", "3"}}, {"click", []string{"bad"}}, {"down", nil}, {"up", []string{"left", "right"}}, {"bad", nil}} { | |||
| 175 | - | if ev, err := i.Pointer(cmd.name, cmd.args); err == nil || len(ev) != 0 { | |||
| 176 | - | t.Fatal(ev, err) | |||
| 177 | - | } | |||
| 178 | - | } | |||
| 179 | - | for _, args := range []struct { | |||
| 180 | - | f int | |||
| 181 | - | d string | |||
| 182 | - | }{{2, "left"}, {3, "sideways"}, {5, "up"}} { | |||
| 183 | - | if ev, err := i.Swipe(args.f, args.d); err == nil || len(ev) != 0 { | |||
| 184 | - | t.Fatal(ev, err) | |||
| 185 | - | } | |||
| 186 | - | } | |||
| 187 | - | // Validation did not leave Super or an implicit Shift pressed. | |||
| 188 | - | ev, err := i.Key("a") | |||
| 189 | - | if err != nil || ev[0].(ports.KeyEvent).Mods != 0 { | |||
| 190 | - | t.Fatal(ev, err) | |||
| 191 | - | } | |||
| 192 | - | } | |||
| 193 | - | ||||
| 194 | - | func TestInjectSecuritySnapshots(t *testing.T) { | |||
| 195 | - | security := portsmocks.NewMockSessionSecurity(t) | |||
| 196 | - | state := domain.SecurityState{Generation: 7, Protected: true} | |||
| 197 | - | security.EXPECT().Snapshot().Return(state).Maybe() | |||
| 198 | - | i := newInjector(injectKeymap(t), security) | |||
| 199 | - | device := i.Device().(ports.SecurityInput) | |||
| 200 | - | if device.State != state || device.Event != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |||
| 201 | - | t.Fatal(device) | |||
| 202 | - | } | |||
| 203 | - | var events []ports.InputEvent | |||
| 204 | - | key, err := i.Key("A") | |||
| 205 | - | if err != nil { | |||
| 206 | - | t.Fatal(err) | |||
| 207 | - | } | |||
| 208 | - | events = append(events, key...) | |||
| 209 | - | move, err := i.Pointer("move", []string{"10", "20"}) | |||
| 210 | - | if err != nil { | |||
| 211 | - | t.Fatal(err) | |||
| 212 | - | } | |||
| 213 | - | events = append(events, move...) | |||
| 214 | - | click, err := i.Pointer("click", nil) | |||
| 215 | - | if err != nil { | |||
| 216 | - | t.Fatal(err) | |||
| 217 | - | } | |||
| 218 | - | events = append(events, click...) | |||
| 219 | - | swipe, err := i.Swipe(3, "left") | |||
| 220 | - | if err != nil { | |||
| 221 | - | t.Fatal(err) | |||
| 222 | - | } | |||
| 223 | - | events = append(events, swipe...) | |||
| 224 | - | for _, raw := range events { | |||
| 225 | - | ev, ok := raw.(ports.SecurityInput) | |||
| 226 | - | if !ok || ev.State != state || reflect.ValueOf(ev.Event).FieldByName("Device").Uint() != uint64(controlDeviceID) { | |||
| 227 | - | t.Fatal(raw) | |||
| 228 | - | } | |||
| 229 | - | } | |||
| 230 | - | } | |||
| 231 | - | ||||
| 232 | - | func TestInjectSecurityQuarantine(t *testing.T) { | |||
| 233 | - | km := injectKeymap(t) | |||
| 234 | - | security := portsmocks.NewMockSessionSecurity(t) | |||
| 235 | - | initial := domain.SecurityState{} | |||
| 236 | - | locked := domain.SecurityState{Generation: 1, Protected: true} | |||
| 237 | - | security.EXPECT().Snapshot().Return(initial).Once() | |||
| 238 | - | i := newInjector(km, security) | |||
| 239 | - | if _, err := i.Press("Super"); err != nil { | |||
| 240 | - | t.Fatal(err) | |||
| 241 | - | } | |||
| 242 | - | security.EXPECT().Snapshot().Return(locked).Times(5) | |||
| 243 | - | events, err := i.Key("q") | |||
| 244 | - | if err != nil { | |||
| 245 | - | t.Fatal(err) | |||
| 246 | - | } | |||
| 247 | - | for _, raw := range events { | |||
| 248 | - | if ev := raw.(ports.SecurityInput).Event.(ports.KeyEvent); ev.Mods&domain.ModSuper != 0 { | |||
| 249 | - | t.Fatal(ev) | |||
| 250 | - | } | |||
| 251 | - | } | |||
| 252 | - | events, err = i.Release("Super") | |||
| 253 | - | if err != nil || len(events) != 0 { | |||
| 254 | - | t.Fatal("held modifier was not quarantined", events, err) | |||
| 255 | - | } | |||
| 256 | - | events, err = i.Key("q") | |||
| 257 | - | if err != nil || len(events) != 2 { | |||
| 258 | - | t.Fatal(events, err) | |||
| 259 | - | } | |||
| 260 | - | } | |||
| 261 | - | ||||
| 262 | - | func TestInjectPunctuation(t *testing.T) { | |||
| 263 | - | i := newInjector(injectKeymap(t), nil) | |||
| 264 | - | for r := range injectPunctuation { | |||
| 265 | - | events, err := i.Type(string(r)) | |||
| 266 | - | if err != nil || len(events) < 2 { | |||
| 267 | - | t.Fatalf("rune %q: %v %v", r, events, err) | |||
| 268 | - | } | |||
| 269 | - | } | |||
| 270 | - | if events, err := i.Type(""); err != nil || len(events) != 0 { | |||
| 271 | - | t.Fatal(events, err) | |||
| 272 | - | } | |||
| 273 | - | } | |||
| 274 | - | ||||
| 275 | - | func TestInjectSecuritySnapshotBeforeTranslation(t *testing.T) { | |||
| 276 | - | km := injectKeymap(t) | |||
| 277 | - | security := portsmocks.NewMockSessionSecurity(t) | |||
| 278 | - | initial := domain.SecurityState{} | |||
| 279 | - | locked := domain.SecurityState{Generation: 1, Protected: true} | |||
| 280 | - | security.EXPECT().Snapshot().Return(initial).Once() | |||
| 281 | - | i := newInjector(km, security) | |||
| 282 | - | if _, err := i.Press("Super"); err != nil { | |||
| 283 | - | t.Fatal(err) | |||
| 284 | - | } | |||
| 285 | - | // The epoch changes between the key's press and release. The release is | |||
| 286 | - | // quarantined, rather than translated using the previous modifier state. | |||
| 287 | - | security.EXPECT().Snapshot().Return(initial).Once() | |||
| 288 | - | security.EXPECT().Snapshot().Return(locked).Once() | |||
| 289 | - | events, err := i.Key("q") | |||
| 290 | - | if err != nil || len(events) != 1 { | |||
| 291 | - | t.Fatal(events, err) | |||
| 292 | - | } | |||
| 293 | - | ev := events[0].(ports.SecurityInput) | |||
| 294 | - | if ev.State != initial || ev.Event.(ports.KeyEvent).Mods&domain.ModSuper == 0 { | |||
| 295 | - | t.Fatal(ev) | |||
| 296 | - | } | |||
| 297 | - | security.EXPECT().Snapshot().Return(locked).Times(3) | |||
| 298 | - | events, err = i.Release("Super") | |||
| 299 | - | if err != nil || len(events) != 0 { | |||
| 300 | - | t.Fatal(events, err) | |||
| 301 | - | } | |||
| 302 | - | events, err = i.Key("q") | |||
| 303 | - | if err != nil || len(events) != 2 { | |||
| 304 | - | t.Fatal(events, err) | |||
| 305 | - | } | |||
| 306 | - | for _, raw := range events { | |||
| 307 | - | ev := raw.(ports.SecurityInput) | |||
| 308 | - | if ev.State != locked || ev.Event.(ports.KeyEvent).Mods&domain.ModSuper != 0 { | |||
| 309 | - | t.Fatal(ev) | |||
| 310 | - | } | |||
| 311 | - | } | |||
| 312 | - | } | |||
D internal/adapters/control/inject_wire.go +0 -84
| @@ -1,84 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "errors" | |
| 5 | - | ||
| 6 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |
| 7 | - | "github.com/bnema/neferwl/internal/ports" | |
| 8 | - | ) | |
| 9 | - | ||
| 10 | - | // translate requires injectMu through admission. Reloads happen before Begin, | |
| 11 | - | // never while the tentative translation is awaiting core admission. | |
| 12 | - | func (s *Server) translate(req request, announce bool) ([]ports.InputEvent, *xkb.Transaction, error) { | |
| 13 | - | select { | |
| 14 | - | case <-s.done: | |
| 15 | - | return nil, nil, errors.New("control closed") | |
| 16 | - | default: | |
| 17 | - | } | |
| 18 | - | if s.injector == nil { | |
| 19 | - | return nil, nil, errors.New("input unavailable") | |
| 20 | - | } | |
| 21 | - | for s.keymaps != nil { | |
| 22 | - | select { | |
| 23 | - | case next, ok := <-s.keymaps: | |
| 24 | - | if !ok { | |
| 25 | - | s.keymaps = nil | |
| 26 | - | continue | |
| 27 | - | } | |
| 28 | - | if next == nil { | |
| 29 | - | continue | |
| 30 | - | } | |
| 31 | - | previous := s.injector.km | |
| 32 | - | if s.injector.security != nil { | |
| 33 | - | next.QuarantineFrom(previous) | |
| 34 | - | } | |
| 35 | - | s.injector.km = next | |
| 36 | - | previous.Close() | |
| 37 | - | default: | |
| 38 | - | goto ready | |
| 39 | - | } | |
| 40 | - | } | |
| 41 | - | ready: | |
| 42 | - | i := s.injector | |
| 43 | - | tx, err := i.km.Begin() | |
| 44 | - | if err != nil { | |
| 45 | - | return nil, nil, err | |
| 46 | - | } | |
| 47 | - | success := false | |
| 48 | - | defer func() { | |
| 49 | - | if !success { | |
| 50 | - | tx.Rollback() | |
| 51 | - | } | |
| 52 | - | }() | |
| 53 | - | var events []ports.InputEvent | |
| 54 | - | // Snapshot an announcement before translating the first event, but don't | |
| 55 | - | // deliver it or consume the connection's announcement on validation failure. | |
| 56 | - | var device ports.InputEvent | |
| 57 | - | if announce { | |
| 58 | - | device = i.Device() | |
| 59 | - | } | |
| 60 | - | switch req.Kind { | |
| 61 | - | case "key": | |
| 62 | - | events, err = i.Key(req.Combo) | |
| 63 | - | case "type": | |
| 64 | - | events, err = i.Type(req.Text) | |
| 65 | - | case "press": | |
| 66 | - | events, err = i.Press(req.Combo) | |
| 67 | - | case "release": | |
| 68 | - | events, err = i.Release(req.Combo) | |
| 69 | - | case "pointer": | |
| 70 | - | events, err = i.Pointer(req.Cmd, req.Args) | |
| 71 | - | case "swipe": | |
| 72 | - | events, err = i.Swipe(req.Fingers, req.Dir) | |
| 73 | - | default: | |
| 74 | - | return nil, nil, errors.New("unknown injection kind") | |
| 75 | - | } | |
| 76 | - | if err != nil { | |
| 77 | - | return nil, nil, err | |
| 78 | - | } | |
| 79 | - | if announce { | |
| 80 | - | events = append([]ports.InputEvent{device}, events...) | |
| 81 | - | } | |
| 82 | - | success = true | |
| 83 | - | return events, tx, nil | |
| 84 | - | } | |
| @@ -1,84 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "errors" | |||
| 5 | - | ||||
| 6 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |||
| 7 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 8 | - | ) | |||
| 9 | - | ||||
| 10 | - | // translate requires injectMu through admission. Reloads happen before Begin, | |||
| 11 | - | // never while the tentative translation is awaiting core admission. | |||
| 12 | - | func (s *Server) translate(req request, announce bool) ([]ports.InputEvent, *xkb.Transaction, error) { | |||
| 13 | - | select { | |||
| 14 | - | case <-s.done: | |||
| 15 | - | return nil, nil, errors.New("control closed") | |||
| 16 | - | default: | |||
| 17 | - | } | |||
| 18 | - | if s.injector == nil { | |||
| 19 | - | return nil, nil, errors.New("input unavailable") | |||
| 20 | - | } | |||
| 21 | - | for s.keymaps != nil { | |||
| 22 | - | select { | |||
| 23 | - | case next, ok := <-s.keymaps: | |||
| 24 | - | if !ok { | |||
| 25 | - | s.keymaps = nil | |||
| 26 | - | continue | |||
| 27 | - | } | |||
| 28 | - | if next == nil { | |||
| 29 | - | continue | |||
| 30 | - | } | |||
| 31 | - | previous := s.injector.km | |||
| 32 | - | if s.injector.security != nil { | |||
| 33 | - | next.QuarantineFrom(previous) | |||
| 34 | - | } | |||
| 35 | - | s.injector.km = next | |||
| 36 | - | previous.Close() | |||
| 37 | - | default: | |||
| 38 | - | goto ready | |||
| 39 | - | } | |||
| 40 | - | } | |||
| 41 | - | ready: | |||
| 42 | - | i := s.injector | |||
| 43 | - | tx, err := i.km.Begin() | |||
| 44 | - | if err != nil { | |||
| 45 | - | return nil, nil, err | |||
| 46 | - | } | |||
| 47 | - | success := false | |||
| 48 | - | defer func() { | |||
| 49 | - | if !success { | |||
| 50 | - | tx.Rollback() | |||
| 51 | - | } | |||
| 52 | - | }() | |||
| 53 | - | var events []ports.InputEvent | |||
| 54 | - | // Snapshot an announcement before translating the first event, but don't | |||
| 55 | - | // deliver it or consume the connection's announcement on validation failure. | |||
| 56 | - | var device ports.InputEvent | |||
| 57 | - | if announce { | |||
| 58 | - | device = i.Device() | |||
| 59 | - | } | |||
| 60 | - | switch req.Kind { | |||
| 61 | - | case "key": | |||
| 62 | - | events, err = i.Key(req.Combo) | |||
| 63 | - | case "type": | |||
| 64 | - | events, err = i.Type(req.Text) | |||
| 65 | - | case "press": | |||
| 66 | - | events, err = i.Press(req.Combo) | |||
| 67 | - | case "release": | |||
| 68 | - | events, err = i.Release(req.Combo) | |||
| 69 | - | case "pointer": | |||
| 70 | - | events, err = i.Pointer(req.Cmd, req.Args) | |||
| 71 | - | case "swipe": | |||
| 72 | - | events, err = i.Swipe(req.Fingers, req.Dir) | |||
| 73 | - | default: | |||
| 74 | - | return nil, nil, errors.New("unknown injection kind") | |||
| 75 | - | } | |||
| 76 | - | if err != nil { | |||
| 77 | - | return nil, nil, err | |||
| 78 | - | } | |||
| 79 | - | if announce { | |||
| 80 | - | events = append([]ports.InputEvent{device}, events...) | |||
| 81 | - | } | |||
| 82 | - | success = true | |||
| 83 | - | return events, tx, nil | |||
| 84 | - | } | |||
D internal/adapters/control/inject_wire_test.go +0 -353
| @@ -1,353 +0,0 @@ | |||
| 1 | - | package control | |
| 2 | - | ||
| 3 | - | import ( | |
| 4 | - | "context" | |
| 5 | - | "encoding/json" | |
| 6 | - | "net" | |
| 7 | - | "path/filepath" | |
| 8 | - | "testing" | |
| 9 | - | "testing/synctest" | |
| 10 | - | "time" | |
| 11 | - | ||
| 12 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |
| 13 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |
| 14 | - | "github.com/bnema/neferwl/internal/domain" | |
| 15 | - | portsmocks "github.com/bnema/neferwl/internal/mocks/ports" | |
| 16 | - | "github.com/bnema/neferwl/internal/ports" | |
| 17 | - | ) | |
| 18 | - | ||
| 19 | - | //testpolicy:realtime real Unix control socket exchanges and shutdown | |
| 20 | - | func TestInjectProtocol(t *testing.T) { | |
| 21 | - | km := injectKeymap(t) | |
| 22 | - | security := portsmocks.NewMockSessionSecurity(t) | |
| 23 | - | state := domain.SecurityState{Generation: 7} | |
| 24 | - | security.EXPECT().Snapshot().Return(state) | |
| 25 | - | updates := make(chan *xkb.Keymap, 1) | |
| 26 | - | path := filepath.Join(t.TempDir(), "control.sock") | |
| 27 | - | s, err := Listen(path, workspaceid.WithPrefix("inject"), Options{Keymap: km, Keymaps: updates, Security: security}) | |
| 28 | - | if err != nil { | |
| 29 | - | t.Fatal(err) | |
| 30 | - | } | |
| 31 | - | defer s.Close() | |
| 32 | - | ctx, cancel := context.WithCancel(context.Background()) | |
| 33 | - | defer cancel() | |
| 34 | - | out := make(chan ports.ControlRequest, 1) | |
| 35 | - | done := make(chan error, 1) | |
| 36 | - | go func() { done <- s.Run(ctx, out) }() | |
| 37 | - | connect := func() net.Conn { | |
| 38 | - | t.Helper() | |
| 39 | - | c, err := net.Dial("unix", path) | |
| 40 | - | if err != nil { | |
| 41 | - | t.Fatal(err) | |
| 42 | - | } | |
| 43 | - | t.Cleanup(func() { c.Close() }) | |
| 44 | - | if err := c.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { | |
| 45 | - | t.Fatal(err) | |
| 46 | - | } | |
| 47 | - | return c | |
| 48 | - | } | |
| 49 | - | conn := connect() | |
| 50 | - | enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) | |
| 51 | - | for _, req := range []map[string]any{ | |
| 52 | - | {"kind": "key", "combo": "bad-key"}, {"kind": "unknown"}, {"kind": "key", "combo": "a", "wait": "bad"}, {"kind": "swipe", "fingers": 3, "dir": "bad"}, | |
| 53 | - | } { | |
| 54 | - | req["id"], req["op"] = 1, "inject" | |
| 55 | - | if err := enc.Encode(req); err != nil { | |
| 56 | - | t.Fatal(err) | |
| 57 | - | } | |
| 58 | - | var response reply | |
| 59 | - | if err := dec.Decode(&response); err != nil || response.Error != ports.ControlErrBadRequest { | |
| 60 | - | t.Fatal(response, err) | |
| 61 | - | } | |
| 62 | - | } | |
| 63 | - | exchange := func(conn net.Conn, req map[string]any, announcement bool) []ports.InputEvent { | |
| 64 | - | t.Helper() | |
| 65 | - | req["id"], req["op"] = 2, "inject" | |
| 66 | - | if err := json.NewEncoder(conn).Encode(req); err != nil { | |
| 67 | - | t.Fatal(err) | |
| 68 | - | } | |
| 69 | - | var message ports.ControlInject | |
| 70 | - | select { | |
| 71 | - | case raw := <-out: | |
| 72 | - | var ok bool | |
| 73 | - | message, ok = raw.(ports.ControlInject) | |
| 74 | - | if !ok { | |
| 75 | - | t.Fatalf("request %T", raw) | |
| 76 | - | } | |
| 77 | - | case <-time.After(5 * time.Second): | |
| 78 | - | t.Fatal("missing injection") | |
| 79 | - | } | |
| 80 | - | if message.Caps != domain.CapsAll || cap(message.Reply) != 1 { | |
| 81 | - | t.Fatal(message) | |
| 82 | - | } | |
| 83 | - | events := message.Events | |
| 84 | - | for _, raw := range events { | |
| 85 | - | if ev, ok := raw.(ports.SecurityInput); !ok || ev.State != state { | |
| 86 | - | t.Fatal(raw) | |
| 87 | - | } | |
| 88 | - | } | |
| 89 | - | if announcement { | |
| 90 | - | if ev := events[0].(ports.SecurityInput).Event; ev != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |
| 91 | - | t.Fatal(ev) | |
| 92 | - | } | |
| 93 | - | events = events[1:] | |
| 94 | - | } else { | |
| 95 | - | if _, ok := events[0].(ports.SecurityInput).Event.(ports.InputDeviceAdded); ok { | |
| 96 | - | t.Fatal("duplicate announcement") | |
| 97 | - | } | |
| 98 | - | } | |
| 99 | - | if req["wait"] != nil { | |
| 100 | - | if message.Wait != domain.WaitPresented || message.Until == nil || message.Until.AppID != "foot" || message.Timeout != 2*time.Second { | |
| 101 | - | t.Fatal(message) | |
| 102 | - | } | |
| 103 | - | } else if message.Wait != domain.DefaultWait || message.Until != nil || message.Timeout != 10*time.Second { | |
| 104 | - | t.Fatal(message) | |
| 105 | - | } | |
| 106 | - | message.Admission <- ports.ControlAdmission{} | |
| 107 | - | message.Reply <- ports.ControlReply{Done: domain.WaitCommitted} | |
| 108 | - | var response reply | |
| 109 | - | if err := json.NewDecoder(conn).Decode(&response); err != nil || !response.OK { | |
| 110 | - | t.Fatal(response, err) | |
| 111 | - | } | |
| 112 | - | return events | |
| 113 | - | } | |
| 114 | - | events := exchange(conn, map[string]any{"kind": "press", "combo": "Super", "wait": "presented", "until": "focused app_id=foot", "timeout": "2s"}, true) | |
| 115 | - | if len(events) != 1 || !events[0].(ports.SecurityInput).Event.(ports.KeyEvent).Pressed { | |
| 116 | - | t.Fatal(events) | |
| 117 | - | } | |
| 118 | - | // A newly received map takes over held-key tracking, quarantining release. | |
| 119 | - | next := injectKeymap(t) | |
| 120 | - | updates <- next | |
| 121 | - | events = exchange(conn, map[string]any{"kind": "key", "combo": "q"}, false) | |
| 122 | - | for _, raw := range events { | |
| 123 | - | if ev := raw.(ports.SecurityInput).Event.(ports.KeyEvent); ev.Mods&domain.ModSuper != 0 { | |
| 124 | - | t.Fatal(ev) | |
| 125 | - | } | |
| 126 | - | } | |
| 127 | - | // Other kinds share the same request port and first-inject bookkeeping. | |
| 128 | - | for _, req := range []map[string]any{ | |
| 129 | - | {"kind": "type", "text": "Hi!"}, {"kind": "pointer", "cmd": "click"}, {"kind": "swipe", "fingers": 4, "dir": "up"}, {"kind": "release", "combo": "a"}, | |
| 130 | - | } { | |
| 131 | - | exchange(conn, req, false) | |
| 132 | - | } | |
| 133 | - | other := connect() | |
| 134 | - | exchange(other, map[string]any{"kind": "key", "combo": "Return"}, true) | |
| 135 | - | // Both clients remain open: shutdown must interrupt their blocked scanners. | |
| 136 | - | cancel() | |
| 137 | - | select { | |
| 138 | - | case err := <-done: | |
| 139 | - | if err != nil { | |
| 140 | - | t.Fatal(err) | |
| 141 | - | } | |
| 142 | - | case <-time.After(5 * time.Second): | |
| 143 | - | t.Fatal("open-client shutdown hung") | |
| 144 | - | } | |
| 145 | - | } | |
| 146 | - | ||
| 147 | - | // The device announcement repeats until core accepts a batch: a refused | |
| 148 | - | // (locked) batch never reached the input path. | |
| 149 | - | func TestInjectAnnouncesUntilAccepted(t *testing.T) { | |
| 150 | - | synctest.Test(t, func(t *testing.T) { | |
| 151 | - | s := &Server{ids: workspaceid.WithPrefix("inject"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |
| 152 | - | out := make(chan ports.ControlRequest) | |
| 153 | - | announced := false | |
| 154 | - | for _, refuse := range []string{ports.ControlErrLocked, "", ""} { | |
| 155 | - | go func() { | |
| 156 | - | r := (<-out).(ports.ControlInject) | |
| 157 | - | _, first := r.Events[0].(ports.InputDeviceAdded) | |
| 158 | - | if first == announced { | |
| 159 | - | t.Errorf("announcement sent=%v after announced=%v", first, announced) | |
| 160 | - | } | |
| 161 | - | r.Admission <- ports.ControlAdmission{Err: refuse} | |
| 162 | - | r.Reply <- ports.ControlReply{Err: refuse} | |
| 163 | - | }() | |
| 164 | - | s.dispatch(context.Background(), request{Op: "inject", Kind: "key", Combo: "a"}, out, &announced) | |
| 165 | - | synctest.Wait() | |
| 166 | - | if announced != (refuse == "") { | |
| 167 | - | t.Fatalf("announced=%v after %q", announced, refuse) | |
| 168 | - | } | |
| 169 | - | } | |
| 170 | - | }) | |
| 171 | - | } | |
| 172 | - | ||
| 173 | - | func TestInjectionAdmissionOrderingAndReload(t *testing.T) { | |
| 174 | - | synctest.Test(t, func(t *testing.T) { | |
| 175 | - | updates := make(chan *xkb.Keymap, 1) | |
| 176 | - | s := &Server{ids: workspaceid.WithPrefix("order"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil), keymaps: updates} | |
| 177 | - | out := make(chan ports.ControlRequest, 2) | |
| 178 | - | firstDone, secondDone := make(chan reply, 1), make(chan reply, 1) | |
| 179 | - | go func() { | |
| 180 | - | announced := false | |
| 181 | - | firstDone <- s.dispatch(t.Context(), request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced) | |
| 182 | - | }() | |
| 183 | - | synctest.Wait() | |
| 184 | - | first := (<-out).(ports.ControlInject) | |
| 185 | - | next := injectKeymap(t) | |
| 186 | - | updates <- next | |
| 187 | - | if s.injectMu.TryLock() { | |
| 188 | - | s.injectMu.Unlock() | |
| 189 | - | t.Fatal("admission serialization released early") | |
| 190 | - | } | |
| 191 | - | go func() { | |
| 192 | - | announced := false | |
| 193 | - | secondDone <- s.dispatch(t.Context(), request{Op: "inject", Kind: "key", Combo: "q"}, out, &announced) | |
| 194 | - | }() | |
| 195 | - | if len(out) != 0 || len(updates) != 1 { | |
| 196 | - | t.Fatal("second connection translated/reloaded before admission") | |
| 197 | - | } | |
| 198 | - | first.Admission <- ports.ControlAdmission{Err: ports.ControlErrBusy} | |
| 199 | - | synctest.Wait() | |
| 200 | - | second := (<-out).(ports.ControlInject) | |
| 201 | - | for _, ev := range second.Events { | |
| 202 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Mods&domain.ModSuper != 0 { | |
| 203 | - | t.Fatal("refused Super leaked into q", key) | |
| 204 | - | } | |
| 205 | - | } | |
| 206 | - | // The second request passed admission serialization while first completion | |
| 207 | - | // is still pending; replacing the map happened only after rollback. | |
| 208 | - | if len(updates) != 0 { | |
| 209 | - | t.Fatal("reload not consumed") | |
| 210 | - | } | |
| 211 | - | second.Admission <- ports.ControlAdmission{} | |
| 212 | - | second.Reply <- ports.ControlReply{} | |
| 213 | - | first.Reply <- ports.ControlReply{Err: ports.ControlErrBusy} | |
| 214 | - | if r := <-firstDone; r.Error != ports.ControlErrBusy { | |
| 215 | - | t.Fatal(r) | |
| 216 | - | } | |
| 217 | - | if r := <-secondDone; !r.OK { | |
| 218 | - | t.Fatal(r) | |
| 219 | - | } | |
| 220 | - | }) | |
| 221 | - | } | |
| 222 | - | ||
| 223 | - | func TestInjectionRefusedSuperRollback(t *testing.T) { | |
| 224 | - | synctest.Test(t, func(t *testing.T) { | |
| 225 | - | s := &Server{ids: workspaceid.WithPrefix("busy"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |
| 226 | - | out := make(chan ports.ControlRequest) | |
| 227 | - | announced := false | |
| 228 | - | go func() { | |
| 229 | - | r := (<-out).(ports.ControlInject) | |
| 230 | - | r.Admission <- ports.ControlAdmission{Err: ports.ControlErrBusy} | |
| 231 | - | r.Reply <- ports.ControlReply{Err: ports.ControlErrBusy} | |
| 232 | - | }() | |
| 233 | - | if r := s.dispatch(t.Context(), request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced); r.Error != ports.ControlErrBusy { | |
| 234 | - | t.Fatal(r) | |
| 235 | - | } | |
| 236 | - | go func() { | |
| 237 | - | r := (<-out).(ports.ControlInject) | |
| 238 | - | for _, ev := range r.Events { | |
| 239 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Mods&domain.ModSuper != 0 { | |
| 240 | - | t.Error("q would trigger Super+q", key) | |
| 241 | - | } | |
| 242 | - | } | |
| 243 | - | r.Admission <- ports.ControlAdmission{} | |
| 244 | - | r.Reply <- ports.ControlReply{} | |
| 245 | - | }() | |
| 246 | - | if r := s.dispatch(t.Context(), request{Op: "inject", Kind: "key", Combo: "q"}, out, &announced); !r.OK { | |
| 247 | - | t.Fatal(r) | |
| 248 | - | } | |
| 249 | - | }) | |
| 250 | - | } | |
| 251 | - | ||
| 252 | - | func TestInjectionCancellationRollsBack(t *testing.T) { | |
| 253 | - | for _, sent := range []bool{false, true} { | |
| 254 | - | synctest.Test(t, func(t *testing.T) { | |
| 255 | - | s := &Server{ids: workspaceid.WithPrefix("cancel"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |
| 256 | - | out := make(chan ports.ControlRequest) | |
| 257 | - | ctx, cancel := context.WithCancel(t.Context()) | |
| 258 | - | done := make(chan struct{}) | |
| 259 | - | go func() { | |
| 260 | - | defer close(done) | |
| 261 | - | announced := false | |
| 262 | - | s.dispatch(ctx, request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced) | |
| 263 | - | }() | |
| 264 | - | if sent { | |
| 265 | - | <-out | |
| 266 | - | } | |
| 267 | - | synctest.Wait() | |
| 268 | - | cancel() | |
| 269 | - | <-done | |
| 270 | - | s.injectMu.Lock() | |
| 271 | - | if ev := s.injector.km.Key(16, true, 0); ev.Mods&domain.ModSuper != 0 { | |
| 272 | - | t.Fatal("cancelled translation leaked", ev) | |
| 273 | - | } | |
| 274 | - | s.injectMu.Unlock() | |
| 275 | - | }) | |
| 276 | - | } | |
| 277 | - | } | |
| 278 | - | ||
| 279 | - | //testpolicy:realtime Two real socket clients verify admission ordering independently of completion. | |
| 280 | - | func TestTwoConnectionsShareAdmittedModifiers(t *testing.T) { | |
| 281 | - | path := filepath.Join(t.TempDir(), "control.sock") | |
| 282 | - | s, err := Listen(path, workspaceid.WithPrefix("order"), Options{Keymap: injectKeymap(t)}) | |
| 283 | - | if err != nil { | |
| 284 | - | t.Fatal(err) | |
| 285 | - | } | |
| 286 | - | defer s.Close() | |
| 287 | - | ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 288 | - | defer cancel() | |
| 289 | - | out := make(chan ports.ControlRequest) | |
| 290 | - | done := make(chan error, 1) | |
| 291 | - | go func() { done <- s.Run(ctx, out) }() | |
| 292 | - | connect := func() net.Conn { | |
| 293 | - | t.Helper() | |
| 294 | - | conn, err := net.Dial("unix", path) | |
| 295 | - | if err != nil { | |
| 296 | - | t.Fatal(err) | |
| 297 | - | } | |
| 298 | - | t.Cleanup(func() { conn.Close() }) | |
| 299 | - | if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { | |
| 300 | - | t.Fatal(err) | |
| 301 | - | } | |
| 302 | - | return conn | |
| 303 | - | } | |
| 304 | - | first, second := connect(), connect() | |
| 305 | - | if err := json.NewEncoder(first).Encode(request{Op: "inject", Kind: "press", Combo: "Super"}); err != nil { | |
| 306 | - | t.Fatal(err) | |
| 307 | - | } | |
| 308 | - | receive := func() ports.ControlInject { | |
| 309 | - | t.Helper() | |
| 310 | - | select { | |
| 311 | - | case r := <-out: | |
| 312 | - | return r.(ports.ControlInject) | |
| 313 | - | case <-ctx.Done(): | |
| 314 | - | t.Fatal(ctx.Err()) | |
| 315 | - | return ports.ControlInject{} | |
| 316 | - | } | |
| 317 | - | } | |
| 318 | - | a := receive() | |
| 319 | - | if err := json.NewEncoder(second).Encode(request{Op: "inject", Kind: "key", Combo: "q"}); err != nil { | |
| 320 | - | t.Fatal(err) | |
| 321 | - | } | |
| 322 | - | if s.injectMu.TryLock() { | |
| 323 | - | s.injectMu.Unlock() | |
| 324 | - | t.Fatal("serialization released before admission") | |
| 325 | - | } | |
| 326 | - | a.Admission <- ports.ControlAdmission{} | |
| 327 | - | b := receive() // Must arrive without completing a. | |
| 328 | - | found := false | |
| 329 | - | for _, ev := range b.Events { | |
| 330 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Keysym == "q" && key.Pressed { | |
| 331 | - | found = true | |
| 332 | - | if key.Mods&domain.ModSuper == 0 { | |
| 333 | - | t.Fatal("second client lost admitted Super") | |
| 334 | - | } | |
| 335 | - | } | |
| 336 | - | } | |
| 337 | - | if !found { | |
| 338 | - | t.Fatal("missing q") | |
| 339 | - | } | |
| 340 | - | b.Admission <- ports.ControlAdmission{} | |
| 341 | - | b.Reply <- ports.ControlReply{} | |
| 342 | - | a.Reply <- ports.ControlReply{} | |
| 343 | - | for _, conn := range []net.Conn{first, second} { | |
| 344 | - | var r reply | |
| 345 | - | if err := json.NewDecoder(conn).Decode(&r); err != nil || !r.OK { | |
| 346 | - | t.Fatal(r, err) | |
| 347 | - | } | |
| 348 | - | } | |
| 349 | - | cancel() | |
| 350 | - | if err := <-done; err != nil { | |
| 351 | - | t.Fatal(err) | |
| 352 | - | } | |
| 353 | - | } | |
| @@ -1,353 +0,0 @@ | |||||
| 1 | - | package control | |||
| 2 | - | ||||
| 3 | - | import ( | |||
| 4 | - | "context" | |||
| 5 | - | "encoding/json" | |||
| 6 | - | "net" | |||
| 7 | - | "path/filepath" | |||
| 8 | - | "testing" | |||
| 9 | - | "testing/synctest" | |||
| 10 | - | "time" | |||
| 11 | - | ||||
| 12 | - | "github.com/bnema/neferwl/internal/adapters/workspaceid" | |||
| 13 | - | "github.com/bnema/neferwl/internal/adapters/xkb" | |||
| 14 | - | "github.com/bnema/neferwl/internal/domain" | |||
| 15 | - | portsmocks "github.com/bnema/neferwl/internal/mocks/ports" | |||
| 16 | - | "github.com/bnema/neferwl/internal/ports" | |||
| 17 | - | ) | |||
| 18 | - | ||||
| 19 | - | //testpolicy:realtime real Unix control socket exchanges and shutdown | |||
| 20 | - | func TestInjectProtocol(t *testing.T) { | |||
| 21 | - | km := injectKeymap(t) | |||
| 22 | - | security := portsmocks.NewMockSessionSecurity(t) | |||
| 23 | - | state := domain.SecurityState{Generation: 7} | |||
| 24 | - | security.EXPECT().Snapshot().Return(state) | |||
| 25 | - | updates := make(chan *xkb.Keymap, 1) | |||
| 26 | - | path := filepath.Join(t.TempDir(), "control.sock") | |||
| 27 | - | s, err := Listen(path, workspaceid.WithPrefix("inject"), Options{Keymap: km, Keymaps: updates, Security: security}) | |||
| 28 | - | if err != nil { | |||
| 29 | - | t.Fatal(err) | |||
| 30 | - | } | |||
| 31 | - | defer s.Close() | |||
| 32 | - | ctx, cancel := context.WithCancel(context.Background()) | |||
| 33 | - | defer cancel() | |||
| 34 | - | out := make(chan ports.ControlRequest, 1) | |||
| 35 | - | done := make(chan error, 1) | |||
| 36 | - | go func() { done <- s.Run(ctx, out) }() | |||
| 37 | - | connect := func() net.Conn { | |||
| 38 | - | t.Helper() | |||
| 39 | - | c, err := net.Dial("unix", path) | |||
| 40 | - | if err != nil { | |||
| 41 | - | t.Fatal(err) | |||
| 42 | - | } | |||
| 43 | - | t.Cleanup(func() { c.Close() }) | |||
| 44 | - | if err := c.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { | |||
| 45 | - | t.Fatal(err) | |||
| 46 | - | } | |||
| 47 | - | return c | |||
| 48 | - | } | |||
| 49 | - | conn := connect() | |||
| 50 | - | enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) | |||
| 51 | - | for _, req := range []map[string]any{ | |||
| 52 | - | {"kind": "key", "combo": "bad-key"}, {"kind": "unknown"}, {"kind": "key", "combo": "a", "wait": "bad"}, {"kind": "swipe", "fingers": 3, "dir": "bad"}, | |||
| 53 | - | } { | |||
| 54 | - | req["id"], req["op"] = 1, "inject" | |||
| 55 | - | if err := enc.Encode(req); err != nil { | |||
| 56 | - | t.Fatal(err) | |||
| 57 | - | } | |||
| 58 | - | var response reply | |||
| 59 | - | if err := dec.Decode(&response); err != nil || response.Error != ports.ControlErrBadRequest { | |||
| 60 | - | t.Fatal(response, err) | |||
| 61 | - | } | |||
| 62 | - | } | |||
| 63 | - | exchange := func(conn net.Conn, req map[string]any, announcement bool) []ports.InputEvent { | |||
| 64 | - | t.Helper() | |||
| 65 | - | req["id"], req["op"] = 2, "inject" | |||
| 66 | - | if err := json.NewEncoder(conn).Encode(req); err != nil { | |||
| 67 | - | t.Fatal(err) | |||
| 68 | - | } | |||
| 69 | - | var message ports.ControlInject | |||
| 70 | - | select { | |||
| 71 | - | case raw := <-out: | |||
| 72 | - | var ok bool | |||
| 73 | - | message, ok = raw.(ports.ControlInject) | |||
| 74 | - | if !ok { | |||
| 75 | - | t.Fatalf("request %T", raw) | |||
| 76 | - | } | |||
| 77 | - | case <-time.After(5 * time.Second): | |||
| 78 | - | t.Fatal("missing injection") | |||
| 79 | - | } | |||
| 80 | - | if message.Caps != domain.CapsAll || cap(message.Reply) != 1 { | |||
| 81 | - | t.Fatal(message) | |||
| 82 | - | } | |||
| 83 | - | events := message.Events | |||
| 84 | - | for _, raw := range events { | |||
| 85 | - | if ev, ok := raw.(ports.SecurityInput); !ok || ev.State != state { | |||
| 86 | - | t.Fatal(raw) | |||
| 87 | - | } | |||
| 88 | - | } | |||
| 89 | - | if announcement { | |||
| 90 | - | if ev := events[0].(ports.SecurityInput).Event; ev != (ports.InputDeviceAdded{ID: controlDeviceID, Name: "control"}) { | |||
| 91 | - | t.Fatal(ev) | |||
| 92 | - | } | |||
| 93 | - | events = events[1:] | |||
| 94 | - | } else { | |||
| 95 | - | if _, ok := events[0].(ports.SecurityInput).Event.(ports.InputDeviceAdded); ok { | |||
| 96 | - | t.Fatal("duplicate announcement") | |||
| 97 | - | } | |||
| 98 | - | } | |||
| 99 | - | if req["wait"] != nil { | |||
| 100 | - | if message.Wait != domain.WaitPresented || message.Until == nil || message.Until.AppID != "foot" || message.Timeout != 2*time.Second { | |||
| 101 | - | t.Fatal(message) | |||
| 102 | - | } | |||
| 103 | - | } else if message.Wait != domain.DefaultWait || message.Until != nil || message.Timeout != 10*time.Second { | |||
| 104 | - | t.Fatal(message) | |||
| 105 | - | } | |||
| 106 | - | message.Admission <- ports.ControlAdmission{} | |||
| 107 | - | message.Reply <- ports.ControlReply{Done: domain.WaitCommitted} | |||
| 108 | - | var response reply | |||
| 109 | - | if err := json.NewDecoder(conn).Decode(&response); err != nil || !response.OK { | |||
| 110 | - | t.Fatal(response, err) | |||
| 111 | - | } | |||
| 112 | - | return events | |||
| 113 | - | } | |||
| 114 | - | events := exchange(conn, map[string]any{"kind": "press", "combo": "Super", "wait": "presented", "until": "focused app_id=foot", "timeout": "2s"}, true) | |||
| 115 | - | if len(events) != 1 || !events[0].(ports.SecurityInput).Event.(ports.KeyEvent).Pressed { | |||
| 116 | - | t.Fatal(events) | |||
| 117 | - | } | |||
| 118 | - | // A newly received map takes over held-key tracking, quarantining release. | |||
| 119 | - | next := injectKeymap(t) | |||
| 120 | - | updates <- next | |||
| 121 | - | events = exchange(conn, map[string]any{"kind": "key", "combo": "q"}, false) | |||
| 122 | - | for _, raw := range events { | |||
| 123 | - | if ev := raw.(ports.SecurityInput).Event.(ports.KeyEvent); ev.Mods&domain.ModSuper != 0 { | |||
| 124 | - | t.Fatal(ev) | |||
| 125 | - | } | |||
| 126 | - | } | |||
| 127 | - | // Other kinds share the same request port and first-inject bookkeeping. | |||
| 128 | - | for _, req := range []map[string]any{ | |||
| 129 | - | {"kind": "type", "text": "Hi!"}, {"kind": "pointer", "cmd": "click"}, {"kind": "swipe", "fingers": 4, "dir": "up"}, {"kind": "release", "combo": "a"}, | |||
| 130 | - | } { | |||
| 131 | - | exchange(conn, req, false) | |||
| 132 | - | } | |||
| 133 | - | other := connect() | |||
| 134 | - | exchange(other, map[string]any{"kind": "key", "combo": "Return"}, true) | |||
| 135 | - | // Both clients remain open: shutdown must interrupt their blocked scanners. | |||
| 136 | - | cancel() | |||
| 137 | - | select { | |||
| 138 | - | case err := <-done: | |||
| 139 | - | if err != nil { | |||
| 140 | - | t.Fatal(err) | |||
| 141 | - | } | |||
| 142 | - | case <-time.After(5 * time.Second): | |||
| 143 | - | t.Fatal("open-client shutdown hung") | |||
| 144 | - | } | |||
| 145 | - | } | |||
| 146 | - | ||||
| 147 | - | // The device announcement repeats until core accepts a batch: a refused | |||
| 148 | - | // (locked) batch never reached the input path. | |||
| 149 | - | func TestInjectAnnouncesUntilAccepted(t *testing.T) { | |||
| 150 | - | synctest.Test(t, func(t *testing.T) { | |||
| 151 | - | s := &Server{ids: workspaceid.WithPrefix("inject"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |||
| 152 | - | out := make(chan ports.ControlRequest) | |||
| 153 | - | announced := false | |||
| 154 | - | for _, refuse := range []string{ports.ControlErrLocked, "", ""} { | |||
| 155 | - | go func() { | |||
| 156 | - | r := (<-out).(ports.ControlInject) | |||
| 157 | - | _, first := r.Events[0].(ports.InputDeviceAdded) | |||
| 158 | - | if first == announced { | |||
| 159 | - | t.Errorf("announcement sent=%v after announced=%v", first, announced) | |||
| 160 | - | } | |||
| 161 | - | r.Admission <- ports.ControlAdmission{Err: refuse} | |||
| 162 | - | r.Reply <- ports.ControlReply{Err: refuse} | |||
| 163 | - | }() | |||
| 164 | - | s.dispatch(context.Background(), request{Op: "inject", Kind: "key", Combo: "a"}, out, &announced) | |||
| 165 | - | synctest.Wait() | |||
| 166 | - | if announced != (refuse == "") { | |||
| 167 | - | t.Fatalf("announced=%v after %q", announced, refuse) | |||
| 168 | - | } | |||
| 169 | - | } | |||
| 170 | - | }) | |||
| 171 | - | } | |||
| 172 | - | ||||
| 173 | - | func TestInjectionAdmissionOrderingAndReload(t *testing.T) { | |||
| 174 | - | synctest.Test(t, func(t *testing.T) { | |||
| 175 | - | updates := make(chan *xkb.Keymap, 1) | |||
| 176 | - | s := &Server{ids: workspaceid.WithPrefix("order"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil), keymaps: updates} | |||
| 177 | - | out := make(chan ports.ControlRequest, 2) | |||
| 178 | - | firstDone, secondDone := make(chan reply, 1), make(chan reply, 1) | |||
| 179 | - | go func() { | |||
| 180 | - | announced := false | |||
| 181 | - | firstDone <- s.dispatch(t.Context(), request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced) | |||
| 182 | - | }() | |||
| 183 | - | synctest.Wait() | |||
| 184 | - | first := (<-out).(ports.ControlInject) | |||
| 185 | - | next := injectKeymap(t) | |||
| 186 | - | updates <- next | |||
| 187 | - | if s.injectMu.TryLock() { | |||
| 188 | - | s.injectMu.Unlock() | |||
| 189 | - | t.Fatal("admission serialization released early") | |||
| 190 | - | } | |||
| 191 | - | go func() { | |||
| 192 | - | announced := false | |||
| 193 | - | secondDone <- s.dispatch(t.Context(), request{Op: "inject", Kind: "key", Combo: "q"}, out, &announced) | |||
| 194 | - | }() | |||
| 195 | - | if len(out) != 0 || len(updates) != 1 { | |||
| 196 | - | t.Fatal("second connection translated/reloaded before admission") | |||
| 197 | - | } | |||
| 198 | - | first.Admission <- ports.ControlAdmission{Err: ports.ControlErrBusy} | |||
| 199 | - | synctest.Wait() | |||
| 200 | - | second := (<-out).(ports.ControlInject) | |||
| 201 | - | for _, ev := range second.Events { | |||
| 202 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Mods&domain.ModSuper != 0 { | |||
| 203 | - | t.Fatal("refused Super leaked into q", key) | |||
| 204 | - | } | |||
| 205 | - | } | |||
| 206 | - | // The second request passed admission serialization while first completion | |||
| 207 | - | // is still pending; replacing the map happened only after rollback. | |||
| 208 | - | if len(updates) != 0 { | |||
| 209 | - | t.Fatal("reload not consumed") | |||
| 210 | - | } | |||
| 211 | - | second.Admission <- ports.ControlAdmission{} | |||
| 212 | - | second.Reply <- ports.ControlReply{} | |||
| 213 | - | first.Reply <- ports.ControlReply{Err: ports.ControlErrBusy} | |||
| 214 | - | if r := <-firstDone; r.Error != ports.ControlErrBusy { | |||
| 215 | - | t.Fatal(r) | |||
| 216 | - | } | |||
| 217 | - | if r := <-secondDone; !r.OK { | |||
| 218 | - | t.Fatal(r) | |||
| 219 | - | } | |||
| 220 | - | }) | |||
| 221 | - | } | |||
| 222 | - | ||||
| 223 | - | func TestInjectionRefusedSuperRollback(t *testing.T) { | |||
| 224 | - | synctest.Test(t, func(t *testing.T) { | |||
| 225 | - | s := &Server{ids: workspaceid.WithPrefix("busy"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |||
| 226 | - | out := make(chan ports.ControlRequest) | |||
| 227 | - | announced := false | |||
| 228 | - | go func() { | |||
| 229 | - | r := (<-out).(ports.ControlInject) | |||
| 230 | - | r.Admission <- ports.ControlAdmission{Err: ports.ControlErrBusy} | |||
| 231 | - | r.Reply <- ports.ControlReply{Err: ports.ControlErrBusy} | |||
| 232 | - | }() | |||
| 233 | - | if r := s.dispatch(t.Context(), request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced); r.Error != ports.ControlErrBusy { | |||
| 234 | - | t.Fatal(r) | |||
| 235 | - | } | |||
| 236 | - | go func() { | |||
| 237 | - | r := (<-out).(ports.ControlInject) | |||
| 238 | - | for _, ev := range r.Events { | |||
| 239 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Mods&domain.ModSuper != 0 { | |||
| 240 | - | t.Error("q would trigger Super+q", key) | |||
| 241 | - | } | |||
| 242 | - | } | |||
| 243 | - | r.Admission <- ports.ControlAdmission{} | |||
| 244 | - | r.Reply <- ports.ControlReply{} | |||
| 245 | - | }() | |||
| 246 | - | if r := s.dispatch(t.Context(), request{Op: "inject", Kind: "key", Combo: "q"}, out, &announced); !r.OK { | |||
| 247 | - | t.Fatal(r) | |||
| 248 | - | } | |||
| 249 | - | }) | |||
| 250 | - | } | |||
| 251 | - | ||||
| 252 | - | func TestInjectionCancellationRollsBack(t *testing.T) { | |||
| 253 | - | for _, sent := range []bool{false, true} { | |||
| 254 | - | synctest.Test(t, func(t *testing.T) { | |||
| 255 | - | s := &Server{ids: workspaceid.WithPrefix("cancel"), done: make(chan struct{}), injector: newInjector(injectKeymap(t), nil)} | |||
| 256 | - | out := make(chan ports.ControlRequest) | |||
| 257 | - | ctx, cancel := context.WithCancel(t.Context()) | |||
| 258 | - | done := make(chan struct{}) | |||
| 259 | - | go func() { | |||
| 260 | - | defer close(done) | |||
| 261 | - | announced := false | |||
| 262 | - | s.dispatch(ctx, request{Op: "inject", Kind: "press", Combo: "Super"}, out, &announced) | |||
| 263 | - | }() | |||
| 264 | - | if sent { | |||
| 265 | - | <-out | |||
| 266 | - | } | |||
| 267 | - | synctest.Wait() | |||
| 268 | - | cancel() | |||
| 269 | - | <-done | |||
| 270 | - | s.injectMu.Lock() | |||
| 271 | - | if ev := s.injector.km.Key(16, true, 0); ev.Mods&domain.ModSuper != 0 { | |||
| 272 | - | t.Fatal("cancelled translation leaked", ev) | |||
| 273 | - | } | |||
| 274 | - | s.injectMu.Unlock() | |||
| 275 | - | }) | |||
| 276 | - | } | |||
| 277 | - | } | |||
| 278 | - | ||||
| 279 | - | //testpolicy:realtime Two real socket clients verify admission ordering independently of completion. | |||
| 280 | - | func TestTwoConnectionsShareAdmittedModifiers(t *testing.T) { | |||
| 281 | - | path := filepath.Join(t.TempDir(), "control.sock") | |||
| 282 | - | s, err := Listen(path, workspaceid.WithPrefix("order"), Options{Keymap: injectKeymap(t)}) | |||
| 283 | - | if err != nil { | |||
| 284 | - | t.Fatal(err) | |||
| 285 | - | } | |||
| 286 | - | defer s.Close() | |||
| 287 | - | ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |||
| 288 | - | defer cancel() | |||
| 289 | - | out := make(chan ports.ControlRequest) | |||
| 290 | - | done := make(chan error, 1) | |||
| 291 | - | go func() { done <- s.Run(ctx, out) }() | |||
| 292 | - | connect := func() net.Conn { | |||
| 293 | - | t.Helper() | |||
| 294 | - | conn, err := net.Dial("unix", path) | |||
| 295 | - | if err != nil { | |||
| 296 | - | t.Fatal(err) | |||
| 297 | - | } | |||
| 298 | - | t.Cleanup(func() { conn.Close() }) | |||
| 299 | - | if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { | |||
| 300 | - | t.Fatal(err) | |||
| 301 | - | } | |||
| 302 | - | return conn | |||
| 303 | - | } | |||
| 304 | - | first, second := connect(), connect() | |||
| 305 | - | if err := json.NewEncoder(first).Encode(request{Op: "inject", Kind: "press", Combo: "Super"}); err != nil { | |||
| 306 | - | t.Fatal(err) | |||
| 307 | - | } | |||
| 308 | - | receive := func() ports.ControlInject { | |||
| 309 | - | t.Helper() | |||
| 310 | - | select { | |||
| 311 | - | case r := <-out: | |||
| 312 | - | return r.(ports.ControlInject) | |||
| 313 | - | case <-ctx.Done(): | |||
| 314 | - | t.Fatal(ctx.Err()) | |||
| 315 | - | return ports.ControlInject{} | |||
| 316 | - | } | |||
| 317 | - | } | |||
| 318 | - | a := receive() | |||
| 319 | - | if err := json.NewEncoder(second).Encode(request{Op: "inject", Kind: "key", Combo: "q"}); err != nil { | |||
| 320 | - | t.Fatal(err) | |||
| 321 | - | } | |||
| 322 | - | if s.injectMu.TryLock() { | |||
| 323 | - | s.injectMu.Unlock() | |||
| 324 | - | t.Fatal("serialization released before admission") | |||
| 325 | - | } | |||
| 326 | - | a.Admission <- ports.ControlAdmission{} | |||
| 327 | - | b := receive() // Must arrive without completing a. | |||
| 328 | - | found := false | |||
| 329 | - | for _, ev := range b.Events { | |||
| 330 | - | if key, ok := ev.(ports.KeyEvent); ok && key.Keysym == "q" && key.Pressed { | |||
| 331 | - | found = true | |||
| 332 | - | if key.Mods&domain.ModSuper == 0 { | |||
| 333 | - | t.Fatal("second client lost admitted Super") | |||
| 334 | - | } | |||
| 335 | - | } | |||
| 336 | - | } | |||
| 337 | - | if !found { | |||
| 338 | - | t.Fatal("missing q") | |||
| 339 | - | } | |||
| 340 | - | b.Admission <- ports.ControlAdmission{} | |||
| 341 | - | b.Reply <- ports.ControlReply{} | |||
| 342 | - | a.Reply <- ports.ControlReply{} | |||
| 343 | - | for _, conn := range []net.Conn{first, second} { | |||
| 344 | - | var r reply | |||
| 345 | - | if err := json.NewDecoder(conn).Decode(&r); err != nil || !r.OK { | |||
| 346 | - | t.Fatal(r, err) | |||
| 347 | - | } | |||
| 348 | - | } | |||
| 349 | - | cancel() | |||
| 350 | - | if err := <-done; err != nil { | |||
| 351 | - | t.Fatal(err) | |||
| 352 | - | } | |||
| 353 | - | } | |||
D internal/adapters/control/output_test.go +0 -38
D internal/adapters/control/shot.go +0 -165
D internal/adapters/control/shot_test.go +0 -104
D internal/adapters/control/shot_wire_test.go +0 -119
D internal/adapters/control/wire_diff.go +0 -23
D internal/adapters/control/wire_diff_test.go +0 -26
M internal/adapters/drm/frame_lifecycle.go +0 -1
M internal/adapters/drm/frame_submit.go +2 -2
M internal/adapters/drm/frames_test.go +5 -5
M internal/adapters/drm/output.go +2 -4
M internal/adapters/drm/supervisor/recovery.go +2 -2
D internal/adapters/drm/supervisor/renderdevice_test.go +0 -46
M internal/adapters/drm/supervisor/supervisor.go +11 -30
M internal/adapters/headless/capture_test.go +0 -37
D internal/adapters/headless/continuous_test.go +0 -190
M internal/adapters/headless/frames_test.go +8 -72
M internal/adapters/headless/output.go +83 -192
A internal/adapters/headlessinput/identity.go +48 -0
A internal/adapters/headlessinput/input.go +476 -0
A internal/adapters/headlessinput/input_test.go +431 -0
A internal/adapters/headlessinput/security_test.go +287 -0
A internal/adapters/headlessinput/swipe.go +35 -0
M internal/adapters/logging/logging.go +11 -136
M internal/adapters/logging/logging_test.go +0 -105
M internal/adapters/outputkit/capture/fence.go +2 -2
M internal/adapters/outputkit/capture/offscreen.go +1 -1
M internal/adapters/outputkit/capture/pipeline.go +9 -23
M internal/adapters/outputkit/capture/pipeline_cursor_test.go +1 -3
M internal/adapters/outputkit/capture/pipeline_pq_test.go +1 -3
D internal/adapters/outputkit/capture/pixels.go +0 -46
D internal/adapters/outputkit/capture/pixels_test.go +0 -81
M internal/adapters/outputkit/capture/requests.go +1 -1
M internal/adapters/outputkit/corewake/corewake.go +4 -6
M internal/adapters/outputkit/corewake/corewake_test.go +6 -6
M internal/adapters/outputkit/headlessbackend/backend.go +17 -115
M internal/adapters/outputkit/headlessbackend/backend_test.go +0 -166
M internal/adapters/outputkit/routing/captured.go +8 -14
M internal/adapters/outputkit/routing/captured_test.go +3 -38
M internal/adapters/outputkit/routing/outputrouting.go +0 -2
M internal/adapters/outputkit/virtuals/virtuals.go +22 -16
M internal/adapters/outputkit/virtuals/virtuals_test.go +18 -0
D internal/adapters/screencast/current_buffers.go +0 -60
D internal/adapters/screencast/current_buffers_test.go +0 -39
D internal/adapters/sessiondir/sessiondir.go +0 -224
D internal/adapters/sessiondir/sessiondir_test.go +0 -118
M internal/adapters/statefile/statefile.go +163 -13
M internal/adapters/statefile/statefile_test.go +147 -6
D internal/adapters/statewire/statewire.go +0 -159
D internal/adapters/statewire/statewire_test.go +0 -150
M internal/adapters/vulkan/capture_dmabuf.go +1 -66
D internal/adapters/vulkan/copy_completion_mock_test.go +0 -185
D internal/adapters/vulkan/copy_completion_test.go +0 -43
M internal/adapters/vulkan/renderer.go +1 -1
M internal/adapters/vulkan/targets_test.go +1 -1
D internal/adapters/wayland/configure_commit_test.go +0 -230
M internal/adapters/wayland/fifo.go +2 -3
M internal/adapters/wayland/input_region_test.go +1 -1
M internal/adapters/wayland/layer.go +1 -1
M internal/adapters/wayland/popup.go +1 -1
M internal/adapters/wayland/session_lock_surface.go +1 -1
M internal/adapters/wayland/socket.go +2 -18
M internal/adapters/wayland/socket_test.go +0 -109
M internal/adapters/wayland/surface.go +3 -3
M internal/adapters/wayland/virtualpointer.go +2 -2
M internal/adapters/wayland/xdg.go +8 -48
D internal/adapters/xkb/transaction.go +0 -68
D internal/adapters/xkb/transaction_test.go +0 -119
M internal/adapters/xkb/xkb.go +1 -14
M internal/app/app.go +22 -36
M internal/app/app_test.go +18 -94
M internal/app/colorcheck_test.go +18 -32
D internal/app/control_client_test.go +0 -142
D internal/app/control_keymaps_test.go +0 -39
D internal/app/control_test.go +0 -177
M internal/app/hintoptin_test.go +3 -19
M internal/app/outputapply_e2e_test.go +2 -2
M internal/app/pointercli_test.go +1 -1
M internal/app/screencast_test.go +8 -18
M internal/app/server_test.go +6 -8
M internal/app/session.go +46 -159
M internal/app/session_lock_test.go +12 -20
M internal/app/textinput_test.go +2 -2
M internal/app/wayvnc_test.go +1 -1
M internal/app/wiring.go +37 -60
M internal/app/xwayland_fullscreen_group_test.go +11 -15
M internal/app/xwayland_keepfocus_test.go +2 -1
M internal/app/xwayland_lineage_test.go +11 -11
M internal/app/xwayland_test.go +39 -75
M internal/cli/cli.go +1 -21
M internal/cli/cli_test.go +66 -13
M internal/cli/commands.go +4 -15
D internal/cli/control.go +0 -179
D internal/cli/control_test.go +0 -216
D internal/cli/inject.go +0 -177
D internal/cli/inject_test.go +0 -20
D internal/cli/main_test.go +0 -25
D internal/cli/output.go +0 -33
D internal/cli/output_test.go +0 -50
D internal/cli/profile_test.go +0 -52
M internal/cli/run.go +69 -101
D internal/cli/session.go +0 -81
D internal/cli/session_new.go +0 -172
D internal/cli/session_new_test.go +0 -108
D internal/cli/session_rm.go +0 -132
D internal/cli/session_rm_test.go +0 -94
D internal/cli/session_test.go +0 -60
D internal/cli/shot.go +0 -60
D internal/cli/shot_test.go +0 -105
D internal/cli/target.go +0 -54
D internal/cli/target_test.go +0 -80
M internal/core/backendplan.go +25 -54
M internal/core/backendplan_test.go +14 -57
D internal/core/catalog_test.go +0 -47
M internal/core/client.go +0 -8
D internal/core/configure_commit_internal_test.go +0 -72
D internal/core/configure_resend_test.go +0 -87
M internal/core/configures.go +5 -40
D internal/core/control.go +0 -181
D internal/core/control_test.go +0 -106
D internal/core/controladmission_test.go +0 -58
D internal/core/controlcapture.go +0 -68
D internal/core/controlcapture_test.go +0 -89
D internal/core/controlinject_test.go +0 -157
D internal/core/controlinput.go +0 -27
D internal/core/controloutput.go +0 -37
D internal/core/controloutput_test.go +0 -56
D internal/core/controlshots_test.go +0 -105
D internal/core/controlwait.go +0 -283
D internal/core/controlwait_test.go +0 -327
M internal/core/core.go +31 -53
M internal/core/core_test.go +6 -9
M internal/core/datadrag.go +0 -2
M internal/core/devicebinding_test.go +0 -35
M internal/core/isolation_test.go +0 -39
M internal/core/outputapply.go +4 -10
M internal/core/outputoverrides.go +1 -2
D internal/core/presented_internal_test.go +0 -47
D internal/core/runtimecode.go +0 -21
D internal/core/runtimecode_test.go +0 -22
M internal/core/scene.go +0 -1
M internal/core/screens.go +1 -7
M internal/core/stash_spawn_test.go +0 -27
D internal/core/virtualruntime.go +0 -92
D internal/core/virtualruntime_test.go +0 -73
D internal/core/workspace/actions_test.go +0 -46
M internal/core/workspace/layout.go +3 -10
M internal/core/workspace/stash_test.go +0 -65
M internal/core/workspace/workspace_actions.go +0 -33
M internal/domain/backend.go +3 -2
D internal/domain/backend_profile.go +0 -34
D internal/domain/backend_profile_test.go +0 -20
M internal/domain/backend_test.go +2 -2
M internal/domain/bind_events.go +0 -1
M internal/domain/capture_messages.go +0 -3
D internal/domain/command.go +0 -334
D internal/domain/command_test.go +0 -178
M internal/domain/input.go +0 -10
M internal/domain/output_events.go +4 -6
D internal/domain/output_mode.go +0 -45
D internal/domain/output_mode_test.go +0 -33
M internal/ports/capture_messages.go +0 -4
M internal/ports/client_commands.go +0 -2
M internal/ports/client_events.go +0 -11
D internal/ports/continuous_capture.go +0 -40
D internal/ports/control.go +0 -117
D internal/ports/output_runtime.go +0 -27
M packaging/neferwl-server.service +1 -1
M packaging/neferwl-session +0 -9
D skills/neferwl/CLI.md +0 -168
D skills/neferwl/PROTOCOL.md +0 -50
D skills/neferwl/SKILL.md +0 -128
M tools/demo/record.sh +16 -15
Comments00 unresolved
no comments yet.