feat/server-mode ea3b2fd

#125 feat: server backend for headless game streaming

state
merged · f1ced29 · merge commit
branch
feat/server-mode → main
opened
bnema ·
updated

Runs NeferWL as a headless game server (e.g. Sunshine streaming) without a desktop session.

  • --backend=server: direct seat devices, virtual outputs, screencast, Xwayland, session D-Bus services.
  • Optional isolation of unplaced virtual outputs.
  • neferwl-server user unit with ordered desktop/server session handover.
  • Docs: game server with Sunshine.

Review: go-reviewer approved. Tests: race, mocks, staticcheck, server backend screencast and Xwayland e2e.

CommitSubjectAuthorDateSignatureStatus
ea3b2fdtest(app): skip the server backend test where /sys/class/drm is absentbrice GPG Verified
8adc94dchore(merge): merge origin/main into feat/server-modebrice GPG Verified
70fc3e8fix(packaging): order desktop and server session handoverbrice GPG Verified
784249cfix(directseat): refuse devices that cannot be grabbedbrice GPG Verified
5eea792docs(server): game server with Sunshinebrice GPG Verified
21ee042feat(packaging): neferwl-server user unitbrice GPG Verified
4fa08f7test(app): server backend screencast and xwayland e2ebrice GPG Verified
8187718feat(cli): --backend=serverbrice GPG Verified
63b2135feat(app): server backend wiringbrice GPG Verified
8278327feat(core): optional isolation of unplaced virtual outputsbrice GPG Verified
52bdf15fix(core): start session D-Bus services in server modebrice GPG Verified
77efcd3Merge branch 'feat/server-plan' into feat/server-modebrice GPG Verified
03667fefeat(core): backend plan for drm, headless and serverbrice GPG Verified
ca2195aMerge branch 'feat/server-directseat' into feat/server-modebrice GPG Verified
9b6265cfeat(directseat): open input devices directly with an exclusive grabbrice GPG Verified
60c24b4feat(core): require a hardware render node on requestbrice GPG Verified
87ec8bcfeat(headless): run with virtual outputs onlybrice GPG Verified

Checks 1

36 files · +1363 -37
1/1
M .goreleaser.yaml +4 -0
@@ -46,6 +46,7 @@ archives:
4646 - examples/capture-allow
4747 - packaging/neferwl-session
4848 - packaging/neferwl.service
49+ - packaging/neferwl-server.service
4950 - packaging/neferwl-shutdown.target
5051 - packaging/neferwl.desktop
5152 - packaging/neferwl-portals.conf
@@ -89,6 +90,8 @@ nfpms:
8990 file_info: {mode: 0755}
9091 - src: packaging/neferwl.service
9192 dst: /usr/lib/systemd/user/neferwl.service
93+ - src: packaging/neferwl-server.service
94+ dst: /usr/lib/systemd/user/neferwl-server.service
9295 - src: packaging/neferwl-shutdown.target
9396 dst: /usr/lib/systemd/user/neferwl-shutdown.target
9497 - src: packaging/neferwl.desktop
@@ -223,6 +226,7 @@ aurs:
223226 install -Dm755 ./neferwl "${pkgdir}/usr/bin/neferwl"
224227 install -Dm755 ./packaging/neferwl-session "${pkgdir}/usr/bin/neferwl-session"
225228 install -Dm644 ./packaging/neferwl.service "${pkgdir}/usr/lib/systemd/user/neferwl.service"
229+ install -Dm644 ./packaging/neferwl-server.service "${pkgdir}/usr/lib/systemd/user/neferwl-server.service"
226230 install -Dm644 ./packaging/neferwl-shutdown.target "${pkgdir}/usr/lib/systemd/user/neferwl-shutdown.target"
227231 install -Dm644 ./packaging/neferwl.desktop "${pkgdir}/usr/share/wayland-sessions/neferwl.desktop"
228232 install -Dm644 ./packaging/neferwl-portals.conf "${pkgdir}/usr/share/xdg-desktop-portal/neferwl-portals.conf"
@@ -46,6 +46,7 @@ archives:
46 - examples/capture-allow46 - examples/capture-allow
47 - packaging/neferwl-session47 - packaging/neferwl-session
48 - packaging/neferwl.service48 - packaging/neferwl.service
49+ - packaging/neferwl-server.service
49 - packaging/neferwl-shutdown.target50 - packaging/neferwl-shutdown.target
50 - packaging/neferwl.desktop51 - packaging/neferwl.desktop
51 - packaging/neferwl-portals.conf52 - packaging/neferwl-portals.conf
@@ -89,6 +90,8 @@ nfpms:
89 file_info: {mode: 0755}90 file_info: {mode: 0755}
90 - src: packaging/neferwl.service91 - src: packaging/neferwl.service
91 dst: /usr/lib/systemd/user/neferwl.service92 dst: /usr/lib/systemd/user/neferwl.service
93+ - src: packaging/neferwl-server.service
94+ dst: /usr/lib/systemd/user/neferwl-server.service
92 - src: packaging/neferwl-shutdown.target95 - src: packaging/neferwl-shutdown.target
93 dst: /usr/lib/systemd/user/neferwl-shutdown.target96 dst: /usr/lib/systemd/user/neferwl-shutdown.target
94 - src: packaging/neferwl.desktop97 - src: packaging/neferwl.desktop
@@ -223,6 +226,7 @@ aurs:
223 install -Dm755 ./neferwl "${pkgdir}/usr/bin/neferwl"226 install -Dm755 ./neferwl "${pkgdir}/usr/bin/neferwl"
224 install -Dm755 ./packaging/neferwl-session "${pkgdir}/usr/bin/neferwl-session"227 install -Dm755 ./packaging/neferwl-session "${pkgdir}/usr/bin/neferwl-session"
225 install -Dm644 ./packaging/neferwl.service "${pkgdir}/usr/lib/systemd/user/neferwl.service"228 install -Dm644 ./packaging/neferwl.service "${pkgdir}/usr/lib/systemd/user/neferwl.service"
229+ install -Dm644 ./packaging/neferwl-server.service "${pkgdir}/usr/lib/systemd/user/neferwl-server.service"
226 install -Dm644 ./packaging/neferwl-shutdown.target "${pkgdir}/usr/lib/systemd/user/neferwl-shutdown.target"230 install -Dm644 ./packaging/neferwl-shutdown.target "${pkgdir}/usr/lib/systemd/user/neferwl-shutdown.target"
227 install -Dm644 ./packaging/neferwl.desktop "${pkgdir}/usr/share/wayland-sessions/neferwl.desktop"231 install -Dm644 ./packaging/neferwl.desktop "${pkgdir}/usr/share/wayland-sessions/neferwl.desktop"
228 install -Dm644 ./packaging/neferwl-portals.conf "${pkgdir}/usr/share/xdg-desktop-portal/neferwl-portals.conf"232 install -Dm644 ./packaging/neferwl-portals.conf "${pkgdir}/usr/share/xdg-desktop-portal/neferwl-portals.conf"
M .mockery.yml +8 -0
@@ -299,3 +299,11 @@ packages:
299299 dir: internal/adapters/wayland/xwm
300300 pkgname: xwm
301301 filename: loop_mock_test.go
302+
303+ github.com/bnema/neferwl/internal/adapters/directseat:
304+ interfaces:
305+ evdev:
306+ config:
307+ dir: internal/adapters/directseat
308+ pkgname: directseat
309+ filename: evdev_mock_test.go
@@ -299,3 +299,11 @@ packages:
299 dir: internal/adapters/wayland/xwm299 dir: internal/adapters/wayland/xwm
300 pkgname: xwm300 pkgname: xwm
301 filename: loop_mock_test.go301 filename: loop_mock_test.go
302+
303+ github.com/bnema/neferwl/internal/adapters/directseat:
304+ interfaces:
305+ evdev:
306+ config:
307+ dir: internal/adapters/directseat
308+ pkgname: directseat
309+ filename: evdev_mock_test.go
M docs/capture.md +2 -0
@@ -101,3 +101,5 @@ capture = portal
101101 ```
102102
103103 Pick the output in the portal dialog, for example a virtual `tv` with `output.tv.hdr = on`.
104+
105+To stream from a machine with no display, run NeferWL in server mode: see [Game server](server.md).
@@ -101,3 +101,5 @@ capture = portal
101 ```101 ```
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+
105+To stream from a machine with no display, run NeferWL in server mode: see [Game server](server.md).
M docs/index.md +1 -0
@@ -6,5 +6,6 @@ NeferWL is a small Wayland compositor in Go. Start with Configuration to set up
66 - [Desktop integration](desktop.md): sessions, clipboard, input methods, X11 apps, session locking and scripting.
77 - [Screen capture](capture.md): protocols, indicator, executable allowlist and portals.
88 - [Performance](performance.md): resource use, VRR and real-time priority.
9+- [Game server](server.md): `--backend=server` on a headless machine, streaming with Sunshine.
910
1011 Developer documentation: [docs/dev](dev/index.md)
@@ -6,5 +6,6 @@ NeferWL is a small Wayland compositor in Go. Start with Configuration to set up
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+- [Game server](server.md): `--backend=server` on a headless machine, streaming with Sunshine.
9 10
10 Developer documentation: [docs/dev](dev/index.md)11 Developer documentation: [docs/dev](dev/index.md)
A docs/server.md +109 -0
@@ -0,0 +1,109 @@
1+# Game server
2+
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+
5+Server mode differs from a desktop session:
6+
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.
12+
13+## Requirements
14+
15+- A GPU with a DRM render node (`/dev/dri/renderD*`). Software rasterizers such as lavapipe are refused.
16+- PipeWire, `xdg-desktop-portal` and `xdg-desktop-portal-gnome`, with the packaged `neferwl-portals.conf` (see [Portals](capture.md#portals)).
17+- Sunshine with portal capture.
18+
19+## Account setup
20+
21+The user service runs without anyone logged in:
22+
23+```sh
24+sudo loginctl enable-linger $USER
25+```
26+
27+Without a logind seat, NeferWL opens `/dev/input/event*` itself, so the user must be in the `input` group. On distributions where `/dev/dri/renderD*` is not world-accessible, add `render` too:
28+
29+```sh
30+sudo usermod -aG input,render $USER
31+```
32+
33+Log out and back in (or reboot) to apply.
34+
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.
36+
37+## Configuration
38+
39+`~/.config/neferwl/config`:
40+
41+```ini
42+output.tv = virtual 1920x1080@60
43+output.tv.hdr = on
44+startup = steam -gamepadui
45+# Only when several GPUs are present, see Configuration > GPUs:
46+# render.device = /dev/dri/renderD128
47+```
48+
49+Check it with `neferwl validate-config`. See [Virtual outputs](config.md#virtual-outputs) and [GPUs](config.md#gpus).
50+
51+## Services
52+
53+```sh
54+systemctl --user enable --now neferwl-server.service
55+systemctl --user enable --now sunshine.service
56+```
57+
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
61+
62+`~/.config/sunshine/sunshine.conf`:
63+
64+```ini
65+capture = portal
66+```
67+
68+To match the client's resolution and refresh rate, change the virtual output's mode before each stream (`global_prep_cmd`, a JSON list):
69+
70+```ini
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"}]
72+```
73+
74+## First portal approval
75+
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:
77+
78+```sh
79+export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=')
80+grim -o tv /tmp/tv.png # look at the dialog
81+ydotool key 28:1 28:0 # Return accepts the selected output
82+```
83+
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.
85+
86+## HDR
87+
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).
89+
90+## Input
91+
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.
93+
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.
95+
96+## Hardening
97+
98+On a dedicated box, a local keyboard should not reboot or reach a console:
99+
100+```sh
101+sudo systemctl mask ctrl-alt-del.target
102+echo kernel.sysrq=0 | sudo tee /etc/sysctl.d/90-sysrq.conf
103+sudo systemctl disable --now getty@tty1.service
104+```
105+
106+## Limits
107+
108+- Touch screens and pens (tablets) are not supported.
109+- Only virtual outputs exist: a connected monitor stays dark.
@@ -0,0 +1,109 @@
1+# Game server
2+
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+
5+Server mode differs from a desktop session:
6+
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.
12+
13+## Requirements
14+
15+- A GPU with a DRM render node (`/dev/dri/renderD*`). Software rasterizers such as lavapipe are refused.
16+- PipeWire, `xdg-desktop-portal` and `xdg-desktop-portal-gnome`, with the packaged `neferwl-portals.conf` (see [Portals](capture.md#portals)).
17+- Sunshine with portal capture.
18+
19+## Account setup
20+
21+The user service runs without anyone logged in:
22+
23+```sh
24+sudo loginctl enable-linger $USER
25+```
26+
27+Without a logind seat, NeferWL opens `/dev/input/event*` itself, so the user must be in the `input` group. On distributions where `/dev/dri/renderD*` is not world-accessible, add `render` too:
28+
29+```sh
30+sudo usermod -aG input,render $USER
31+```
32+
33+Log out and back in (or reboot) to apply.
34+
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.
36+
37+## Configuration
38+
39+`~/.config/neferwl/config`:
40+
41+```ini
42+output.tv = virtual 1920x1080@60
43+output.tv.hdr = on
44+startup = steam -gamepadui
45+# Only when several GPUs are present, see Configuration > GPUs:
46+# render.device = /dev/dri/renderD128
47+```
48+
49+Check it with `neferwl validate-config`. See [Virtual outputs](config.md#virtual-outputs) and [GPUs](config.md#gpus).
50+
51+## Services
52+
53+```sh
54+systemctl --user enable --now neferwl-server.service
55+systemctl --user enable --now sunshine.service
56+```
57+
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
61+
62+`~/.config/sunshine/sunshine.conf`:
63+
64+```ini
65+capture = portal
66+```
67+
68+To match the client's resolution and refresh rate, change the virtual output's mode before each stream (`global_prep_cmd`, a JSON list):
69+
70+```ini
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"}]
72+```
73+
74+## First portal approval
75+
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:
77+
78+```sh
79+export $(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=')
80+grim -o tv /tmp/tv.png # look at the dialog
81+ydotool key 28:1 28:0 # Return accepts the selected output
82+```
83+
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.
85+
86+## HDR
87+
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).
89+
90+## Input
91+
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.
93+
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.
95+
96+## Hardening
97+
98+On a dedicated box, a local keyboard should not reboot or reach a console:
99+
100+```sh
101+sudo systemctl mask ctrl-alt-del.target
102+echo kernel.sysrq=0 | sudo tee /etc/sysctl.d/90-sysrq.conf
103+sudo systemctl disable --now getty@tty1.service
104+```
105+
106+## Limits
107+
108+- Touch screens and pens (tablets) are not supported.
109+- Only virtual outputs exist: a connected monitor stays dark.
A internal/adapters/directseat/directseat.go +101 -0
@@ -0,0 +1,101 @@
1+// Package directseat opens input devices directly, without logind or
2+// seatd. It serves server mode under systemd linger, where no session
3+// broker exists. Each device is grabbed exclusively (EVIOCGRAB) so
4+// keystrokes injected through uinput do not reach the kernel console.
5+package directseat
6+
7+import (
8+ "errors"
9+ "fmt"
10+
11+ "bnema.dev/zerowrap"
12+ "golang.org/x/sys/unix"
13+
14+ "github.com/bnema/neferwl/internal/ports"
15+)
16+
17+// name is the seat every directly opened device belongs to.
18+const name = "seat0"
19+
20+// eviocgrab is EVIOCGRAB, _IOW('E', 0x90, int); x/sys/unix does not export it.
21+const eviocgrab = 0x40044590
22+
23+// evdev is the kernel boundary for input device fds.
24+type evdev interface {
25+ open(path string) (int, error)
26+ grab(fd int) error
27+ ungrab(fd int) error
28+ close(fd int) error
29+}
30+
31+type unixEvdev struct{}
32+
33+func (unixEvdev) open(path string) (int, error) {
34+ return unix.Open(path, unix.O_RDWR|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
35+}
36+
37+func (unixEvdev) grab(fd int) error { return unix.IoctlSetInt(fd, eviocgrab, 1) }
38+func (unixEvdev) ungrab(fd int) error { return unix.IoctlSetInt(fd, eviocgrab, 0) }
39+func (unixEvdev) close(fd int) error { return unix.Close(fd) }
40+
41+// Seat implements ports.Seat by opening devices itself. It is always
42+// active: there is no VT to switch away from.
43+type Seat struct {
44+ log zerowrap.Logger
45+ dev evdev
46+ active chan bool
47+}
48+
49+var _ ports.Seat = (*Seat)(nil)
50+
51+// New returns a direct seat. log should carry the seat component.
52+func New(log zerowrap.Logger) *Seat { return newSeat(log, unixEvdev{}) }
53+
54+func newSeat(log zerowrap.Logger, dev evdev) *Seat {
55+ active := make(chan bool, 1)
56+ active <- true
57+ return &Seat{log: log, dev: dev, active: active}
58+}
59+
60+// OpenDevice opens path read-write and grabs it exclusively. It fails
61+// closed: a device it cannot grab is closed and refused, so its input never
62+// reaches another client (a console or another session) as well.
63+func (s *Seat) OpenDevice(path string) (int, error) {
64+ fd, err := s.dev.open(path)
65+ if err != nil {
66+ return -1, fmt.Errorf("open input device %s: %w", path, err)
67+ }
68+ if err := s.dev.grab(fd); err != nil {
69+ if cerr := s.dev.close(fd); cerr != nil {
70+ s.log.Warn().Err(cerr).Int("fd", fd).Msg("close input device")
71+ }
72+ if errors.Is(err, unix.EBUSY) {
73+ err = fmt.Errorf("another client holds an exclusive grab: %w", err)
74+ }
75+ err = fmt.Errorf("grab input device %s: %w", path, err)
76+ s.log.Warn().Err(err).Str("path", path).Msg("input device skipped")
77+ return -1, err
78+ }
79+ return fd, nil
80+}
81+
82+// CloseDevice releases the grab and closes fd.
83+func (s *Seat) CloseDevice(fd int) {
84+ if err := s.dev.ungrab(fd); err != nil {
85+ s.log.Debug().Err(err).Int("fd", fd).Msg("release grab")
86+ }
87+ if err := s.dev.close(fd); err != nil {
88+ s.log.Warn().Err(err).Int("fd", fd).Msg("close input device")
89+ }
90+}
91+
92+// SwitchVT is a no-op: a direct seat owns no VT.
93+func (s *Seat) SwitchVT(vt int) {
94+ s.log.Debug().Int("vt", vt).Msg("vt switch ignored without a session broker")
95+}
96+
97+// Name returns the seat name.
98+func (s *Seat) Name() string { return name }
99+
100+// Active yields true once: the seat never goes inactive.
101+func (s *Seat) Active() <-chan bool { return s.active }
@@ -0,0 +1,101 @@
1+// Package directseat opens input devices directly, without logind or
2+// seatd. It serves server mode under systemd linger, where no session
3+// broker exists. Each device is grabbed exclusively (EVIOCGRAB) so
4+// keystrokes injected through uinput do not reach the kernel console.
5+package directseat
6+
7+import (
8+ "errors"
9+ "fmt"
10+
11+ "bnema.dev/zerowrap"
12+ "golang.org/x/sys/unix"
13+
14+ "github.com/bnema/neferwl/internal/ports"
15+)
16+
17+// name is the seat every directly opened device belongs to.
18+const name = "seat0"
19+
20+// eviocgrab is EVIOCGRAB, _IOW('E', 0x90, int); x/sys/unix does not export it.
21+const eviocgrab = 0x40044590
22+
23+// evdev is the kernel boundary for input device fds.
24+type evdev interface {
25+ open(path string) (int, error)
26+ grab(fd int) error
27+ ungrab(fd int) error
28+ close(fd int) error
29+}
30+
31+type unixEvdev struct{}
32+
33+func (unixEvdev) open(path string) (int, error) {
34+ return unix.Open(path, unix.O_RDWR|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
35+}
36+
37+func (unixEvdev) grab(fd int) error { return unix.IoctlSetInt(fd, eviocgrab, 1) }
38+func (unixEvdev) ungrab(fd int) error { return unix.IoctlSetInt(fd, eviocgrab, 0) }
39+func (unixEvdev) close(fd int) error { return unix.Close(fd) }
40+
41+// Seat implements ports.Seat by opening devices itself. It is always
42+// active: there is no VT to switch away from.
43+type Seat struct {
44+ log zerowrap.Logger
45+ dev evdev
46+ active chan bool
47+}
48+
49+var _ ports.Seat = (*Seat)(nil)
50+
51+// New returns a direct seat. log should carry the seat component.
52+func New(log zerowrap.Logger) *Seat { return newSeat(log, unixEvdev{}) }
53+
54+func newSeat(log zerowrap.Logger, dev evdev) *Seat {
55+ active := make(chan bool, 1)
56+ active <- true
57+ return &Seat{log: log, dev: dev, active: active}
58+}
59+
60+// OpenDevice opens path read-write and grabs it exclusively. It fails
61+// closed: a device it cannot grab is closed and refused, so its input never
62+// reaches another client (a console or another session) as well.
63+func (s *Seat) OpenDevice(path string) (int, error) {
64+ fd, err := s.dev.open(path)
65+ if err != nil {
66+ return -1, fmt.Errorf("open input device %s: %w", path, err)
67+ }
68+ if err := s.dev.grab(fd); err != nil {
69+ if cerr := s.dev.close(fd); cerr != nil {
70+ s.log.Warn().Err(cerr).Int("fd", fd).Msg("close input device")
71+ }
72+ if errors.Is(err, unix.EBUSY) {
73+ err = fmt.Errorf("another client holds an exclusive grab: %w", err)
74+ }
75+ err = fmt.Errorf("grab input device %s: %w", path, err)
76+ s.log.Warn().Err(err).Str("path", path).Msg("input device skipped")
77+ return -1, err
78+ }
79+ return fd, nil
80+}
81+
82+// CloseDevice releases the grab and closes fd.
83+func (s *Seat) CloseDevice(fd int) {
84+ if err := s.dev.ungrab(fd); err != nil {
85+ s.log.Debug().Err(err).Int("fd", fd).Msg("release grab")
86+ }
87+ if err := s.dev.close(fd); err != nil {
88+ s.log.Warn().Err(err).Int("fd", fd).Msg("close input device")
89+ }
90+}
91+
92+// SwitchVT is a no-op: a direct seat owns no VT.
93+func (s *Seat) SwitchVT(vt int) {
94+ s.log.Debug().Int("vt", vt).Msg("vt switch ignored without a session broker")
95+}
96+
97+// Name returns the seat name.
98+func (s *Seat) Name() string { return name }
99+
100+// Active yields true once: the seat never goes inactive.
101+func (s *Seat) Active() <-chan bool { return s.active }
A internal/adapters/directseat/directseat_test.go +140 -0
@@ -0,0 +1,140 @@
1+package directseat
2+
3+import (
4+ "bytes"
5+ "errors"
6+ "os"
7+ "path/filepath"
8+ "sync"
9+ "testing"
10+
11+ "bnema.dev/zerowrap"
12+ "github.com/stretchr/testify/assert"
13+ "github.com/stretchr/testify/require"
14+ "golang.org/x/sys/unix"
15+)
16+
17+type lockedBuffer struct {
18+ mu sync.Mutex
19+ buf bytes.Buffer
20+}
21+
22+func (b *lockedBuffer) Write(p []byte) (int, error) {
23+ b.mu.Lock()
24+ defer b.mu.Unlock()
25+ return b.buf.Write(p)
26+}
27+
28+func (b *lockedBuffer) String() string {
29+ b.mu.Lock()
30+ defer b.mu.Unlock()
31+ return b.buf.String()
32+}
33+
34+func testLog(out *lockedBuffer) zerowrap.Logger {
35+ return zerowrap.Logger{Logger: zerowrap.New(zerowrap.Config{Level: "debug", Format: "json", Output: out}).With().Str("component", "seat").Logger()}
36+}
37+
38+func TestOpenDeviceGrabs(t *testing.T) {
39+ d := newMockevdev(t)
40+ d.EXPECT().open("/dev/input/event3").Return(7, nil)
41+ d.EXPECT().grab(7).Return(nil)
42+ var out lockedBuffer
43+ fd, err := newSeat(testLog(&out), d).OpenDevice("/dev/input/event3")
44+ require.NoError(t, err)
45+ assert.Equal(t, 7, fd)
46+ assert.NotContains(t, out.String(), `"warn"`)
47+}
48+
49+func TestOpenDeviceGrabBusyRefused(t *testing.T) {
50+ d := newMockevdev(t)
51+ d.EXPECT().open("/dev/input/event3").Return(7, nil)
52+ d.EXPECT().grab(7).Return(unix.EBUSY)
53+ d.EXPECT().close(7).Return(nil).Once()
54+ var out lockedBuffer
55+ fd, err := newSeat(testLog(&out), d).OpenDevice("/dev/input/event3")
56+ require.ErrorIs(t, err, unix.EBUSY)
57+ assert.Contains(t, err.Error(), "another client holds an exclusive grab")
58+ assert.Contains(t, err.Error(), "/dev/input/event3")
59+ assert.Equal(t, -1, fd)
60+ assert.Contains(t, out.String(), `"level":"warn"`)
61+ assert.Contains(t, out.String(), `"component":"seat"`)
62+}
63+
64+func TestOpenDeviceOpenFailure(t *testing.T) {
65+ d := newMockevdev(t)
66+ d.EXPECT().open("/dev/input/event3").Return(-1, unix.EACCES)
67+ _, err := newSeat(testLog(&lockedBuffer{}), d).OpenDevice("/dev/input/event3")
68+ require.ErrorIs(t, err, unix.EACCES)
69+}
70+
71+func TestCloseDeviceReleasesAndCloses(t *testing.T) {
72+ d := newMockevdev(t)
73+ var order []string
74+ d.EXPECT().ungrab(7).RunAndReturn(func(int) error { order = append(order, "ungrab"); return nil })
75+ d.EXPECT().close(7).RunAndReturn(func(int) error { order = append(order, "close"); return nil })
76+ newSeat(testLog(&lockedBuffer{}), d).CloseDevice(7)
77+ assert.Equal(t, []string{"ungrab", "close"}, order)
78+}
79+
80+func TestCloseDeviceClosesAfterUngrabFailure(t *testing.T) {
81+ d := newMockevdev(t)
82+ d.EXPECT().ungrab(7).Return(errors.New("not grabbed"))
83+ d.EXPECT().close(7).Return(nil)
84+ newSeat(testLog(&lockedBuffer{}), d).CloseDevice(7)
85+}
86+
87+func TestSeatIdentityAndActive(t *testing.T) {
88+ var out lockedBuffer
89+ s := newSeat(testLog(&out), newMockevdev(t))
90+ assert.Equal(t, "seat0", s.Name())
91+ assert.True(t, <-s.Active())
92+ s.SwitchVT(2)
93+ assert.Contains(t, out.String(), `"level":"debug"`)
94+}
95+
96+// A regular file is not an evdev node: the grab fails with ENOTTY, the
97+// device is refused and the fd it opened is closed. Never opens a real
98+// /dev/input device.
99+func TestRealFileGrabENOTTYRefused(t *testing.T) {
100+ path := filepath.Join(t.TempDir(), "event0")
101+ require.NoError(t, os.WriteFile(path, nil, 0o600))
102+ before := openFDs(t)
103+ var out lockedBuffer
104+ fd, err := New(testLog(&out)).OpenDevice(path)
105+ require.ErrorIs(t, err, unix.ENOTTY)
106+ assert.Equal(t, -1, fd)
107+ assert.Contains(t, out.String(), "inappropriate ioctl")
108+ assert.Equal(t, before, openFDs(t), "the refused device's fd leaked")
109+}
110+
111+// openFDs lists the process's open descriptors that point at regular files
112+// named event0 (the test's fake device).
113+func openFDs(t *testing.T) []string {
114+ t.Helper()
115+ entries, err := os.ReadDir("/proc/self/fd")
116+ require.NoError(t, err)
117+ var fds []string
118+ for _, e := range entries {
119+ if target, err := os.Readlink(filepath.Join("/proc/self/fd", e.Name())); err == nil && filepath.Base(target) == "event0" {
120+ fds = append(fds, e.Name())
121+ }
122+ }
123+ return fds
124+}
125+
126+// The kernel boundary opens devices read-write, non-blocking and close-on-exec.
127+func TestUnixOpenFlags(t *testing.T) {
128+ path := filepath.Join(t.TempDir(), "event0")
129+ require.NoError(t, os.WriteFile(path, nil, 0o600))
130+ fd, err := unixEvdev{}.open(path)
131+ require.NoError(t, err)
132+ defer unix.Close(fd)
133+ flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
134+ require.NoError(t, err)
135+ assert.Equal(t, unix.O_RDWR, flags&unix.O_ACCMODE)
136+ assert.NotZero(t, flags&unix.O_NONBLOCK)
137+ fdflags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0)
138+ require.NoError(t, err)
139+ assert.NotZero(t, fdflags&unix.FD_CLOEXEC)
140+}
@@ -0,0 +1,140 @@
1+package directseat
2+
3+import (
4+ "bytes"
5+ "errors"
6+ "os"
7+ "path/filepath"
8+ "sync"
9+ "testing"
10+
11+ "bnema.dev/zerowrap"
12+ "github.com/stretchr/testify/assert"
13+ "github.com/stretchr/testify/require"
14+ "golang.org/x/sys/unix"
15+)
16+
17+type lockedBuffer struct {
18+ mu sync.Mutex
19+ buf bytes.Buffer
20+}
21+
22+func (b *lockedBuffer) Write(p []byte) (int, error) {
23+ b.mu.Lock()
24+ defer b.mu.Unlock()
25+ return b.buf.Write(p)
26+}
27+
28+func (b *lockedBuffer) String() string {
29+ b.mu.Lock()
30+ defer b.mu.Unlock()
31+ return b.buf.String()
32+}
33+
34+func testLog(out *lockedBuffer) zerowrap.Logger {
35+ return zerowrap.Logger{Logger: zerowrap.New(zerowrap.Config{Level: "debug", Format: "json", Output: out}).With().Str("component", "seat").Logger()}
36+}
37+
38+func TestOpenDeviceGrabs(t *testing.T) {
39+ d := newMockevdev(t)
40+ d.EXPECT().open("/dev/input/event3").Return(7, nil)
41+ d.EXPECT().grab(7).Return(nil)
42+ var out lockedBuffer
43+ fd, err := newSeat(testLog(&out), d).OpenDevice("/dev/input/event3")
44+ require.NoError(t, err)
45+ assert.Equal(t, 7, fd)
46+ assert.NotContains(t, out.String(), `"warn"`)
47+}
48+
49+func TestOpenDeviceGrabBusyRefused(t *testing.T) {
50+ d := newMockevdev(t)
51+ d.EXPECT().open("/dev/input/event3").Return(7, nil)
52+ d.EXPECT().grab(7).Return(unix.EBUSY)
53+ d.EXPECT().close(7).Return(nil).Once()
54+ var out lockedBuffer
55+ fd, err := newSeat(testLog(&out), d).OpenDevice("/dev/input/event3")
56+ require.ErrorIs(t, err, unix.EBUSY)
57+ assert.Contains(t, err.Error(), "another client holds an exclusive grab")
58+ assert.Contains(t, err.Error(), "/dev/input/event3")
59+ assert.Equal(t, -1, fd)
60+ assert.Contains(t, out.String(), `"level":"warn"`)
61+ assert.Contains(t, out.String(), `"component":"seat"`)
62+}
63+
64+func TestOpenDeviceOpenFailure(t *testing.T) {
65+ d := newMockevdev(t)
66+ d.EXPECT().open("/dev/input/event3").Return(-1, unix.EACCES)
67+ _, err := newSeat(testLog(&lockedBuffer{}), d).OpenDevice("/dev/input/event3")
68+ require.ErrorIs(t, err, unix.EACCES)
69+}
70+
71+func TestCloseDeviceReleasesAndCloses(t *testing.T) {
72+ d := newMockevdev(t)
73+ var order []string
74+ d.EXPECT().ungrab(7).RunAndReturn(func(int) error { order = append(order, "ungrab"); return nil })
75+ d.EXPECT().close(7).RunAndReturn(func(int) error { order = append(order, "close"); return nil })
76+ newSeat(testLog(&lockedBuffer{}), d).CloseDevice(7)
77+ assert.Equal(t, []string{"ungrab", "close"}, order)
78+}
79+
80+func TestCloseDeviceClosesAfterUngrabFailure(t *testing.T) {
81+ d := newMockevdev(t)
82+ d.EXPECT().ungrab(7).Return(errors.New("not grabbed"))
83+ d.EXPECT().close(7).Return(nil)
84+ newSeat(testLog(&lockedBuffer{}), d).CloseDevice(7)
85+}
86+
87+func TestSeatIdentityAndActive(t *testing.T) {
88+ var out lockedBuffer
89+ s := newSeat(testLog(&out), newMockevdev(t))
90+ assert.Equal(t, "seat0", s.Name())
91+ assert.True(t, <-s.Active())
92+ s.SwitchVT(2)
93+ assert.Contains(t, out.String(), `"level":"debug"`)
94+}
95+
96+// A regular file is not an evdev node: the grab fails with ENOTTY, the
97+// device is refused and the fd it opened is closed. Never opens a real
98+// /dev/input device.
99+func TestRealFileGrabENOTTYRefused(t *testing.T) {
100+ path := filepath.Join(t.TempDir(), "event0")
101+ require.NoError(t, os.WriteFile(path, nil, 0o600))
102+ before := openFDs(t)
103+ var out lockedBuffer
104+ fd, err := New(testLog(&out)).OpenDevice(path)
105+ require.ErrorIs(t, err, unix.ENOTTY)
106+ assert.Equal(t, -1, fd)
107+ assert.Contains(t, out.String(), "inappropriate ioctl")
108+ assert.Equal(t, before, openFDs(t), "the refused device's fd leaked")
109+}
110+
111+// openFDs lists the process's open descriptors that point at regular files
112+// named event0 (the test's fake device).
113+func openFDs(t *testing.T) []string {
114+ t.Helper()
115+ entries, err := os.ReadDir("/proc/self/fd")
116+ require.NoError(t, err)
117+ var fds []string
118+ for _, e := range entries {
119+ if target, err := os.Readlink(filepath.Join("/proc/self/fd", e.Name())); err == nil && filepath.Base(target) == "event0" {
120+ fds = append(fds, e.Name())
121+ }
122+ }
123+ return fds
124+}
125+
126+// The kernel boundary opens devices read-write, non-blocking and close-on-exec.
127+func TestUnixOpenFlags(t *testing.T) {
128+ path := filepath.Join(t.TempDir(), "event0")
129+ require.NoError(t, os.WriteFile(path, nil, 0o600))
130+ fd, err := unixEvdev{}.open(path)
131+ require.NoError(t, err)
132+ defer unix.Close(fd)
133+ flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
134+ require.NoError(t, err)
135+ assert.Equal(t, unix.O_RDWR, flags&unix.O_ACCMODE)
136+ assert.NotZero(t, flags&unix.O_NONBLOCK)
137+ fdflags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0)
138+ require.NoError(t, err)
139+ assert.NotZero(t, fdflags&unix.FD_CLOEXEC)
140+}
A internal/adapters/directseat/evdev_mock_test.go +258 -0
@@ -0,0 +1,258 @@
1+// Code generated by mockery; DO NOT EDIT.
2+// github.com/vektra/mockery
3+// template: testify
4+
5+package directseat
6+
7+import (
8+ mock "github.com/stretchr/testify/mock"
9+)
10+
11+// newMockevdev creates a new instance of mockevdev. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
12+// The first argument is typically a *testing.T value.
13+func newMockevdev(t interface {
14+ mock.TestingT
15+ Cleanup(func())
16+}) *mockevdev {
17+ if helper, ok := t.(interface{ Helper() }); ok {
18+ helper.Helper()
19+ }
20+
21+ mock := &mockevdev{}
22+ mock.Mock.Test(t)
23+
24+ t.Cleanup(func() {
25+ if helper, ok := t.(interface{ Helper() }); ok {
26+ helper.Helper()
27+ }
28+ mock.AssertExpectations(t)
29+ })
30+
31+ return mock
32+}
33+
34+// mockevdev is an autogenerated mock type for the evdev type
35+type mockevdev struct {
36+ mock.Mock
37+}
38+
39+type mockevdev_Expecter struct {
40+ mock *mock.Mock
41+}
42+
43+func (_m *mockevdev) EXPECT() *mockevdev_Expecter {
44+ return &mockevdev_Expecter{mock: &_m.Mock}
45+}
46+
47+// close provides a mock function for the type mockevdev
48+func (_mock *mockevdev) close(fd int) error {
49+ ret := _mock.Called(fd)
50+
51+ if len(ret) == 0 {
52+ panic("no return value specified for close")
53+ }
54+
55+ var r0 error
56+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
57+ r0 = returnFunc(fd)
58+ } else {
59+ r0 = ret.Error(0)
60+ }
61+ return r0
62+}
63+
64+// mockevdev_close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'close'
65+type mockevdev_close_Call struct {
66+ *mock.Call
67+}
68+
69+// close is a helper method to define mock.On call
70+// - fd int
71+func (_e *mockevdev_Expecter) close(fd any) *mockevdev_close_Call {
72+ return &mockevdev_close_Call{Call: _e.mock.On("close", fd)}
73+}
74+
75+func (_c *mockevdev_close_Call) Run(run func(fd int)) *mockevdev_close_Call {
76+ _c.Call.Run(func(args mock.Arguments) {
77+ var arg0 int
78+ if args[0] != nil {
79+ arg0 = args[0].(int)
80+ }
81+ run(
82+ arg0,
83+ )
84+ })
85+ return _c
86+}
87+
88+func (_c *mockevdev_close_Call) Return(err error) *mockevdev_close_Call {
89+ _c.Call.Return(err)
90+ return _c
91+}
92+
93+func (_c *mockevdev_close_Call) RunAndReturn(run func(fd int) error) *mockevdev_close_Call {
94+ _c.Call.Return(run)
95+ return _c
96+}
97+
98+// grab provides a mock function for the type mockevdev
99+func (_mock *mockevdev) grab(fd int) error {
100+ ret := _mock.Called(fd)
101+
102+ if len(ret) == 0 {
103+ panic("no return value specified for grab")
104+ }
105+
106+ var r0 error
107+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
108+ r0 = returnFunc(fd)
109+ } else {
110+ r0 = ret.Error(0)
111+ }
112+ return r0
113+}
114+
115+// mockevdev_grab_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'grab'
116+type mockevdev_grab_Call struct {
117+ *mock.Call
118+}
119+
120+// grab is a helper method to define mock.On call
121+// - fd int
122+func (_e *mockevdev_Expecter) grab(fd any) *mockevdev_grab_Call {
123+ return &mockevdev_grab_Call{Call: _e.mock.On("grab", fd)}
124+}
125+
126+func (_c *mockevdev_grab_Call) Run(run func(fd int)) *mockevdev_grab_Call {
127+ _c.Call.Run(func(args mock.Arguments) {
128+ var arg0 int
129+ if args[0] != nil {
130+ arg0 = args[0].(int)
131+ }
132+ run(
133+ arg0,
134+ )
135+ })
136+ return _c
137+}
138+
139+func (_c *mockevdev_grab_Call) Return(err error) *mockevdev_grab_Call {
140+ _c.Call.Return(err)
141+ return _c
142+}
143+
144+func (_c *mockevdev_grab_Call) RunAndReturn(run func(fd int) error) *mockevdev_grab_Call {
145+ _c.Call.Return(run)
146+ return _c
147+}
148+
149+// open provides a mock function for the type mockevdev
150+func (_mock *mockevdev) open(path string) (int, error) {
151+ ret := _mock.Called(path)
152+
153+ if len(ret) == 0 {
154+ panic("no return value specified for open")
155+ }
156+
157+ var r0 int
158+ var r1 error
159+ if returnFunc, ok := ret.Get(0).(func(string) (int, error)); ok {
160+ return returnFunc(path)
161+ }
162+ if returnFunc, ok := ret.Get(0).(func(string) int); ok {
163+ r0 = returnFunc(path)
164+ } else {
165+ r0 = ret.Get(0).(int)
166+ }
167+ if returnFunc, ok := ret.Get(1).(func(string) error); ok {
168+ r1 = returnFunc(path)
169+ } else {
170+ r1 = ret.Error(1)
171+ }
172+ return r0, r1
173+}
174+
175+// mockevdev_open_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'open'
176+type mockevdev_open_Call struct {
177+ *mock.Call
178+}
179+
180+// open is a helper method to define mock.On call
181+// - path string
182+func (_e *mockevdev_Expecter) open(path any) *mockevdev_open_Call {
183+ return &mockevdev_open_Call{Call: _e.mock.On("open", path)}
184+}
185+
186+func (_c *mockevdev_open_Call) Run(run func(path string)) *mockevdev_open_Call {
187+ _c.Call.Run(func(args mock.Arguments) {
188+ var arg0 string
189+ if args[0] != nil {
190+ arg0 = args[0].(string)
191+ }
192+ run(
193+ arg0,
194+ )
195+ })
196+ return _c
197+}
198+
199+func (_c *mockevdev_open_Call) Return(n int, err error) *mockevdev_open_Call {
200+ _c.Call.Return(n, err)
201+ return _c
202+}
203+
204+func (_c *mockevdev_open_Call) RunAndReturn(run func(path string) (int, error)) *mockevdev_open_Call {
205+ _c.Call.Return(run)
206+ return _c
207+}
208+
209+// ungrab provides a mock function for the type mockevdev
210+func (_mock *mockevdev) ungrab(fd int) error {
211+ ret := _mock.Called(fd)
212+
213+ if len(ret) == 0 {
214+ panic("no return value specified for ungrab")
215+ }
216+
217+ var r0 error
218+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
219+ r0 = returnFunc(fd)
220+ } else {
221+ r0 = ret.Error(0)
222+ }
223+ return r0
224+}
225+
226+// mockevdev_ungrab_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ungrab'
227+type mockevdev_ungrab_Call struct {
228+ *mock.Call
229+}
230+
231+// ungrab is a helper method to define mock.On call
232+// - fd int
233+func (_e *mockevdev_Expecter) ungrab(fd any) *mockevdev_ungrab_Call {
234+ return &mockevdev_ungrab_Call{Call: _e.mock.On("ungrab", fd)}
235+}
236+
237+func (_c *mockevdev_ungrab_Call) Run(run func(fd int)) *mockevdev_ungrab_Call {
238+ _c.Call.Run(func(args mock.Arguments) {
239+ var arg0 int
240+ if args[0] != nil {
241+ arg0 = args[0].(int)
242+ }
243+ run(
244+ arg0,
245+ )
246+ })
247+ return _c
248+}
249+
250+func (_c *mockevdev_ungrab_Call) Return(err error) *mockevdev_ungrab_Call {
251+ _c.Call.Return(err)
252+ return _c
253+}
254+
255+func (_c *mockevdev_ungrab_Call) RunAndReturn(run func(fd int) error) *mockevdev_ungrab_Call {
256+ _c.Call.Return(run)
257+ return _c
258+}
@@ -0,0 +1,258 @@
1+// Code generated by mockery; DO NOT EDIT.
2+// github.com/vektra/mockery
3+// template: testify
4+
5+package directseat
6+
7+import (
8+ mock "github.com/stretchr/testify/mock"
9+)
10+
11+// newMockevdev creates a new instance of mockevdev. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
12+// The first argument is typically a *testing.T value.
13+func newMockevdev(t interface {
14+ mock.TestingT
15+ Cleanup(func())
16+}) *mockevdev {
17+ if helper, ok := t.(interface{ Helper() }); ok {
18+ helper.Helper()
19+ }
20+
21+ mock := &mockevdev{}
22+ mock.Mock.Test(t)
23+
24+ t.Cleanup(func() {
25+ if helper, ok := t.(interface{ Helper() }); ok {
26+ helper.Helper()
27+ }
28+ mock.AssertExpectations(t)
29+ })
30+
31+ return mock
32+}
33+
34+// mockevdev is an autogenerated mock type for the evdev type
35+type mockevdev struct {
36+ mock.Mock
37+}
38+
39+type mockevdev_Expecter struct {
40+ mock *mock.Mock
41+}
42+
43+func (_m *mockevdev) EXPECT() *mockevdev_Expecter {
44+ return &mockevdev_Expecter{mock: &_m.Mock}
45+}
46+
47+// close provides a mock function for the type mockevdev
48+func (_mock *mockevdev) close(fd int) error {
49+ ret := _mock.Called(fd)
50+
51+ if len(ret) == 0 {
52+ panic("no return value specified for close")
53+ }
54+
55+ var r0 error
56+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
57+ r0 = returnFunc(fd)
58+ } else {
59+ r0 = ret.Error(0)
60+ }
61+ return r0
62+}
63+
64+// mockevdev_close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'close'
65+type mockevdev_close_Call struct {
66+ *mock.Call
67+}
68+
69+// close is a helper method to define mock.On call
70+// - fd int
71+func (_e *mockevdev_Expecter) close(fd any) *mockevdev_close_Call {
72+ return &mockevdev_close_Call{Call: _e.mock.On("close", fd)}
73+}
74+
75+func (_c *mockevdev_close_Call) Run(run func(fd int)) *mockevdev_close_Call {
76+ _c.Call.Run(func(args mock.Arguments) {
77+ var arg0 int
78+ if args[0] != nil {
79+ arg0 = args[0].(int)
80+ }
81+ run(
82+ arg0,
83+ )
84+ })
85+ return _c
86+}
87+
88+func (_c *mockevdev_close_Call) Return(err error) *mockevdev_close_Call {
89+ _c.Call.Return(err)
90+ return _c
91+}
92+
93+func (_c *mockevdev_close_Call) RunAndReturn(run func(fd int) error) *mockevdev_close_Call {
94+ _c.Call.Return(run)
95+ return _c
96+}
97+
98+// grab provides a mock function for the type mockevdev
99+func (_mock *mockevdev) grab(fd int) error {
100+ ret := _mock.Called(fd)
101+
102+ if len(ret) == 0 {
103+ panic("no return value specified for grab")
104+ }
105+
106+ var r0 error
107+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
108+ r0 = returnFunc(fd)
109+ } else {
110+ r0 = ret.Error(0)
111+ }
112+ return r0
113+}
114+
115+// mockevdev_grab_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'grab'
116+type mockevdev_grab_Call struct {
117+ *mock.Call
118+}
119+
120+// grab is a helper method to define mock.On call
121+// - fd int
122+func (_e *mockevdev_Expecter) grab(fd any) *mockevdev_grab_Call {
123+ return &mockevdev_grab_Call{Call: _e.mock.On("grab", fd)}
124+}
125+
126+func (_c *mockevdev_grab_Call) Run(run func(fd int)) *mockevdev_grab_Call {
127+ _c.Call.Run(func(args mock.Arguments) {
128+ var arg0 int
129+ if args[0] != nil {
130+ arg0 = args[0].(int)
131+ }
132+ run(
133+ arg0,
134+ )
135+ })
136+ return _c
137+}
138+
139+func (_c *mockevdev_grab_Call) Return(err error) *mockevdev_grab_Call {
140+ _c.Call.Return(err)
141+ return _c
142+}
143+
144+func (_c *mockevdev_grab_Call) RunAndReturn(run func(fd int) error) *mockevdev_grab_Call {
145+ _c.Call.Return(run)
146+ return _c
147+}
148+
149+// open provides a mock function for the type mockevdev
150+func (_mock *mockevdev) open(path string) (int, error) {
151+ ret := _mock.Called(path)
152+
153+ if len(ret) == 0 {
154+ panic("no return value specified for open")
155+ }
156+
157+ var r0 int
158+ var r1 error
159+ if returnFunc, ok := ret.Get(0).(func(string) (int, error)); ok {
160+ return returnFunc(path)
161+ }
162+ if returnFunc, ok := ret.Get(0).(func(string) int); ok {
163+ r0 = returnFunc(path)
164+ } else {
165+ r0 = ret.Get(0).(int)
166+ }
167+ if returnFunc, ok := ret.Get(1).(func(string) error); ok {
168+ r1 = returnFunc(path)
169+ } else {
170+ r1 = ret.Error(1)
171+ }
172+ return r0, r1
173+}
174+
175+// mockevdev_open_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'open'
176+type mockevdev_open_Call struct {
177+ *mock.Call
178+}
179+
180+// open is a helper method to define mock.On call
181+// - path string
182+func (_e *mockevdev_Expecter) open(path any) *mockevdev_open_Call {
183+ return &mockevdev_open_Call{Call: _e.mock.On("open", path)}
184+}
185+
186+func (_c *mockevdev_open_Call) Run(run func(path string)) *mockevdev_open_Call {
187+ _c.Call.Run(func(args mock.Arguments) {
188+ var arg0 string
189+ if args[0] != nil {
190+ arg0 = args[0].(string)
191+ }
192+ run(
193+ arg0,
194+ )
195+ })
196+ return _c
197+}
198+
199+func (_c *mockevdev_open_Call) Return(n int, err error) *mockevdev_open_Call {
200+ _c.Call.Return(n, err)
201+ return _c
202+}
203+
204+func (_c *mockevdev_open_Call) RunAndReturn(run func(path string) (int, error)) *mockevdev_open_Call {
205+ _c.Call.Return(run)
206+ return _c
207+}
208+
209+// ungrab provides a mock function for the type mockevdev
210+func (_mock *mockevdev) ungrab(fd int) error {
211+ ret := _mock.Called(fd)
212+
213+ if len(ret) == 0 {
214+ panic("no return value specified for ungrab")
215+ }
216+
217+ var r0 error
218+ if returnFunc, ok := ret.Get(0).(func(int) error); ok {
219+ r0 = returnFunc(fd)
220+ } else {
221+ r0 = ret.Error(0)
222+ }
223+ return r0
224+}
225+
226+// mockevdev_ungrab_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ungrab'
227+type mockevdev_ungrab_Call struct {
228+ *mock.Call
229+}
230+
231+// ungrab is a helper method to define mock.On call
232+// - fd int
233+func (_e *mockevdev_Expecter) ungrab(fd any) *mockevdev_ungrab_Call {
234+ return &mockevdev_ungrab_Call{Call: _e.mock.On("ungrab", fd)}
235+}
236+
237+func (_c *mockevdev_ungrab_Call) Run(run func(fd int)) *mockevdev_ungrab_Call {
238+ _c.Call.Run(func(args mock.Arguments) {
239+ var arg0 int
240+ if args[0] != nil {
241+ arg0 = args[0].(int)
242+ }
243+ run(
244+ arg0,
245+ )
246+ })
247+ return _c
248+}
249+
250+func (_c *mockevdev_ungrab_Call) Return(err error) *mockevdev_ungrab_Call {
251+ _c.Call.Return(err)
252+ return _c
253+}
254+
255+func (_c *mockevdev_ungrab_Call) RunAndReturn(run func(fd int) error) *mockevdev_ungrab_Call {
256+ _c.Call.Return(run)
257+ return _c
258+}
M internal/adapters/launcher/session.go +40 -1
@@ -4,6 +4,7 @@ import (
44 "context"
55 "net"
66 "os/exec"
7+ "strings"
78 "time"
89
910 "bnema.dev/zerowrap"
@@ -35,14 +36,52 @@ func ExportSession(ctx context.Context, env []string, log zerowrap.Logger) {
3536
3637 // UnexportSession withdraws the displays from the systemd user manager on
3738 // exit, so services started after logout do not reach a dead display, and
38-// stops the portals that still hold them.
39+// stops the portals that still hold them. When another session has exported
40+// its own display since (a desktop/server handover), the variables and the
41+// portals are its own: they are left alone.
3942 func UnexportSession(env []string, log zerowrap.Logger) {
4043 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
4144 defer cancel()
45+ ours := envValue(env, "WAYLAND_DISPLAY")
46+ if current, ok := managerEnv(ctx, env, "WAYLAND_DISPLAY"); ok && current != "" && current != ours {
47+ log.Info().Str("ours", ours).Str("current", current).Msg("session unexport skipped: another session exported its display")
48+ return
49+ }
4250 runSystemctl(ctx, env, log, append([]string{"unset-environment"}, sessionVars...), "session unexport failed")
4351 runSystemctl(ctx, env, log, []string{"--no-block", "stop", portalUnits}, "portal stop failed")
4452 }
4553
54+// managerEnv reads key from the systemd user manager's environment ("" when
55+// unset); ok is false when it cannot be read.
56+func managerEnv(ctx context.Context, env []string, key string) (value string, ok bool) {
57+ path, err := childLookPath("systemctl", env)
58+ if err != nil {
59+ return "", false
60+ }
61+ cmd := exec.CommandContext(ctx, path, "--user", "show-environment")
62+ cmd.Env = env
63+ out, err := cmd.Output()
64+ if err != nil {
65+ return "", false
66+ }
67+ for line := range strings.SplitSeq(string(out), "\n") {
68+ if v, found := strings.CutPrefix(line, key+"="); found {
69+ return v, true
70+ }
71+ }
72+ return "", true
73+}
74+
75+// envValue is key's value in env, "" when absent.
76+func envValue(env []string, key string) string {
77+ for i := len(env) - 1; i >= 0; i-- {
78+ if v, found := strings.CutPrefix(env[i], key+"="); found {
79+ return v
80+ }
81+ }
82+ return ""
83+}
84+
4685 // runSystemctl runs systemctl --user with args; a missing systemctl is skipped.
4786 func runSystemctl(ctx context.Context, env []string, log zerowrap.Logger, args []string, failed string) {
4887 path, err := childLookPath("systemctl", env)
@@ -4,6 +4,7 @@ import (
4 "context"4 "context"
5 "net"5 "net"
6 "os/exec"6 "os/exec"
7+ "strings"
7 "time"8 "time"
8 9
9 "bnema.dev/zerowrap"10 "bnema.dev/zerowrap"
@@ -35,14 +36,52 @@ func ExportSession(ctx context.Context, env []string, log zerowrap.Logger) {
35 36
36 // UnexportSession withdraws the displays from the systemd user manager on37 // UnexportSession withdraws the displays from the systemd user manager on
37 // exit, so services started after logout do not reach a dead display, and38 // exit, so services started after logout do not reach a dead display, and
38-// stops the portals that still hold them.39+// stops the portals that still hold them. When another session has exported
40+// its own display since (a desktop/server handover), the variables and the
41+// portals are its own: they are left alone.
39 func UnexportSession(env []string, log zerowrap.Logger) {42 func UnexportSession(env []string, log zerowrap.Logger) {
40 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)43 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
41 defer cancel()44 defer cancel()
45+ ours := envValue(env, "WAYLAND_DISPLAY")
46+ if current, ok := managerEnv(ctx, env, "WAYLAND_DISPLAY"); ok && current != "" && current != ours {
47+ log.Info().Str("ours", ours).Str("current", current).Msg("session unexport skipped: another session exported its display")
48+ return
49+ }
42 runSystemctl(ctx, env, log, append([]string{"unset-environment"}, sessionVars...), "session unexport failed")50 runSystemctl(ctx, env, log, append([]string{"unset-environment"}, sessionVars...), "session unexport failed")
43 runSystemctl(ctx, env, log, []string{"--no-block", "stop", portalUnits}, "portal stop failed")51 runSystemctl(ctx, env, log, []string{"--no-block", "stop", portalUnits}, "portal stop failed")
44 }52 }
45 53
54+// managerEnv reads key from the systemd user manager's environment ("" when
55+// unset); ok is false when it cannot be read.
56+func managerEnv(ctx context.Context, env []string, key string) (value string, ok bool) {
57+ path, err := childLookPath("systemctl", env)
58+ if err != nil {
59+ return "", false
60+ }
61+ cmd := exec.CommandContext(ctx, path, "--user", "show-environment")
62+ cmd.Env = env
63+ out, err := cmd.Output()
64+ if err != nil {
65+ return "", false
66+ }
67+ for line := range strings.SplitSeq(string(out), "\n") {
68+ if v, found := strings.CutPrefix(line, key+"="); found {
69+ return v, true
70+ }
71+ }
72+ return "", true
73+}
74+
75+// envValue is key's value in env, "" when absent.
76+func envValue(env []string, key string) string {
77+ for i := len(env) - 1; i >= 0; i-- {
78+ if v, found := strings.CutPrefix(env[i], key+"="); found {
79+ return v
80+ }
81+ }
82+ return ""
83+}
84+
46 // runSystemctl runs systemctl --user with args; a missing systemctl is skipped.85 // runSystemctl runs systemctl --user with args; a missing systemctl is skipped.
47 func runSystemctl(ctx context.Context, env []string, log zerowrap.Logger, args []string, failed string) {86 func runSystemctl(ctx context.Context, env []string, log zerowrap.Logger, args []string, failed string) {
48 path, err := childLookPath("systemctl", env)87 path, err := childLookPath("systemctl", env)
M internal/adapters/launcher/session_test.go +33 -1
@@ -17,7 +17,8 @@ import (
1717 func TestExportSession(t *testing.T) {
1818 dir := t.TempDir()
1919 out := filepath.Join(dir, "calls")
20- script := "#!/bin/sh\necho \"${0##*/} $* $WAYLAND_DISPLAY\" >> " + out + "\n"
20+ // show-environment reports this session's display: it is still ours.
21+ script := "#!/bin/sh\nif [ \"$2\" = show-environment ]; then echo WAYLAND_DISPLAY=$WAYLAND_DISPLAY; exit 0; fi\necho \"${0##*/} $* $WAYLAND_DISPLAY\" >> " + out + "\n"
2122 for _, name := range []string{"dbus-update-activation-environment", "systemctl"} {
2223 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil {
2324 t.Fatal(err)
@@ -45,6 +46,37 @@ func TestExportSession(t *testing.T) {
4546 }
4647 }
4748
49+// handoverCalls runs UnexportSession for wayland-1 against a user manager
50+// whose environment is shown, and returns the other systemctl calls.
51+func handoverCalls(t *testing.T, shown string) string {
52+ t.Helper()
53+ dir := t.TempDir()
54+ out := filepath.Join(dir, "calls")
55+ script := "#!/bin/sh\nif [ \"$2\" = show-environment ]; then printf '" + shown + "'; exit 0; fi\necho \"$*\" >> " + out + "\n"
56+ if err := os.WriteFile(filepath.Join(dir, "systemctl"), []byte(script), 0o755); err != nil {
57+ t.Fatal(err)
58+ }
59+ ctx := context.Background()
60+ UnexportSession([]string{"PATH=" + dir, "WAYLAND_DISPLAY=wayland-1"}, logging.For(ctx, "launcher"))
61+ data, _ := os.ReadFile(out)
62+ return string(data)
63+}
64+
65+// A session stopping after another exported its display leaves the other's
66+// variables and portals alone; its own (or none left) are withdrawn.
67+func TestUnexportSessionOnlyOurs(t *testing.T) {
68+ if got := handoverCalls(t, `HOME=/h\nWAYLAND_DISPLAY=wayland-2\nDISPLAY=:1\n`); got != "" {
69+ t.Errorf("another session's display: calls %q, want none", got)
70+ }
71+ want := "--user unset-environment WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE\n--user --no-block stop xdg-desktop-portal*.service\n"
72+ if got := handoverCalls(t, `HOME=/h\nWAYLAND_DISPLAY=wayland-1\n`); got != want {
73+ t.Errorf("our display: calls %q, want %q", got, want)
74+ }
75+ if got := handoverCalls(t, `HOME=/h\n`); got != want {
76+ t.Errorf("no display exported: calls %q, want %q", got, want)
77+ }
78+}
79+
4880 // A failed export restarts no portal: it would read the old variables again.
4981 func TestExportSessionFailedSkipsPortals(t *testing.T) {
5082 dir := t.TempDir()
@@ -17,7 +17,8 @@ import (
17 func TestExportSession(t *testing.T) {17 func TestExportSession(t *testing.T) {
18 dir := t.TempDir()18 dir := t.TempDir()
19 out := filepath.Join(dir, "calls")19 out := filepath.Join(dir, "calls")
20- script := "#!/bin/sh\necho \"${0##*/} $* $WAYLAND_DISPLAY\" >> " + out + "\n"20+ // show-environment reports this session's display: it is still ours.
21+ script := "#!/bin/sh\nif [ \"$2\" = show-environment ]; then echo WAYLAND_DISPLAY=$WAYLAND_DISPLAY; exit 0; fi\necho \"${0##*/} $* $WAYLAND_DISPLAY\" >> " + out + "\n"
21 for _, name := range []string{"dbus-update-activation-environment", "systemctl"} {22 for _, name := range []string{"dbus-update-activation-environment", "systemctl"} {
22 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil {23 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil {
23 t.Fatal(err)24 t.Fatal(err)
@@ -45,6 +46,37 @@ func TestExportSession(t *testing.T) {
45 }46 }
46 }47 }
47 48
49+// handoverCalls runs UnexportSession for wayland-1 against a user manager
50+// whose environment is shown, and returns the other systemctl calls.
51+func handoverCalls(t *testing.T, shown string) string {
52+ t.Helper()
53+ dir := t.TempDir()
54+ out := filepath.Join(dir, "calls")
55+ script := "#!/bin/sh\nif [ \"$2\" = show-environment ]; then printf '" + shown + "'; exit 0; fi\necho \"$*\" >> " + out + "\n"
56+ if err := os.WriteFile(filepath.Join(dir, "systemctl"), []byte(script), 0o755); err != nil {
57+ t.Fatal(err)
58+ }
59+ ctx := context.Background()
60+ UnexportSession([]string{"PATH=" + dir, "WAYLAND_DISPLAY=wayland-1"}, logging.For(ctx, "launcher"))
61+ data, _ := os.ReadFile(out)
62+ return string(data)
63+}
64+
65+// A session stopping after another exported its display leaves the other's
66+// variables and portals alone; its own (or none left) are withdrawn.
67+func TestUnexportSessionOnlyOurs(t *testing.T) {
68+ if got := handoverCalls(t, `HOME=/h\nWAYLAND_DISPLAY=wayland-2\nDISPLAY=:1\n`); got != "" {
69+ t.Errorf("another session's display: calls %q, want none", got)
70+ }
71+ want := "--user unset-environment WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE\n--user --no-block stop xdg-desktop-portal*.service\n"
72+ if got := handoverCalls(t, `HOME=/h\nWAYLAND_DISPLAY=wayland-1\n`); got != want {
73+ t.Errorf("our display: calls %q, want %q", got, want)
74+ }
75+ if got := handoverCalls(t, `HOME=/h\n`); got != want {
76+ t.Errorf("no display exported: calls %q, want %q", got, want)
77+ }
78+}
79+
48 // A failed export restarts no portal: it would read the old variables again.80 // A failed export restarts no portal: it would read the old variables again.
49 func TestExportSessionFailedSkipsPortals(t *testing.T) {81 func TestExportSessionFailedSkipsPortals(t *testing.T) {
50 dir := t.TempDir()82 dir := t.TempDir()
M internal/adapters/outputkit/headlessbackend/backend.go +6 -2
@@ -27,6 +27,7 @@ type BackendOptions struct {
2727 }
2828
2929 // Run drives one virtual output per size, named HEADLESS-1, -2, ...
30+// Sizes may be empty: then only config-declared virtual outputs exist.
3031 // With several outputs, screenshots go to a subdirectory per output. Modes
3132 // of built-in heads are fixed; config-declared outputs reconcile through apply.
3233 //
@@ -73,8 +74,11 @@ func Run(ctx context.Context, o BackendOptions, apply *core.OutputApply, ch rout
7374 if set.State.Protected {
7475 set.SecurityEvent(ports.SecurityBackendBarrier{Generation: set.State.Generation})
7576 }
76- // The pointer starts centred on the first output, like libinput's.
77- curs.Move("HEADLESS-1", float64(o.Sizes[0][0])/2, float64(o.Sizes[0][1])/2, false)
77+ // The pointer starts centred on the first output, like libinput's. With
78+ // virtual outputs only, there is no fixed head to centre on.
79+ if len(o.Sizes) > 0 {
80+ curs.Move("HEADLESS-1", float64(o.Sizes[0][0])/2, float64(o.Sizes[0][1])/2, false)
81+ }
7882 for {
7983 if _, ok := apply.Next(); ok {
8084 err := host.Sync(ctx, apply.Virtuals())
@@ -27,6 +27,7 @@ type BackendOptions struct {
27 }27 }
28 28
29 // Run drives one virtual output per size, named HEADLESS-1, -2, ...29 // Run drives one virtual output per size, named HEADLESS-1, -2, ...
30+// Sizes may be empty: then only config-declared virtual outputs exist.
30 // With several outputs, screenshots go to a subdirectory per output. Modes31 // With several outputs, screenshots go to a subdirectory per output. Modes
31 // of built-in heads are fixed; config-declared outputs reconcile through apply.32 // of built-in heads are fixed; config-declared outputs reconcile through apply.
32 //33 //
@@ -73,8 +74,11 @@ func Run(ctx context.Context, o BackendOptions, apply *core.OutputApply, ch rout
73 if set.State.Protected {74 if set.State.Protected {
74 set.SecurityEvent(ports.SecurityBackendBarrier{Generation: set.State.Generation})75 set.SecurityEvent(ports.SecurityBackendBarrier{Generation: set.State.Generation})
75 }76 }
76- // The pointer starts centred on the first output, like libinput's.77+ // The pointer starts centred on the first output, like libinput's. With
77- curs.Move("HEADLESS-1", float64(o.Sizes[0][0])/2, float64(o.Sizes[0][1])/2, false)78+ // virtual outputs only, there is no fixed head to centre on.
79+ if len(o.Sizes) > 0 {
80+ curs.Move("HEADLESS-1", float64(o.Sizes[0][0])/2, float64(o.Sizes[0][1])/2, false)
81+ }
78 for {82 for {
79 if _, ok := apply.Next(); ok {83 if _, ok := apply.Next(); ok {
80 err := host.Sync(ctx, apply.Virtuals())84 err := host.Sync(ctx, apply.Virtuals())
M internal/adapters/outputkit/headlessbackend/backend_test.go +27 -0
@@ -59,3 +59,30 @@ func TestVirtualReloadInventory(t *testing.T) {
5959 }
6060 })
6161 }
62+
63+func TestVirtualOnlyNoFixedHeads(t *testing.T) {
64+ synctest.Test(t, func(t *testing.T) {
65+ ctx, cancel := context.WithCancel(context.Background())
66+ defer cancel()
67+ file := domain.Config{Outputs: []domain.OutputConfig{{Name: "tv", Virtual: true, Mode: "10x10"}}}
68+ apply := core.NewOutputApply(core.NewOutputOverrides(file, true))
69+ events := make(chan ports.OutputEvent, 16)
70+ heads := make(chan domain.OutputHeads, 16)
71+ ch := routing.Channels{Events: events, Heads: heads, Reloads: make(chan domain.ConfigChanged)}
72+ r := portsmocks.NewMockRenderer(t)
73+ r.EXPECT().Close().Return().Maybe()
74+ done := make(chan error, 1)
75+ go func() {
76+ done <- Run(ctx, BackendOptions{}, apply, ch, cursors.New(nil, 0), func(int, int) (ports.Renderer, error) { return r, nil }, logging.For(ctx, "render"))
77+ }()
78+ inventory := <-heads
79+ if len(inventory.Heads) != 1 || inventory.Heads[0].Info.Name != "tv" || !inventory.Heads[0].Info.Virtual {
80+ t.Fatal(inventory)
81+ }
82+ synctest.Wait()
83+ cancel()
84+ if err := <-done; err != nil {
85+ t.Fatal(err)
86+ }
87+ })
88+}
@@ -59,3 +59,30 @@ func TestVirtualReloadInventory(t *testing.T) {
59 }59 }
60 })60 })
61 }61 }
62+
63+func TestVirtualOnlyNoFixedHeads(t *testing.T) {
64+ synctest.Test(t, func(t *testing.T) {
65+ ctx, cancel := context.WithCancel(context.Background())
66+ defer cancel()
67+ file := domain.Config{Outputs: []domain.OutputConfig{{Name: "tv", Virtual: true, Mode: "10x10"}}}
68+ apply := core.NewOutputApply(core.NewOutputOverrides(file, true))
69+ events := make(chan ports.OutputEvent, 16)
70+ heads := make(chan domain.OutputHeads, 16)
71+ ch := routing.Channels{Events: events, Heads: heads, Reloads: make(chan domain.ConfigChanged)}
72+ r := portsmocks.NewMockRenderer(t)
73+ r.EXPECT().Close().Return().Maybe()
74+ done := make(chan error, 1)
75+ go func() {
76+ done <- Run(ctx, BackendOptions{}, apply, ch, cursors.New(nil, 0), func(int, int) (ports.Renderer, error) { return r, nil }, logging.For(ctx, "render"))
77+ }()
78+ inventory := <-heads
79+ if len(inventory.Heads) != 1 || inventory.Heads[0].Info.Name != "tv" || !inventory.Heads[0].Info.Virtual {
80+ t.Fatal(inventory)
81+ }
82+ synctest.Wait()
83+ cancel()
84+ if err := <-done; err != nil {
85+ t.Fatal(err)
86+ }
87+ })
88+}
M internal/app/app.go +6 -2
@@ -21,7 +21,7 @@ import (
2121 )
2222
2323 type Options struct {
24- Backend string
24+ Backend domain.Backend
2525 Config domain.Config
2626 ConfigPath string
2727 Timeout time.Duration
@@ -56,13 +56,17 @@ type Options struct {
5656 // castInventoryApplied (tests) is signalled after each screencast
5757 // inventory the D-Bus service applied.
5858 castInventoryApplied chan<- struct{}
59+ // noLibinput (tests) keeps a libinput backend from opening real devices:
60+ // the inject channel drives input instead. A grab would steal the
61+ // developer's keyboard.
62+ noLibinput bool
5963 }
6064
6165 func Run(ctx context.Context, opts Options) error { return run(ctx, opts, nil) }
6266
6367 func run(ctx context.Context, opts Options, inject func(chan<- ports.InputEvent)) error {
6468 log := logging.For(ctx, "app")
65- log.Info().Str("backend", opts.Backend).Msg("starting neferwl")
69+ log.Info().Str("backend", string(opts.Backend)).Msg("starting neferwl")
6670 var cancel context.CancelFunc
6771 if opts.Timeout > 0 {
6872 ctx, cancel = context.WithTimeoutCause(ctx, opts.Timeout, errTimeout)
@@ -21,7 +21,7 @@ import (
21 )21 )
22 22
23 type Options struct {23 type Options struct {
24- Backend string24+ Backend domain.Backend
25 Config domain.Config25 Config domain.Config
26 ConfigPath string26 ConfigPath string
27 Timeout time.Duration27 Timeout time.Duration
@@ -56,13 +56,17 @@ type Options struct {
56 // castInventoryApplied (tests) is signalled after each screencast56 // castInventoryApplied (tests) is signalled after each screencast
57 // inventory the D-Bus service applied.57 // inventory the D-Bus service applied.
58 castInventoryApplied chan<- struct{}58 castInventoryApplied chan<- struct{}
59+ // noLibinput (tests) keeps a libinput backend from opening real devices:
60+ // the inject channel drives input instead. A grab would steal the
61+ // developer's keyboard.
62+ noLibinput bool
59 }63 }
60 64
61 func Run(ctx context.Context, opts Options) error { return run(ctx, opts, nil) }65 func Run(ctx context.Context, opts Options) error { return run(ctx, opts, nil) }
62 66
63 func run(ctx context.Context, opts Options, inject func(chan<- ports.InputEvent)) error {67 func run(ctx context.Context, opts Options, inject func(chan<- ports.InputEvent)) error {
64 log := logging.For(ctx, "app")68 log := logging.For(ctx, "app")
65- log.Info().Str("backend", opts.Backend).Msg("starting neferwl")69+ log.Info().Str("backend", string(opts.Backend)).Msg("starting neferwl")
66 var cancel context.CancelFunc70 var cancel context.CancelFunc
67 if opts.Timeout > 0 {71 if opts.Timeout > 0 {
68 ctx, cancel = context.WithTimeoutCause(ctx, opts.Timeout, errTimeout)72 ctx, cancel = context.WithTimeoutCause(ctx, opts.Timeout, errTimeout)
M internal/app/gpuopen.go +19 -1
@@ -32,6 +32,24 @@ func openPlannedRender(opener ports.RenderDeviceOpener, plans []core.CardPlan, s
3232
3333 // openHeadlessRender executes core policy, keeping filesystem probes at the edge.
3434 func openHeadlessRender(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, log zerowrap.Logger) (ports.RenderDevice, error) {
35+ return openHeadlessRenderPolicy(opener, cands, listErr, cfg, env, false, log)
36+}
37+
38+// openHeadlessRenderPolicy is openHeadlessRender; requireRenderNode rejects
39+// devices without a DRM render node (software rasterizers such as lavapipe).
40+func openHeadlessRenderPolicy(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, requireRenderNode bool, log zerowrap.Logger) (ports.RenderDevice, error) {
41+ dev, err := openHeadlessRenderDevice(opener, cands, listErr, cfg, env, requireRenderNode, log)
42+ if err != nil || !requireRenderNode {
43+ return dev, err
44+ }
45+ if _, render := dev.Node(); render == 0 {
46+ dev.Close()
47+ return nil, fmt.Errorf("headless render: a hardware render node is required: %w", core.ErrNoRenderNode)
48+ }
49+ return dev, nil
50+}
51+
52+func openHeadlessRenderDevice(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, requireRenderNode bool, log zerowrap.Logger) (ports.RenderDevice, error) {
3553 constrained := len(cfg.DRM.Devices) > 0 || len(cfg.DRM.Ignore) > 0 || cfg.Render.Device != "" || env != ""
3654 fallback := func(reason error) (ports.RenderDevice, error) {
3755 log.Info().Err(reason).Msg("render GPU: first usable Vulkan device (headless discovery fallback)")
@@ -50,7 +68,7 @@ func openHeadlessRender(opener ports.RenderDeviceOpener, cands []domain.GPUInfo,
5068 }
5169 }
5270 }
53- decision := core.PlanHeadlessRender(cands, listErr, config, constrained, matched)
71+ decision := core.PlanHeadlessRender(cands, listErr, config, constrained, matched, requireRenderNode)
5472 switch decision.Choice {
5573 case core.HeadlessUseExplicitRenderNode:
5674 var st unix.Stat_t
@@ -32,6 +32,24 @@ func openPlannedRender(opener ports.RenderDeviceOpener, plans []core.CardPlan, s
32 32
33 // openHeadlessRender executes core policy, keeping filesystem probes at the edge.33 // openHeadlessRender executes core policy, keeping filesystem probes at the edge.
34 func openHeadlessRender(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, log zerowrap.Logger) (ports.RenderDevice, error) {34 func openHeadlessRender(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, log zerowrap.Logger) (ports.RenderDevice, error) {
35+ return openHeadlessRenderPolicy(opener, cands, listErr, cfg, env, false, log)
36+}
37+
38+// openHeadlessRenderPolicy is openHeadlessRender; requireRenderNode rejects
39+// devices without a DRM render node (software rasterizers such as lavapipe).
40+func openHeadlessRenderPolicy(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, requireRenderNode bool, log zerowrap.Logger) (ports.RenderDevice, error) {
41+ dev, err := openHeadlessRenderDevice(opener, cands, listErr, cfg, env, requireRenderNode, log)
42+ if err != nil || !requireRenderNode {
43+ return dev, err
44+ }
45+ if _, render := dev.Node(); render == 0 {
46+ dev.Close()
47+ return nil, fmt.Errorf("headless render: a hardware render node is required: %w", core.ErrNoRenderNode)
48+ }
49+ return dev, nil
50+}
51+
52+func openHeadlessRenderDevice(opener ports.RenderDeviceOpener, cands []domain.GPUInfo, listErr error, cfg domain.Config, env string, requireRenderNode bool, log zerowrap.Logger) (ports.RenderDevice, error) {
35 constrained := len(cfg.DRM.Devices) > 0 || len(cfg.DRM.Ignore) > 0 || cfg.Render.Device != "" || env != ""53 constrained := len(cfg.DRM.Devices) > 0 || len(cfg.DRM.Ignore) > 0 || cfg.Render.Device != "" || env != ""
36 fallback := func(reason error) (ports.RenderDevice, error) {54 fallback := func(reason error) (ports.RenderDevice, error) {
37 log.Info().Err(reason).Msg("render GPU: first usable Vulkan device (headless discovery fallback)")55 log.Info().Err(reason).Msg("render GPU: first usable Vulkan device (headless discovery fallback)")
@@ -50,7 +68,7 @@ func openHeadlessRender(opener ports.RenderDeviceOpener, cands []domain.GPUInfo,
50 }68 }
51 }69 }
52 }70 }
53- decision := core.PlanHeadlessRender(cands, listErr, config, constrained, matched)71+ decision := core.PlanHeadlessRender(cands, listErr, config, constrained, matched, requireRenderNode)
54 switch decision.Choice {72 switch decision.Choice {
55 case core.HeadlessUseExplicitRenderNode:73 case core.HeadlessUseExplicitRenderNode:
56 var st unix.Stat_t74 var st unix.Stat_t
M internal/app/gpuopen_test.go +32 -0
@@ -5,6 +5,7 @@ import (
55 "strings"
66 "testing"
77
8+ "github.com/bnema/neferwl/internal/core"
89 "github.com/bnema/neferwl/internal/domain"
910 portsmocks "github.com/bnema/neferwl/internal/mocks/ports"
1011 "bnema.dev/zerowrap"
@@ -58,3 +59,34 @@ func TestOpenHeadlessRenderDiscovery(t *testing.T) {
5859 })
5960 }
6061 }
62+
63+func TestOpenHeadlessRenderRequireNode(t *testing.T) {
64+ gpu := domain.GPUInfo{Path: "card0", Render: 1}
65+ t.Run("no fallback", func(t *testing.T) {
66+ opener := portsmocks.NewMockRenderDeviceOpener(t)
67+ if _, err := openHeadlessRenderPolicy(opener, nil, nil, domain.Config{}, "", true, zerowrap.Logger{}); err == nil {
68+ t.Fatal("fallback used")
69+ }
70+ })
71+ t.Run("software device", func(t *testing.T) {
72+ opener := portsmocks.NewMockRenderDeviceOpener(t)
73+ dev := portsmocks.NewMockRenderDevice(t)
74+ opener.EXPECT().Open(gpu).Return(dev, nil).Once()
75+ dev.EXPECT().Node().Return(0, 0).Once()
76+ dev.EXPECT().Close().Return().Once()
77+ _, err := openHeadlessRenderPolicy(opener, []domain.GPUInfo{gpu}, nil, domain.Config{}, "", true, zerowrap.Logger{})
78+ if !errors.Is(err, core.ErrNoRenderNode) || !strings.Contains(err.Error(), "render node") {
79+ t.Fatal(err)
80+ }
81+ })
82+ t.Run("hardware device", func(t *testing.T) {
83+ opener := portsmocks.NewMockRenderDeviceOpener(t)
84+ dev := portsmocks.NewMockRenderDevice(t)
85+ opener.EXPECT().Open(gpu).Return(dev, nil).Once()
86+ dev.EXPECT().Node().Return(0, 1).Once()
87+ got, err := openHeadlessRenderPolicy(opener, []domain.GPUInfo{gpu}, nil, domain.Config{}, "", true, zerowrap.Logger{})
88+ if err != nil || got != dev {
89+ t.Fatal(got, err)
90+ }
91+ })
92+}
@@ -5,6 +5,7 @@ import (
5 "strings"5 "strings"
6 "testing"6 "testing"
7 7
8+ "github.com/bnema/neferwl/internal/core"
8 "github.com/bnema/neferwl/internal/domain"9 "github.com/bnema/neferwl/internal/domain"
9 portsmocks "github.com/bnema/neferwl/internal/mocks/ports"10 portsmocks "github.com/bnema/neferwl/internal/mocks/ports"
10 "bnema.dev/zerowrap"11 "bnema.dev/zerowrap"
@@ -58,3 +59,34 @@ func TestOpenHeadlessRenderDiscovery(t *testing.T) {
58 })59 })
59 }60 }
60 }61 }
62+
63+func TestOpenHeadlessRenderRequireNode(t *testing.T) {
64+ gpu := domain.GPUInfo{Path: "card0", Render: 1}
65+ t.Run("no fallback", func(t *testing.T) {
66+ opener := portsmocks.NewMockRenderDeviceOpener(t)
67+ if _, err := openHeadlessRenderPolicy(opener, nil, nil, domain.Config{}, "", true, zerowrap.Logger{}); err == nil {
68+ t.Fatal("fallback used")
69+ }
70+ })
71+ t.Run("software device", func(t *testing.T) {
72+ opener := portsmocks.NewMockRenderDeviceOpener(t)
73+ dev := portsmocks.NewMockRenderDevice(t)
74+ opener.EXPECT().Open(gpu).Return(dev, nil).Once()
75+ dev.EXPECT().Node().Return(0, 0).Once()
76+ dev.EXPECT().Close().Return().Once()
77+ _, err := openHeadlessRenderPolicy(opener, []domain.GPUInfo{gpu}, nil, domain.Config{}, "", true, zerowrap.Logger{})
78+ if !errors.Is(err, core.ErrNoRenderNode) || !strings.Contains(err.Error(), "render node") {
79+ t.Fatal(err)
80+ }
81+ })
82+ t.Run("hardware device", func(t *testing.T) {
83+ opener := portsmocks.NewMockRenderDeviceOpener(t)
84+ dev := portsmocks.NewMockRenderDevice(t)
85+ opener.EXPECT().Open(gpu).Return(dev, nil).Once()
86+ dev.EXPECT().Node().Return(0, 1).Once()
87+ got, err := openHeadlessRenderPolicy(opener, []domain.GPUInfo{gpu}, nil, domain.Config{}, "", true, zerowrap.Logger{})
88+ if err != nil || got != dev {
89+ t.Fatal(got, err)
90+ }
91+ })
92+}
M internal/app/screencast_test.go +105 -2
@@ -64,10 +64,23 @@ func startCastApp(t *testing.T, allow string) *castApp {
6464 // startCastAppConfig runs the compositor with cfg and the capture allowlist
6565 // content. The PipeWire socket stays where it is: only the Wayland socket
6666 // and the state move to temporary directories.
67+func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp {
68+ t.Helper()
69+ return startCastAppBackend(t, allow, cfg, domain.BackendHeadless)
70+}
71+
72+// startCastAppBackend is startCastAppConfig on backend. The server backend
73+// has no fixed head (only cfg's virtual outputs), always serves the session
74+// bus and never runs libinput here (noLibinput).
6775 //
6876 //testpolicy:realtime real headless renderer and D-Bus service startup and teardown
69-func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp {
77+func startCastAppBackend(t *testing.T, allow string, cfg domain.Config, backend domain.Backend) *castApp {
7078 t.Helper()
79+ server := backend == domain.BackendServer
80+ sizes := [][2]int{{320, 240}}
81+ if server {
82+ sizes = nil
83+ }
7184 t.Setenv("PIPEWIRE_RUNTIME_DIR", os.Getenv("XDG_RUNTIME_DIR"))
7285 t.Setenv("XDG_RUNTIME_DIR", t.TempDir())
7386 t.Setenv("XDG_STATE_HOME", t.TempDir())
@@ -81,7 +94,7 @@ func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp
8194 inputReady := make(chan chan<- ports.InputEvent, 1)
8295 done := make(chan error, 1)
8396 go func() {
84- done <- run(ctx, Options{Backend: "headless", DBus: true, NoXwayland: true, NoTerminal: true, Config: cfg, Sizes: [][2]int{{320, 240}}, captureAllowPath: allowPath, captureAllowOwner: uint32(os.Getuid()), castInventoryApplied: inventory},
97+ done <- run(ctx, Options{Backend: backend, DBus: !server, NoXwayland: true, NoTerminal: true, Config: cfg, Sizes: sizes, noLibinput: server, captureAllowPath: allowPath, captureAllowOwner: uint32(os.Getuid()), castInventoryApplied: inventory},
8598 func(in chan<- ports.InputEvent) { inputReady <- in })
8699 }()
87100 a := &castApp{inventory: inventory}
@@ -523,6 +536,96 @@ func waitFrames(t *testing.T, frames *atomic.Int64, changed <-chan struct{}, exi
523536 }
524537 }
525538
539+// TestServerScreencastVirtualOutput: the server backend serves the cast
540+// service without --dbus and streams its virtual output to a PipeWire
541+// consumer.
542+//
543+//testpolicy:realtime real PipeWire/GStreamer frames and D-Bus lifecycle
544+func TestServerScreencastVirtualOutput(t *testing.T) {
545+ requireCastEnv(t)
546+ cfg := config.Defaults()
547+ cfg.Outputs = append(cfg.Outputs, domain.OutputConfig{Name: "tv", Virtual: true, Mode: "320x240"})
548+ app := startCastAppBackend(t, "*\n", cfg, domain.BackendServer)
549+ c := castClient(t)
550+ waitOwner(t, c, scName)
551+ var session, stream string
552+ timeout := time.After(15 * time.Second)
553+ for {
554+ name, m := call(c, scPath, "org.gnome.Mutter.ScreenCast", "CreateSession", "a{sv}", emptyProps)
555+ if name != "" {
556+ t.Fatalf("CreateSession: %s", name)
557+ }
558+ session = strings.Clone(m.Body().ObjectPath())
559+ var errName string
560+ if errName, stream = recordMonitor(c, session, "tv"); errName == "" {
561+ break
562+ }
563+ call(c, session, scSession, "Stop", "", nil)
564+ select {
565+ case <-timeout:
566+ t.Fatalf("RecordMonitor tv: %s", errName)
567+ case <-app.inventory:
568+ }
569+ }
570+ if err := c.AddMatch("type='signal',interface='" + scStream + "'"); err != nil {
571+ t.Fatal(err)
572+ }
573+ if name, _ := call(c, session, scSession, "Start", "", nil); name != "" {
574+ t.Fatalf("Start: %s", name)
575+ }
576+ node := uint32(0)
577+ for node == 0 {
578+ m, err := c.ReadMessage()
579+ if err != nil {
580+ t.Fatal(err)
581+ }
582+ if m.Member == "PipeWireStreamAdded" && m.Path == stream && m.Destination == c.UniqueName() {
583+ node = m.Body().Uint32()
584+ }
585+ }
586+ // Pointer motion (an unbound device reaches the placed virtual output)
587+ // damages the output while the consumer runs.
588+ stop := make(chan struct{})
589+ moved := make(chan struct{})
590+ go func() {
591+ defer close(moved)
592+ tick := time.NewTicker(16 * time.Millisecond)
593+ defer tick.Stop()
594+ for i := 0; ; i++ {
595+ ev := ports.InputEvent(ports.SecurityInput{Event: ports.PointerMotion{X: float64(40 + 120*(i%2)), Y: 40}})
596+ select {
597+ case app.input <- ev:
598+ case <-stop:
599+ return
600+ }
601+ select {
602+ case <-tick.C:
603+ case <-stop:
604+ return
605+ }
606+ }
607+ }()
608+ defer func() { close(stop); <-moved }()
609+ gst := exec.Command("gst-launch-1.0", "pipewiresrc", "path="+itoa(node), "stream-properties=props,media.type=Video", "num-buffers=30", "!", "fakesink")
610+ exited := make(chan error, 1)
611+ if err := gst.Start(); err != nil {
612+ t.Fatal(err)
613+ }
614+ go func() { exited <- gst.Wait() }()
615+ select {
616+ case err := <-exited:
617+ if err != nil {
618+ t.Errorf("gst-launch-1.0: %v", err)
619+ }
620+ case <-time.After(30 * time.Second):
621+ _ = gst.Process.Kill()
622+ t.Fatal("gst-launch-1.0 did not receive 30 buffers")
623+ }
624+ if name, _ := call(c, session, scSession, "Stop", "", nil); name != "" {
625+ t.Fatalf("Stop: %s", name)
626+ }
627+}
628+
526629 // castRaceEnabled keeps the real-I/O lifecycle running with -race, but disables
527630 // allocation assertions: purego's sync.Pool drops argument storage under race.
528631 func castRaceEnabled() bool {
@@ -64,10 +64,23 @@ func startCastApp(t *testing.T, allow string) *castApp {
64 // startCastAppConfig runs the compositor with cfg and the capture allowlist64 // startCastAppConfig runs the compositor with cfg and the capture allowlist
65 // content. The PipeWire socket stays where it is: only the Wayland socket65 // content. The PipeWire socket stays where it is: only the Wayland socket
66 // and the state move to temporary directories.66 // and the state move to temporary directories.
67+func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp {
68+ t.Helper()
69+ return startCastAppBackend(t, allow, cfg, domain.BackendHeadless)
70+}
71+
72+// startCastAppBackend is startCastAppConfig on backend. The server backend
73+// has no fixed head (only cfg's virtual outputs), always serves the session
74+// bus and never runs libinput here (noLibinput).
67 //75 //
68 //testpolicy:realtime real headless renderer and D-Bus service startup and teardown76 //testpolicy:realtime real headless renderer and D-Bus service startup and teardown
69-func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp {77+func startCastAppBackend(t *testing.T, allow string, cfg domain.Config, backend domain.Backend) *castApp {
70 t.Helper()78 t.Helper()
79+ server := backend == domain.BackendServer
80+ sizes := [][2]int{{320, 240}}
81+ if server {
82+ sizes = nil
83+ }
71 t.Setenv("PIPEWIRE_RUNTIME_DIR", os.Getenv("XDG_RUNTIME_DIR"))84 t.Setenv("PIPEWIRE_RUNTIME_DIR", os.Getenv("XDG_RUNTIME_DIR"))
72 t.Setenv("XDG_RUNTIME_DIR", t.TempDir())85 t.Setenv("XDG_RUNTIME_DIR", t.TempDir())
73 t.Setenv("XDG_STATE_HOME", t.TempDir())86 t.Setenv("XDG_STATE_HOME", t.TempDir())
@@ -81,7 +94,7 @@ func startCastAppConfig(t *testing.T, allow string, cfg domain.Config) *castApp
81 inputReady := make(chan chan<- ports.InputEvent, 1)94 inputReady := make(chan chan<- ports.InputEvent, 1)
82 done := make(chan error, 1)95 done := make(chan error, 1)
83 go func() {96 go func() {
84- done <- run(ctx, Options{Backend: "headless", DBus: true, NoXwayland: true, NoTerminal: true, Config: cfg, Sizes: [][2]int{{320, 240}}, captureAllowPath: allowPath, captureAllowOwner: uint32(os.Getuid()), castInventoryApplied: inventory},97+ done <- run(ctx, Options{Backend: backend, DBus: !server, NoXwayland: true, NoTerminal: true, Config: cfg, Sizes: sizes, noLibinput: server, captureAllowPath: allowPath, captureAllowOwner: uint32(os.Getuid()), castInventoryApplied: inventory},
85 func(in chan<- ports.InputEvent) { inputReady <- in })98 func(in chan<- ports.InputEvent) { inputReady <- in })
86 }()99 }()
87 a := &castApp{inventory: inventory}100 a := &castApp{inventory: inventory}
@@ -523,6 +536,96 @@ func waitFrames(t *testing.T, frames *atomic.Int64, changed <-chan struct{}, exi
523 }536 }
524 }537 }
525 538
539+// TestServerScreencastVirtualOutput: the server backend serves the cast
540+// service without --dbus and streams its virtual output to a PipeWire
541+// consumer.
542+//
543+//testpolicy:realtime real PipeWire/GStreamer frames and D-Bus lifecycle
544+func TestServerScreencastVirtualOutput(t *testing.T) {
545+ requireCastEnv(t)
546+ cfg := config.Defaults()
547+ cfg.Outputs = append(cfg.Outputs, domain.OutputConfig{Name: "tv", Virtual: true, Mode: "320x240"})
548+ app := startCastAppBackend(t, "*\n", cfg, domain.BackendServer)
549+ c := castClient(t)
550+ waitOwner(t, c, scName)
551+ var session, stream string
552+ timeout := time.After(15 * time.Second)
553+ for {
554+ name, m := call(c, scPath, "org.gnome.Mutter.ScreenCast", "CreateSession", "a{sv}", emptyProps)
555+ if name != "" {
556+ t.Fatalf("CreateSession: %s", name)
557+ }
558+ session = strings.Clone(m.Body().ObjectPath())
559+ var errName string
560+ if errName, stream = recordMonitor(c, session, "tv"); errName == "" {
561+ break
562+ }
563+ call(c, session, scSession, "Stop", "", nil)
564+ select {
565+ case <-timeout:
566+ t.Fatalf("RecordMonitor tv: %s", errName)
567+ case <-app.inventory:
568+ }
569+ }
570+ if err := c.AddMatch("type='signal',interface='" + scStream + "'"); err != nil {
571+ t.Fatal(err)
572+ }
573+ if name, _ := call(c, session, scSession, "Start", "", nil); name != "" {
574+ t.Fatalf("Start: %s", name)
575+ }
576+ node := uint32(0)
577+ for node == 0 {
578+ m, err := c.ReadMessage()
579+ if err != nil {
580+ t.Fatal(err)
581+ }
582+ if m.Member == "PipeWireStreamAdded" && m.Path == stream && m.Destination == c.UniqueName() {
583+ node = m.Body().Uint32()
584+ }
585+ }
586+ // Pointer motion (an unbound device reaches the placed virtual output)
587+ // damages the output while the consumer runs.
588+ stop := make(chan struct{})
589+ moved := make(chan struct{})
590+ go func() {
591+ defer close(moved)
592+ tick := time.NewTicker(16 * time.Millisecond)
593+ defer tick.Stop()
594+ for i := 0; ; i++ {
595+ ev := ports.InputEvent(ports.SecurityInput{Event: ports.PointerMotion{X: float64(40 + 120*(i%2)), Y: 40}})
596+ select {
597+ case app.input <- ev:
598+ case <-stop:
599+ return
600+ }
601+ select {
602+ case <-tick.C:
603+ case <-stop:
604+ return
605+ }
606+ }
607+ }()
608+ defer func() { close(stop); <-moved }()
609+ gst := exec.Command("gst-launch-1.0", "pipewiresrc", "path="+itoa(node), "stream-properties=props,media.type=Video", "num-buffers=30", "!", "fakesink")
610+ exited := make(chan error, 1)
611+ if err := gst.Start(); err != nil {
612+ t.Fatal(err)
613+ }
614+ go func() { exited <- gst.Wait() }()
615+ select {
616+ case err := <-exited:
617+ if err != nil {
618+ t.Errorf("gst-launch-1.0: %v", err)
619+ }
620+ case <-time.After(30 * time.Second):
621+ _ = gst.Process.Kill()
622+ t.Fatal("gst-launch-1.0 did not receive 30 buffers")
623+ }
624+ if name, _ := call(c, session, scSession, "Stop", "", nil); name != "" {
625+ t.Fatalf("Stop: %s", name)
626+ }
627+}
628+
526 // castRaceEnabled keeps the real-I/O lifecycle running with -race, but disables629 // castRaceEnabled keeps the real-I/O lifecycle running with -race, but disables
527 // allocation assertions: purego's sync.Pool drops argument storage under race.630 // allocation assertions: purego's sync.Pool drops argument storage under race.
528 func castRaceEnabled() bool {631 func castRaceEnabled() bool {
A internal/app/server_test.go +106 -0
@@ -0,0 +1,106 @@
1+package app
2+
3+import (
4+ "context"
5+ "errors"
6+ "io/fs"
7+ "os"
8+ "path/filepath"
9+ "strings"
10+ "testing"
11+ "time"
12+
13+ "github.com/bnema/neferwl/internal/adapters/config"
14+ "github.com/bnema/neferwl/internal/adapters/statefile"
15+ "github.com/bnema/neferwl/internal/core"
16+ "github.com/bnema/neferwl/internal/domain"
17+ "github.com/bnema/neferwl/internal/ports"
18+)
19+
20+// TestServerVirtualOutput: the server backend with one virtual output and no
21+// physical one focuses the virtual output at startup, and a client maps on
22+// it. Real libinput never runs (noLibinput); the inject channel is the input.
23+//
24+//testpolicy:realtime real Wayland client process, headless renderer and state file
25+func TestServerVirtualOutput(t *testing.T) {
26+ runtimeDir := t.TempDir()
27+ t.Setenv("XDG_RUNTIME_DIR", runtimeDir)
28+ t.Setenv("XDG_STATE_HOME", t.TempDir())
29+ // Server mode always serves the session bus: keep it off the desktop's.
30+ t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+filepath.Join(runtimeDir, "no-bus"))
31+ path := filepath.Join(t.TempDir(), "config")
32+ if err := os.WriteFile(path, []byte("output.tv = virtual 640x360\n"), 0o600); err != nil {
33+ t.Fatal(err)
34+ }
35+ cfg, _, err := config.Load(path)
36+ if err != nil {
37+ t.Fatal(err)
38+ }
39+ cfg.Terminal.Command = []string{os.Args[0], spawnClientArg}
40+ scenes := make(chan []domain.Scene, 4096)
41+ ctx, cancel := context.WithCancel(context.Background())
42+ defer cancel()
43+ inputReady := make(chan chan<- ports.InputEvent, 1)
44+ done := make(chan error, 1)
45+ go func() {
46+ done <- run(ctx, Options{Backend: domain.BackendServer, NoXwayland: true, Config: cfg, ConfigPath: path, testScenes: scenes, noLibinput: true},
47+ func(input chan<- ports.InputEvent) { inputReady <- input })
48+ }()
49+ var input chan<- ports.InputEvent
50+ select {
51+ case input = <-inputReady:
52+ case err := <-done:
53+ // Containers without /sys/class/drm or a GPU cannot run the server backend.
54+ if errors.Is(err, core.ErrNoRenderNode) || errors.Is(err, fs.ErrNotExist) || (err != nil && strings.Contains(strings.ToLower(err.Error()), "vulkan")) {
55+ t.Skipf("no hardware render device: %v", err)
56+ }
57+ t.Fatalf("app exited: %v", err)
58+ case <-time.After(5 * time.Second):
59+ t.Fatal("app did not start")
60+ }
61+ defer func() {
62+ cancel()
63+ select {
64+ case err := <-done:
65+ if err != nil {
66+ t.Errorf("Run: %v", err)
67+ }
68+ case <-time.After(5 * time.Second):
69+ t.Error("Run did not stop")
70+ }
71+ }()
72+ statePath, err := statefile.Path(runtimeDir, "wayland-1")
73+ if err != nil {
74+ t.Fatal(err)
75+ }
76+ input <- ports.SecurityInput{Event: ports.KeyEvent{Keysym: "Return", Mods: domain.ModSuper, Pressed: true}}
77+ deadline := time.After(10 * time.Second)
78+ // The state file is written by its own worker after the scene.
79+ tick := time.NewTicker(20 * time.Millisecond)
80+ defer tick.Stop()
81+ mapped := false
82+ for {
83+ if mapped {
84+ st, err := statefile.Read(statePath)
85+ if err == nil && st.Output == "tv" && len(st.Windows) == 1 && st.Windows[0].Output == "tv" {
86+ return
87+ }
88+ }
89+ select {
90+ case <-tick.C:
91+ case set := <-scenes:
92+ if len(set) == 1 && set[0].Output == "" {
93+ continue // before the first output
94+ }
95+ if len(set) != 1 || set[0].Output != "tv" || set[0].OutputWidth != 640 {
96+ t.Fatalf("scenes: want only tv 640 wide, got %+v", set)
97+ }
98+ mapped = mapped || len(set[0].Windows) == 1
99+ case err := <-done:
100+ t.Fatalf("app exited early: %v", err)
101+ case <-deadline:
102+ st, err := statefile.Read(statePath)
103+ t.Fatalf("no window mapped on a focused tv: %+v %v", st, err)
104+ }
105+ }
106+}
@@ -0,0 +1,106 @@
1+package app
2+
3+import (
4+ "context"
5+ "errors"
6+ "io/fs"
7+ "os"
8+ "path/filepath"
9+ "strings"
10+ "testing"
11+ "time"
12+
13+ "github.com/bnema/neferwl/internal/adapters/config"
14+ "github.com/bnema/neferwl/internal/adapters/statefile"
15+ "github.com/bnema/neferwl/internal/core"
16+ "github.com/bnema/neferwl/internal/domain"
17+ "github.com/bnema/neferwl/internal/ports"
18+)
19+
20+// TestServerVirtualOutput: the server backend with one virtual output and no
21+// physical one focuses the virtual output at startup, and a client maps on
22+// it. Real libinput never runs (noLibinput); the inject channel is the input.
23+//
24+//testpolicy:realtime real Wayland client process, headless renderer and state file
25+func TestServerVirtualOutput(t *testing.T) {
26+ runtimeDir := t.TempDir()
27+ t.Setenv("XDG_RUNTIME_DIR", runtimeDir)
28+ t.Setenv("XDG_STATE_HOME", t.TempDir())
29+ // Server mode always serves the session bus: keep it off the desktop's.
30+ t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+filepath.Join(runtimeDir, "no-bus"))
31+ path := filepath.Join(t.TempDir(), "config")
32+ if err := os.WriteFile(path, []byte("output.tv = virtual 640x360\n"), 0o600); err != nil {
33+ t.Fatal(err)
34+ }
35+ cfg, _, err := config.Load(path)
36+ if err != nil {
37+ t.Fatal(err)
38+ }
39+ cfg.Terminal.Command = []string{os.Args[0], spawnClientArg}
40+ scenes := make(chan []domain.Scene, 4096)
41+ ctx, cancel := context.WithCancel(context.Background())
42+ defer cancel()
43+ inputReady := make(chan chan<- ports.InputEvent, 1)
44+ done := make(chan error, 1)
45+ go func() {
46+ done <- run(ctx, Options{Backend: domain.BackendServer, NoXwayland: true, Config: cfg, ConfigPath: path, testScenes: scenes, noLibinput: true},
47+ func(input chan<- ports.InputEvent) { inputReady <- input })
48+ }()
49+ var input chan<- ports.InputEvent
50+ select {
51+ case input = <-inputReady:
52+ case err := <-done:
53+ // Containers without /sys/class/drm or a GPU cannot run the server backend.
54+ if errors.Is(err, core.ErrNoRenderNode) || errors.Is(err, fs.ErrNotExist) || (err != nil && strings.Contains(strings.ToLower(err.Error()), "vulkan")) {
55+ t.Skipf("no hardware render device: %v", err)
56+ }
57+ t.Fatalf("app exited: %v", err)
58+ case <-time.After(5 * time.Second):
59+ t.Fatal("app did not start")
60+ }
61+ defer func() {
62+ cancel()
63+ select {
64+ case err := <-done:
65+ if err != nil {
66+ t.Errorf("Run: %v", err)
67+ }
68+ case <-time.After(5 * time.Second):
69+ t.Error("Run did not stop")
70+ }
71+ }()
72+ statePath, err := statefile.Path(runtimeDir, "wayland-1")
73+ if err != nil {
74+ t.Fatal(err)
75+ }
76+ input <- ports.SecurityInput{Event: ports.KeyEvent{Keysym: "Return", Mods: domain.ModSuper, Pressed: true}}
77+ deadline := time.After(10 * time.Second)
78+ // The state file is written by its own worker after the scene.
79+ tick := time.NewTicker(20 * time.Millisecond)
80+ defer tick.Stop()
81+ mapped := false
82+ for {
83+ if mapped {
84+ st, err := statefile.Read(statePath)
85+ if err == nil && st.Output == "tv" && len(st.Windows) == 1 && st.Windows[0].Output == "tv" {
86+ return
87+ }
88+ }
89+ select {
90+ case <-tick.C:
91+ case set := <-scenes:
92+ if len(set) == 1 && set[0].Output == "" {
93+ continue // before the first output
94+ }
95+ if len(set) != 1 || set[0].Output != "tv" || set[0].OutputWidth != 640 {
96+ t.Fatalf("scenes: want only tv 640 wide, got %+v", set)
97+ }
98+ mapped = mapped || len(set[0].Windows) == 1
99+ case err := <-done:
100+ t.Fatalf("app exited early: %v", err)
101+ case <-deadline:
102+ st, err := statefile.Read(statePath)
103+ t.Fatalf("no window mapped on a focused tv: %+v %v", st, err)
104+ }
105+ }
106+}
M internal/app/session.go +29 -15
@@ -13,6 +13,7 @@ import (
1313 "github.com/bnema/neferwl/internal/adapters/captureallow"
1414 "github.com/bnema/neferwl/internal/adapters/clock"
1515 "github.com/bnema/neferwl/internal/adapters/config"
16+ "github.com/bnema/neferwl/internal/adapters/directseat"
1617 "github.com/bnema/neferwl/internal/adapters/drm"
1718 "github.com/bnema/neferwl/internal/adapters/drm/supervisor"
1819 "github.com/bnema/neferwl/internal/adapters/headlessinput"
@@ -46,6 +47,7 @@ import (
4647 // until run ends; the keymap and the wayland server own themselves.
4748 type session struct {
4849 opts Options
50+ plan core.BackendPlan
4951 log zerowrap.Logger
5052
5153 clock ports.Clock
@@ -93,7 +95,7 @@ const (
9395 // warning or nil instead of failing. A failure releases the DRM backend,
9496 // keymap and Vulkan resources (abort).
9597 func assembleSession(ctx context.Context, opts Options) (s *session, err error) {
96- s = &session{opts: opts, log: logging.For(ctx, "app"), clock: clock.System{}, security: &sessionsecurity.Gate{}}
98+ s = &session{opts: opts, plan: core.PlanBackend(opts.Backend), log: logging.For(ctx, "app"), clock: clock.System{}, security: &sessionsecurity.Gate{}}
9799 defer func() {
98100 if err != nil {
99101 s.abort()
@@ -102,7 +104,7 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
102104 }()
103105 log := s.log
104106 s.sizes = opts.Sizes
105- if len(s.sizes) == 0 {
107+ if len(s.sizes) == 0 && s.plan.FixedHeads == core.HeadsSized {
106108 s.sizes = [][2]int{{1920, 1080}}
107109 }
108110 // Every output renders on the same GPU: its formats are the clients'.
@@ -110,24 +112,24 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
110112 if err != nil {
111113 return s, err
112114 }
113- if opts.Backend == "drm" {
115+ if s.plan.KMS {
114116 if s.hw, err = supervisor.Open(ctx, opts.Config, s.inst); err != nil {
115117 return s, err
116118 }
117119 s.gpu = s.hw.RenderDevice()
118120 } else {
119121 cands, listErr := drm.ListGPUs("/sys", "/dev")
120- s.gpu, err = openHeadlessRender(s.inst, cands, listErr, opts.Config, os.Getenv("NEFERWL_RENDER_DEVICE"), logging.For(ctx, "drm"))
122+ s.gpu, err = openHeadlessRenderPolicy(s.inst, cands, listErr, opts.Config, os.Getenv("NEFERWL_RENDER_DEVICE"), s.plan.RequireRenderNode, logging.For(ctx, "drm"))
121123 if err != nil {
122124 return s, err
123125 }
124126 }
125127 s.dmabuf = s.gpu.DMABuf()
126128 log.Info().Int("formats", len(s.dmabuf.Formats)).Msg("dmabuf")
127- s.p = newPipes(s.hw != nil, opts.Config.Hint.Enable)
129+ s.p = newPipes(s.plan.PersistScales, opts.Config.Hint.Enable)
128130 // core() carries channels only; the gate, clock and terminal flag are
129131 // explicit core.Options.
130- if s.core, err = core.New(opts.Config, s.p.core(), core.Options{Security: s.security, Clock: s.clock, Tokens: launcher.Tokens{}, Terminal: !opts.NoTerminal, HintDisabled: hintDisabledNote(ctx)}); err != nil {
132+ if s.core, err = core.New(opts.Config, s.p.core(), core.Options{Security: s.security, Clock: s.clock, Tokens: launcher.Tokens{}, Terminal: !opts.NoTerminal && s.plan.AutoTerminal != core.AutoTerminalOff, HintDisabled: hintDisabledNote(ctx), PlaceVirtuals: !s.plan.IsolateVirtuals}); err != nil {
131133 return s, err
132134 }
133135 if s.km, err = xkb.New(xkb.RMLVO{Layout: opts.Config.Keyboard.Layout, Variant: opts.Config.Keyboard.Variant, Options: opts.Config.Keyboard.Options}); err != nil {
@@ -153,7 +155,7 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
153155 // Only a real session (or a test that asks) serves the session bus:
154156 // headless runs would take the names from the desktop they run in.
155157 var casts ports.CastSink
156- if s.hw != nil || opts.DBus {
158+ if s.plan.SessionDBus == core.SessionDBusAlways || opts.DBus {
157159 s.cast = screencast.New(s.captureAllow.Policy, s.p.castCommands, logging.For(ctx, "screencast"))
158160 s.cast.SetCastBuffers(s.gpu)
159161 casts = s.cast
@@ -251,7 +253,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
251253 defer s.close()
252254 ctx, cancel := context.WithCancel(ctx)
253255 defer cancel()
254- opts, log, p, hw, km, security := s.opts, s.log, s.p, s.hw, s.km, s.security
256+ opts, plan, log, p, hw, km, security := s.opts, s.plan, s.log, s.p, s.hw, s.km, s.security
255257 childEnv, curs, xdisplay, statePath := s.childEnv, s.curs, s.xdisplay, s.statePath
256258 server, captureAllow, c, child, wsIDs, sizes, path := s.server, s.captureAllow, s.core, s.child, s.wsIDs, s.sizes, s.path
257259 if opts.Session {
@@ -284,8 +286,20 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
284286 script := make(chan string)
285287 go func() {
286288 defer workers.Done()
287- if hw != nil {
288- // Core sends the first layout once DRM reports the outputs.
289+ var (
290+ seat ports.Seat
291+ seatName string
292+ active <-chan bool
293+ )
294+ switch {
295+ case plan.Input == core.InputLibinputLibseat:
296+ seat, seatName, active = hw.Seat(), hw.Seat().Name(), hw.Seat().Subscribe()
297+ case plan.Input == core.InputLibinputDirect && !opts.noLibinput:
298+ direct := directseat.New(logging.For(ctx, "seat"))
299+ seat, seatName, active = direct, direct.Name(), direct.Active()
300+ }
301+ if seat != nil {
302+ // Core sends the first layout once the backend reports the outputs.
289303 var layout domain.Layout
290304 select {
291305 case layout = <-p.layouts:
@@ -304,8 +318,8 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
304318 }
305319 return libinput.Run(ctx, libinput.Options{
306320 Security: security,
307- Seat: hw.Seat(),
308- SeatName: hw.Seat().Name(),
321+ Seat: seat,
322+ SeatName: seatName,
309323 Keymap: km,
310324 Keymaps: p.keymaps,
311325 Layout: layout,
@@ -313,7 +327,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
313327 Constraints: p.constraints,
314328 DeviceConfig: opts.Config.InputDevicesConfig,
315329 DeviceConfigs: p.deviceConfigs,
316- Active: hw.Seat().Subscribe(),
330+ Active: active,
317331 MoveCursor: curs.Move,
318332 Log: logging.For(ctx, "input"),
319333 LogMotion: logging.Enabled(ctx, "input-motion"),
@@ -427,7 +441,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
427441 }
428442 // Only a real session serves the session bus: headless runs would take
429443 // the names from the desktop they run in, unless a test asks (DBus).
430- if hw != nil || opts.DBus {
444+ if plan.SessionDBus == core.SessionDBusAlways || opts.DBus {
431445 workers.Add(2)
432446 go func() {
433447 defer workers.Done()
@@ -441,7 +455,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
441455 s.cast.Run(ctx, busRetry)
442456 }()
443457 }
444- if hw != nil {
458+ if plan.LogindPowerKeys {
445459 // The same goes for the system bus: logind's locks keep the power
446460 // keys from acting before a bind sees them.
447461 workers.Add(1)
@@ -13,6 +13,7 @@ import (
13 "github.com/bnema/neferwl/internal/adapters/captureallow"13 "github.com/bnema/neferwl/internal/adapters/captureallow"
14 "github.com/bnema/neferwl/internal/adapters/clock"14 "github.com/bnema/neferwl/internal/adapters/clock"
15 "github.com/bnema/neferwl/internal/adapters/config"15 "github.com/bnema/neferwl/internal/adapters/config"
16+ "github.com/bnema/neferwl/internal/adapters/directseat"
16 "github.com/bnema/neferwl/internal/adapters/drm"17 "github.com/bnema/neferwl/internal/adapters/drm"
17 "github.com/bnema/neferwl/internal/adapters/drm/supervisor"18 "github.com/bnema/neferwl/internal/adapters/drm/supervisor"
18 "github.com/bnema/neferwl/internal/adapters/headlessinput"19 "github.com/bnema/neferwl/internal/adapters/headlessinput"
@@ -46,6 +47,7 @@ import (
46 // until run ends; the keymap and the wayland server own themselves.47 // until run ends; the keymap and the wayland server own themselves.
47 type session struct {48 type session struct {
48 opts Options49 opts Options
50+ plan core.BackendPlan
49 log zerowrap.Logger51 log zerowrap.Logger
50 52
51 clock ports.Clock53 clock ports.Clock
@@ -93,7 +95,7 @@ const (
93 // warning or nil instead of failing. A failure releases the DRM backend,95 // warning or nil instead of failing. A failure releases the DRM backend,
94 // keymap and Vulkan resources (abort).96 // keymap and Vulkan resources (abort).
95 func assembleSession(ctx context.Context, opts Options) (s *session, err error) {97 func assembleSession(ctx context.Context, opts Options) (s *session, err error) {
96- s = &session{opts: opts, log: logging.For(ctx, "app"), clock: clock.System{}, security: &sessionsecurity.Gate{}}98+ s = &session{opts: opts, plan: core.PlanBackend(opts.Backend), log: logging.For(ctx, "app"), clock: clock.System{}, security: &sessionsecurity.Gate{}}
97 defer func() {99 defer func() {
98 if err != nil {100 if err != nil {
99 s.abort()101 s.abort()
@@ -102,7 +104,7 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
102 }()104 }()
103 log := s.log105 log := s.log
104 s.sizes = opts.Sizes106 s.sizes = opts.Sizes
105- if len(s.sizes) == 0 {107+ if len(s.sizes) == 0 && s.plan.FixedHeads == core.HeadsSized {
106 s.sizes = [][2]int{{1920, 1080}}108 s.sizes = [][2]int{{1920, 1080}}
107 }109 }
108 // Every output renders on the same GPU: its formats are the clients'.110 // Every output renders on the same GPU: its formats are the clients'.
@@ -110,24 +112,24 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
110 if err != nil {112 if err != nil {
111 return s, err113 return s, err
112 }114 }
113- if opts.Backend == "drm" {115+ if s.plan.KMS {
114 if s.hw, err = supervisor.Open(ctx, opts.Config, s.inst); err != nil {116 if s.hw, err = supervisor.Open(ctx, opts.Config, s.inst); err != nil {
115 return s, err117 return s, err
116 }118 }
117 s.gpu = s.hw.RenderDevice()119 s.gpu = s.hw.RenderDevice()
118 } else {120 } else {
119 cands, listErr := drm.ListGPUs("/sys", "/dev")121 cands, listErr := drm.ListGPUs("/sys", "/dev")
120- s.gpu, err = openHeadlessRender(s.inst, cands, listErr, opts.Config, os.Getenv("NEFERWL_RENDER_DEVICE"), logging.For(ctx, "drm"))122+ s.gpu, err = openHeadlessRenderPolicy(s.inst, cands, listErr, opts.Config, os.Getenv("NEFERWL_RENDER_DEVICE"), s.plan.RequireRenderNode, logging.For(ctx, "drm"))
121 if err != nil {123 if err != nil {
122 return s, err124 return s, err
123 }125 }
124 }126 }
125 s.dmabuf = s.gpu.DMABuf()127 s.dmabuf = s.gpu.DMABuf()
126 log.Info().Int("formats", len(s.dmabuf.Formats)).Msg("dmabuf")128 log.Info().Int("formats", len(s.dmabuf.Formats)).Msg("dmabuf")
127- s.p = newPipes(s.hw != nil, opts.Config.Hint.Enable)129+ s.p = newPipes(s.plan.PersistScales, opts.Config.Hint.Enable)
128 // core() carries channels only; the gate, clock and terminal flag are130 // core() carries channels only; the gate, clock and terminal flag are
129 // explicit core.Options.131 // explicit core.Options.
130- if s.core, err = core.New(opts.Config, s.p.core(), core.Options{Security: s.security, Clock: s.clock, Tokens: launcher.Tokens{}, Terminal: !opts.NoTerminal, HintDisabled: hintDisabledNote(ctx)}); err != nil {132+ if s.core, err = core.New(opts.Config, s.p.core(), core.Options{Security: s.security, Clock: s.clock, Tokens: launcher.Tokens{}, Terminal: !opts.NoTerminal && s.plan.AutoTerminal != core.AutoTerminalOff, HintDisabled: hintDisabledNote(ctx), PlaceVirtuals: !s.plan.IsolateVirtuals}); err != nil {
131 return s, err133 return s, err
132 }134 }
133 if s.km, err = xkb.New(xkb.RMLVO{Layout: opts.Config.Keyboard.Layout, Variant: opts.Config.Keyboard.Variant, Options: opts.Config.Keyboard.Options}); err != nil {135 if s.km, err = xkb.New(xkb.RMLVO{Layout: opts.Config.Keyboard.Layout, Variant: opts.Config.Keyboard.Variant, Options: opts.Config.Keyboard.Options}); err != nil {
@@ -153,7 +155,7 @@ func assembleSession(ctx context.Context, opts Options) (s *session, err error)
153 // Only a real session (or a test that asks) serves the session bus:155 // Only a real session (or a test that asks) serves the session bus:
154 // headless runs would take the names from the desktop they run in.156 // headless runs would take the names from the desktop they run in.
155 var casts ports.CastSink157 var casts ports.CastSink
156- if s.hw != nil || opts.DBus {158+ if s.plan.SessionDBus == core.SessionDBusAlways || opts.DBus {
157 s.cast = screencast.New(s.captureAllow.Policy, s.p.castCommands, logging.For(ctx, "screencast"))159 s.cast = screencast.New(s.captureAllow.Policy, s.p.castCommands, logging.For(ctx, "screencast"))
158 s.cast.SetCastBuffers(s.gpu)160 s.cast.SetCastBuffers(s.gpu)
159 casts = s.cast161 casts = s.cast
@@ -251,7 +253,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
251 defer s.close()253 defer s.close()
252 ctx, cancel := context.WithCancel(ctx)254 ctx, cancel := context.WithCancel(ctx)
253 defer cancel()255 defer cancel()
254- opts, log, p, hw, km, security := s.opts, s.log, s.p, s.hw, s.km, s.security256+ opts, plan, log, p, hw, km, security := s.opts, s.plan, s.log, s.p, s.hw, s.km, s.security
255 childEnv, curs, xdisplay, statePath := s.childEnv, s.curs, s.xdisplay, s.statePath257 childEnv, curs, xdisplay, statePath := s.childEnv, s.curs, s.xdisplay, s.statePath
256 server, captureAllow, c, child, wsIDs, sizes, path := s.server, s.captureAllow, s.core, s.child, s.wsIDs, s.sizes, s.path258 server, captureAllow, c, child, wsIDs, sizes, path := s.server, s.captureAllow, s.core, s.child, s.wsIDs, s.sizes, s.path
257 if opts.Session {259 if opts.Session {
@@ -284,8 +286,20 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
284 script := make(chan string)286 script := make(chan string)
285 go func() {287 go func() {
286 defer workers.Done()288 defer workers.Done()
287- if hw != nil {289+ var (
288- // Core sends the first layout once DRM reports the outputs.290+ seat ports.Seat
291+ seatName string
292+ active <-chan bool
293+ )
294+ switch {
295+ case plan.Input == core.InputLibinputLibseat:
296+ seat, seatName, active = hw.Seat(), hw.Seat().Name(), hw.Seat().Subscribe()
297+ case plan.Input == core.InputLibinputDirect && !opts.noLibinput:
298+ direct := directseat.New(logging.For(ctx, "seat"))
299+ seat, seatName, active = direct, direct.Name(), direct.Active()
300+ }
301+ if seat != nil {
302+ // Core sends the first layout once the backend reports the outputs.
289 var layout domain.Layout303 var layout domain.Layout
290 select {304 select {
291 case layout = <-p.layouts:305 case layout = <-p.layouts:
@@ -304,8 +318,8 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
304 }318 }
305 return libinput.Run(ctx, libinput.Options{319 return libinput.Run(ctx, libinput.Options{
306 Security: security,320 Security: security,
307- Seat: hw.Seat(),321+ Seat: seat,
308- SeatName: hw.Seat().Name(),322+ SeatName: seatName,
309 Keymap: km,323 Keymap: km,
310 Keymaps: p.keymaps,324 Keymaps: p.keymaps,
311 Layout: layout,325 Layout: layout,
@@ -313,7 +327,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
313 Constraints: p.constraints,327 Constraints: p.constraints,
314 DeviceConfig: opts.Config.InputDevicesConfig,328 DeviceConfig: opts.Config.InputDevicesConfig,
315 DeviceConfigs: p.deviceConfigs,329 DeviceConfigs: p.deviceConfigs,
316- Active: hw.Seat().Subscribe(),330+ Active: active,
317 MoveCursor: curs.Move,331 MoveCursor: curs.Move,
318 Log: logging.For(ctx, "input"),332 Log: logging.For(ctx, "input"),
319 LogMotion: logging.Enabled(ctx, "input-motion"),333 LogMotion: logging.Enabled(ctx, "input-motion"),
@@ -427,7 +441,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
427 }441 }
428 // Only a real session serves the session bus: headless runs would take442 // Only a real session serves the session bus: headless runs would take
429 // the names from the desktop they run in, unless a test asks (DBus).443 // the names from the desktop they run in, unless a test asks (DBus).
430- if hw != nil || opts.DBus {444+ if plan.SessionDBus == core.SessionDBusAlways || opts.DBus {
431 workers.Add(2)445 workers.Add(2)
432 go func() {446 go func() {
433 defer workers.Done()447 defer workers.Done()
@@ -441,7 +455,7 @@ func (s *session) run(ctx context.Context, inject func(chan<- ports.InputEvent))
441 s.cast.Run(ctx, busRetry)455 s.cast.Run(ctx, busRetry)
442 }()456 }()
443 }457 }
444- if hw != nil {458+ if plan.LogindPowerKeys {
445 // The same goes for the system bus: logind's locks keep the power459 // The same goes for the system bus: logind's locks keep the power
446 // keys from acting before a bind sees them.460 // keys from acting before a bind sees them.
447 workers.Add(1)461 workers.Add(1)
M internal/app/xwayland_test.go +48 -3
@@ -72,11 +72,24 @@ func startXwaylandWith(t *testing.T, sizes [][2]int, mutate func(*domain.Config)
7272 return startXwaylandConfig(t, sizes, mutate, "")
7373 }
7474
75+// startXwaylandBackend is startXwaylandWith on backend. The server backend
76+// never runs libinput here (noLibinput): the script stays the input.
77+func startXwaylandBackend(t *testing.T, backend domain.Backend, sizes [][2]int, mutate func(*domain.Config)) *xwaylandEnv {
78+ t.Helper()
79+ return startXwaylandBackendConfig(t, backend, sizes, mutate, "")
80+}
81+
7582 // startXwaylandConfig is startXwaylandWith watching the config file at path
7683 // for reloads; empty uses a path that does not exist.
84+func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {
85+ t.Helper()
86+ return startXwaylandBackendConfig(t, domain.BackendHeadless, sizes, mutate, path)
87+}
88+
89+// startXwaylandBackendConfig combines backend selection and config reloads.
7790 //
7891 //testpolicy:realtime bounded wait on real X11/Wayland sockets or child process I/O
79-func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {
92+func startXwaylandBackendConfig(t *testing.T, backend domain.Backend, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {
8093 t.Helper()
8194 if path == "" {
8295 // Never the user's own config file.
@@ -162,8 +175,8 @@ func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Confi
162175 done := make(chan error, 1)
163176 go func() {
164177 done <- Run(ctx, Options{
165- Backend: "headless", NoTerminal: true, Config: cfg, ConfigPath: path, Script: script,
166- ScreenshotDir: shots, Sizes: sizes,
178+ Backend: backend, NoTerminal: true, Config: cfg, ConfigPath: path, Script: script,
179+ ScreenshotDir: shots, Sizes: sizes, noLibinput: backend == domain.BackendServer,
167180 })
168181 }()
169182 t.Cleanup(func() {
@@ -987,3 +1000,35 @@ func publicationChanges(t *testing.T) chan struct{} {
9871000 }
9881001 return changes.(chan struct{})
9891002 }
1003+
1004+// TestXwaylandServerProbe: on the server backend, with one virtual output
1005+// and no fixed head, an X11 client maps on the virtual output, takes the
1006+// focus and closes with the close-window bind.
1007+//
1008+//testpolicy:realtime bounded wait on real X11/Wayland sockets or child process I/O
1009+func TestXwaylandServerProbe(t *testing.T) {
1010+ e := startXwaylandBackend(t, domain.BackendServer, nil, func(c *domain.Config) {
1011+ c.Outputs = append(c.Outputs, domain.OutputConfig{Name: "tv", Virtual: true, Mode: "640x360"})
1012+ })
1013+ p := startProbe(t, e.bin, e.display, "-title", "server")
1014+ var st statefile.State
1015+ until(t, "X11Probe visible on tv", func() bool {
1016+ st = readState(e.statePath)
1017+ return st.Output == "tv" && len(st.Windows) == 1 && st.Windows[0].AppID == "X11Probe" && st.Windows[0].Visible && st.Windows[0].Output == "tv"
1018+ })
1019+ if !st.Windows[0].Xwayland {
1020+ t.Errorf("X11 window not marked Xwayland: %+v", st.Windows[0])
1021+ }
1022+ until(t, "probe focus", func() bool { return strings.Contains(p.out.String(), "focus") })
1023+ if _, err := io.WriteString(e.script, "key Super+q\n"); err != nil {
1024+ t.Fatal(err)
1025+ }
1026+ select {
1027+ case err := <-p.waited:
1028+ if err != nil {
1029+ t.Errorf("probe exited with %v, want 0", err)
1030+ }
1031+ case <-time.After(2 * time.Second):
1032+ t.Fatal("probe did not exit within 2s of Super+q")
1033+ }
1034+}
@@ -72,11 +72,24 @@ func startXwaylandWith(t *testing.T, sizes [][2]int, mutate func(*domain.Config)
72 return startXwaylandConfig(t, sizes, mutate, "")72 return startXwaylandConfig(t, sizes, mutate, "")
73 }73 }
74 74
75+// startXwaylandBackend is startXwaylandWith on backend. The server backend
76+// never runs libinput here (noLibinput): the script stays the input.
77+func startXwaylandBackend(t *testing.T, backend domain.Backend, sizes [][2]int, mutate func(*domain.Config)) *xwaylandEnv {
78+ t.Helper()
79+ return startXwaylandBackendConfig(t, backend, sizes, mutate, "")
80+}
81+
75 // startXwaylandConfig is startXwaylandWith watching the config file at path82 // startXwaylandConfig is startXwaylandWith watching the config file at path
76 // for reloads; empty uses a path that does not exist.83 // for reloads; empty uses a path that does not exist.
84+func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {
85+ t.Helper()
86+ return startXwaylandBackendConfig(t, domain.BackendHeadless, sizes, mutate, path)
87+}
88+
89+// startXwaylandBackendConfig combines backend selection and config reloads.
77 //90 //
78 //testpolicy:realtime bounded wait on real X11/Wayland sockets or child process I/O91 //testpolicy:realtime bounded wait on real X11/Wayland sockets or child process I/O
79-func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {92+func startXwaylandBackendConfig(t *testing.T, backend domain.Backend, sizes [][2]int, mutate func(*domain.Config), path string) *xwaylandEnv {
80 t.Helper()93 t.Helper()
81 if path == "" {94 if path == "" {
82 // Never the user's own config file.95 // Never the user's own config file.
@@ -162,8 +175,8 @@ func startXwaylandConfig(t *testing.T, sizes [][2]int, mutate func(*domain.Confi
162 done := make(chan error, 1)175 done := make(chan error, 1)
163 go func() {176 go func() {
164 done <- Run(ctx, Options{177 done <- Run(ctx, Options{
165- Backend: "headless", NoTerminal: true, Config: cfg, ConfigPath: path, Script: script,178+ Backend: backend, NoTerminal: true, Config: cfg, ConfigPath: path, Script: script,
166- ScreenshotDir: shots, Sizes: sizes,179+ ScreenshotDir: shots, Sizes: sizes, noLibinput: backend == domain.BackendServer,
167 })180 })
168 }()181 }()
169 t.Cleanup(func() {182 t.Cleanup(func() {
@@ -987,3 +1000,35 @@ func publicationChanges(t *testing.T) chan struct{} {
987 }1000 }
988 return changes.(chan struct{})1001 return changes.(chan struct{})
989 }1002 }
1003+
1004+// TestXwaylandServerProbe: on the server backend, with one virtual output
1005+// and no fixed head, an X11 client maps on the virtual output, takes the
1006+// focus and closes with the close-window bind.
1007+//
1008+//testpolicy:realtime bounded wait on real X11/Wayland sockets or child process I/O
1009+func TestXwaylandServerProbe(t *testing.T) {
1010+ e := startXwaylandBackend(t, domain.BackendServer, nil, func(c *domain.Config) {
1011+ c.Outputs = append(c.Outputs, domain.OutputConfig{Name: "tv", Virtual: true, Mode: "640x360"})
1012+ })
1013+ p := startProbe(t, e.bin, e.display, "-title", "server")
1014+ var st statefile.State
1015+ until(t, "X11Probe visible on tv", func() bool {
1016+ st = readState(e.statePath)
1017+ return st.Output == "tv" && len(st.Windows) == 1 && st.Windows[0].AppID == "X11Probe" && st.Windows[0].Visible && st.Windows[0].Output == "tv"
1018+ })
1019+ if !st.Windows[0].Xwayland {
1020+ t.Errorf("X11 window not marked Xwayland: %+v", st.Windows[0])
1021+ }
1022+ until(t, "probe focus", func() bool { return strings.Contains(p.out.String(), "focus") })
1023+ if _, err := io.WriteString(e.script, "key Super+q\n"); err != nil {
1024+ t.Fatal(err)
1025+ }
1026+ select {
1027+ case err := <-p.waited:
1028+ if err != nil {
1029+ t.Errorf("probe exited with %v, want 0", err)
1030+ }
1031+ case <-time.After(2 * time.Second):
1032+ t.Fatal("probe did not exit within 2s of Super+q")
1033+ }
1034+}
M internal/cli/cli_test.go +32 -0
@@ -4,6 +4,7 @@ import (
44 "bytes"
55 "context"
66 "errors"
7+ "flag"
78 "io"
89 "os"
910 "strconv"
@@ -79,6 +80,15 @@ func TestCommands(t *testing.T) {
7980 {[]string{"--backend=drm", "--input=-"}, 2, "", "--input requires"},
8081 {[]string{"--backend=headless", "--screenshot=" + dir, "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},
8182 {[]string{"--backend=headless", "--headless-hdr", "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},
83+ {[]string{"--backend=server", "--screenshot=" + dir}, 2, "", "--screenshot is not allowed with --backend=server"},
84+ {[]string{"--backend=server", "--screenshot-raw"}, 2, "", "--screenshot-raw is not allowed"},
85+ {[]string{"--backend=server", "--input=-"}, 2, "", "--input is not allowed"},
86+ {[]string{"--backend=server", "--size=1920x1080"}, 2, "", "--size is not allowed"},
87+ {[]string{"--backend=server", "--timeout=1s"}, 2, "", "--timeout is not allowed"},
88+ {[]string{"--backend=server", "--headless-hdr"}, 2, "", "--headless-hdr is not allowed"},
89+ {[]string{"--backend=server", "--dbus"}, 2, "", "--dbus is not allowed"},
90+ {[]string{"--backend=server", "extra"}, 2, "", "unexpected arguments"},
91+ {[]string{"--backend=server", "--debug=nope"}, 2, "", "--debug"},
8292 {[]string{"--size=1920"}, 2, "", "--size"},
8393 {[]string{"--timeout=-1s"}, 2, "", "negative timeout"},
8494 {[]string{"--debug=nope"}, 2, "", "--debug"},
@@ -180,3 +190,25 @@ func TestOpenScript(t *testing.T) {
180190 })
181191 }
182192 }
193+
194+// TestServerFlagsAllowed validates without running: a server run would grab
195+// the machine's input devices.
196+func TestServerFlagsAllowed(t *testing.T) {
197+ for _, args := range [][]string{
198+ {"--backend=server"},
199+ {"--backend=server", "--config=/tmp/x", "--debug=all", "--pprof=localhost:0", "--session", "--no-xwayland", "--no-terminal"},
200+ } {
201+ fs := flag.NewFlagSet("neferwl", flag.ContinueOnError)
202+ var f runFlags
203+ f.register(fs)
204+ if err := fs.Parse(args); err != nil {
205+ t.Fatal(err)
206+ }
207+ set := map[string]bool{}
208+ fs.Visit(func(fl *flag.Flag) { set[fl.Name] = true })
209+ sizes, err := f.validate(fs.Args(), set)
210+ if err != nil || sizes != nil {
211+ t.Errorf("%v: sizes %v err %v", args, sizes, err)
212+ }
213+ }
214+}
@@ -4,6 +4,7 @@ import (
4 "bytes"4 "bytes"
5 "context"5 "context"
6 "errors"6 "errors"
7+ "flag"
7 "io"8 "io"
8 "os"9 "os"
9 "strconv"10 "strconv"
@@ -79,6 +80,15 @@ func TestCommands(t *testing.T) {
79 {[]string{"--backend=drm", "--input=-"}, 2, "", "--input requires"},80 {[]string{"--backend=drm", "--input=-"}, 2, "", "--input requires"},
80 {[]string{"--backend=headless", "--screenshot=" + dir, "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},81 {[]string{"--backend=headless", "--screenshot=" + dir, "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},
81 {[]string{"--backend=headless", "--headless-hdr", "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},82 {[]string{"--backend=headless", "--headless-hdr", "--screenshot-raw"}, 2, "", "--screenshot-raw requires"},
83+ {[]string{"--backend=server", "--screenshot=" + dir}, 2, "", "--screenshot is not allowed with --backend=server"},
84+ {[]string{"--backend=server", "--screenshot-raw"}, 2, "", "--screenshot-raw is not allowed"},
85+ {[]string{"--backend=server", "--input=-"}, 2, "", "--input is not allowed"},
86+ {[]string{"--backend=server", "--size=1920x1080"}, 2, "", "--size is not allowed"},
87+ {[]string{"--backend=server", "--timeout=1s"}, 2, "", "--timeout is not allowed"},
88+ {[]string{"--backend=server", "--headless-hdr"}, 2, "", "--headless-hdr is not allowed"},
89+ {[]string{"--backend=server", "--dbus"}, 2, "", "--dbus is not allowed"},
90+ {[]string{"--backend=server", "extra"}, 2, "", "unexpected arguments"},
91+ {[]string{"--backend=server", "--debug=nope"}, 2, "", "--debug"},
82 {[]string{"--size=1920"}, 2, "", "--size"},92 {[]string{"--size=1920"}, 2, "", "--size"},
83 {[]string{"--timeout=-1s"}, 2, "", "negative timeout"},93 {[]string{"--timeout=-1s"}, 2, "", "negative timeout"},
84 {[]string{"--debug=nope"}, 2, "", "--debug"},94 {[]string{"--debug=nope"}, 2, "", "--debug"},
@@ -180,3 +190,25 @@ func TestOpenScript(t *testing.T) {
180 })190 })
181 }191 }
182 }192 }
193+
194+// TestServerFlagsAllowed validates without running: a server run would grab
195+// the machine's input devices.
196+func TestServerFlagsAllowed(t *testing.T) {
197+ for _, args := range [][]string{
198+ {"--backend=server"},
199+ {"--backend=server", "--config=/tmp/x", "--debug=all", "--pprof=localhost:0", "--session", "--no-xwayland", "--no-terminal"},
200+ } {
201+ fs := flag.NewFlagSet("neferwl", flag.ContinueOnError)
202+ var f runFlags
203+ f.register(fs)
204+ if err := fs.Parse(args); err != nil {
205+ t.Fatal(err)
206+ }
207+ set := map[string]bool{}
208+ fs.Visit(func(fl *flag.Flag) { set[fl.Name] = true })
209+ sizes, err := f.validate(fs.Args(), set)
210+ if err != nil || sizes != nil {
211+ t.Errorf("%v: sizes %v err %v", args, sizes, err)
212+ }
213+ }
214+}
M internal/cli/run.go +28 -5
@@ -19,6 +19,7 @@ import (
1919 "github.com/bnema/neferwl/internal/adapters/config"
2020 "github.com/bnema/neferwl/internal/adapters/logging"
2121 "github.com/bnema/neferwl/internal/app"
22+ "github.com/bnema/neferwl/internal/domain"
2223 "golang.org/x/term"
2324 )
2425
@@ -30,7 +31,7 @@ type runFlags struct {
3031 }
3132
3233 func (f *runFlags) register(fs *flag.FlagSet) {
33- fs.StringVar(&f.backend, "backend", "drm", "drm or headless")
34+ fs.StringVar(&f.backend, "backend", "drm", "drm, headless or server")
3435 fs.StringVar(&f.screenshot, "screenshot", "", "write PNG frames to directory")
3536 fs.StringVar(&f.size, "size", "1920x1080", "headless output sizes WxH, comma-separated for several outputs")
3637 fs.StringVar(&f.input, "input", "", "headless input script path (- for stdin)")
@@ -46,9 +47,29 @@ func (f *runFlags) register(fs *flag.FlagSet) {
4647 fs.StringVar(&f.pprof, "pprof", "", "serve Go runtime profiles (heap, CPU, trace) on this address, e.g. localhost:6060")
4748 }
4849
49-// validate checks the flag combinations and parses --size.
50-func (f *runFlags) validate(args []string) ([][2]int, error) {
50+// serverRejected are the test-only and headless flags --backend=server
51+// refuses, in report order.
52+var serverRejected = []string{"screenshot", "screenshot-raw", "input", "size", "timeout", "headless-hdr", "dbus"}
53+
54+// validate checks the flag combinations and parses --size. set holds the
55+// flags given on the command line.
56+func (f *runFlags) validate(args []string, set map[string]bool) ([][2]int, error) {
5157 headless := f.backend == "headless"
58+ if f.backend == string(domain.BackendServer) {
59+ for _, name := range serverRejected {
60+ if set[name] {
61+ return nil, usagef("--%s is not allowed with --backend=server", name)
62+ }
63+ }
64+ if len(args) != 0 {
65+ return nil, usagef("unexpected arguments: %v", args)
66+ }
67+ if _, err := logging.ParseDebug(f.debug); err != nil {
68+ return nil, usageError{fmt.Errorf("--debug: %w", err)}
69+ }
70+ // Server mode has no fixed heads: only config-declared virtual outputs.
71+ return nil, nil
72+ }
5273 switch {
5374 case f.backend != "drm" && !headless:
5475 return nil, usagef("invalid backend %q", f.backend)
@@ -93,7 +114,9 @@ func setupRun(fs *flag.FlagSet) Runner {
93114 var f runFlags
94115 f.register(fs)
95116 return func(ctx context.Context, _ Env, args []string) error {
96- sizes, err := f.validate(args)
117+ set := map[string]bool{}
118+ fs.Visit(func(fl *flag.Flag) { set[fl.Name] = true })
119+ sizes, err := f.validate(args, set)
97120 if err != nil {
98121 return err
99122 }
@@ -149,7 +172,7 @@ func (f *runFlags) run(ctx context.Context, sizes [][2]int) error {
149172 configLog.Warn().Int("line", w.Line).Msg(w.Msg)
150173 }
151174 err = app.Run(ctx, app.Options{
152- Backend: f.backend,
175+ Backend: domain.Backend(f.backend),
153176 Config: cfg,
154177 ConfigPath: path,
155178 Timeout: f.timeout,
@@ -19,6 +19,7 @@ import (
19 "github.com/bnema/neferwl/internal/adapters/config"19 "github.com/bnema/neferwl/internal/adapters/config"
20 "github.com/bnema/neferwl/internal/adapters/logging"20 "github.com/bnema/neferwl/internal/adapters/logging"
21 "github.com/bnema/neferwl/internal/app"21 "github.com/bnema/neferwl/internal/app"
22+ "github.com/bnema/neferwl/internal/domain"
22 "golang.org/x/term"23 "golang.org/x/term"
23 )24 )
24 25
@@ -30,7 +31,7 @@ type runFlags struct {
30 }31 }
31 32
32 func (f *runFlags) register(fs *flag.FlagSet) {33 func (f *runFlags) register(fs *flag.FlagSet) {
33- fs.StringVar(&f.backend, "backend", "drm", "drm or headless")34+ fs.StringVar(&f.backend, "backend", "drm", "drm, headless or server")
34 fs.StringVar(&f.screenshot, "screenshot", "", "write PNG frames to directory")35 fs.StringVar(&f.screenshot, "screenshot", "", "write PNG frames to directory")
35 fs.StringVar(&f.size, "size", "1920x1080", "headless output sizes WxH, comma-separated for several outputs")36 fs.StringVar(&f.size, "size", "1920x1080", "headless output sizes WxH, comma-separated for several outputs")
36 fs.StringVar(&f.input, "input", "", "headless input script path (- for stdin)")37 fs.StringVar(&f.input, "input", "", "headless input script path (- for stdin)")
@@ -46,9 +47,29 @@ func (f *runFlags) register(fs *flag.FlagSet) {
46 fs.StringVar(&f.pprof, "pprof", "", "serve Go runtime profiles (heap, CPU, trace) on this address, e.g. localhost:6060")47 fs.StringVar(&f.pprof, "pprof", "", "serve Go runtime profiles (heap, CPU, trace) on this address, e.g. localhost:6060")
47 }48 }
48 49
49-// validate checks the flag combinations and parses --size.50+// serverRejected are the test-only and headless flags --backend=server
50-func (f *runFlags) validate(args []string) ([][2]int, error) {51+// refuses, in report order.
52+var serverRejected = []string{"screenshot", "screenshot-raw", "input", "size", "timeout", "headless-hdr", "dbus"}
53+
54+// validate checks the flag combinations and parses --size. set holds the
55+// flags given on the command line.
56+func (f *runFlags) validate(args []string, set map[string]bool) ([][2]int, error) {
51 headless := f.backend == "headless"57 headless := f.backend == "headless"
58+ if f.backend == string(domain.BackendServer) {
59+ for _, name := range serverRejected {
60+ if set[name] {
61+ return nil, usagef("--%s is not allowed with --backend=server", name)
62+ }
63+ }
64+ if len(args) != 0 {
65+ return nil, usagef("unexpected arguments: %v", args)
66+ }
67+ if _, err := logging.ParseDebug(f.debug); err != nil {
68+ return nil, usageError{fmt.Errorf("--debug: %w", err)}
69+ }
70+ // Server mode has no fixed heads: only config-declared virtual outputs.
71+ return nil, nil
72+ }
52 switch {73 switch {
53 case f.backend != "drm" && !headless:74 case f.backend != "drm" && !headless:
54 return nil, usagef("invalid backend %q", f.backend)75 return nil, usagef("invalid backend %q", f.backend)
@@ -93,7 +114,9 @@ func setupRun(fs *flag.FlagSet) Runner {
93 var f runFlags114 var f runFlags
94 f.register(fs)115 f.register(fs)
95 return func(ctx context.Context, _ Env, args []string) error {116 return func(ctx context.Context, _ Env, args []string) error {
96- sizes, err := f.validate(args)117+ set := map[string]bool{}
118+ fs.Visit(func(fl *flag.Flag) { set[fl.Name] = true })
119+ sizes, err := f.validate(args, set)
97 if err != nil {120 if err != nil {
98 return err121 return err
99 }122 }
@@ -149,7 +172,7 @@ func (f *runFlags) run(ctx context.Context, sizes [][2]int) error {
149 configLog.Warn().Int("line", w.Line).Msg(w.Msg)172 configLog.Warn().Int("line", w.Line).Msg(w.Msg)
150 }173 }
151 err = app.Run(ctx, app.Options{174 err = app.Run(ctx, app.Options{
152- Backend: f.backend,175+ Backend: domain.Backend(f.backend),
153 Config: cfg,176 Config: cfg,
154 ConfigPath: path,177 ConfigPath: path,
155 Timeout: f.timeout,178 Timeout: f.timeout,
A internal/core/backendplan.go +70 -0
@@ -0,0 +1,70 @@
1+package core
2+
3+import "github.com/bnema/neferwl/internal/domain"
4+
5+// HeadsSource tells where a backend's fixed output heads come from.
6+type HeadsSource uint8
7+
8+const (
9+ HeadsNone HeadsSource = iota // no fixed heads
10+ HeadsConnectors // DRM connectors
11+ HeadsSized // headless heads of a configured size
12+)
13+
14+// InputSource tells how a backend receives input.
15+type InputSource uint8
16+
17+const (
18+ InputNone InputSource = iota
19+ InputLibinputLibseat // libinput with devices opened through libseat
20+ InputScript // scripted input (headless)
21+ InputLibinputDirect // libinput opening devices directly
22+)
23+
24+// SessionDBusMode tells when the session D-Bus services start.
25+type SessionDBusMode uint8
26+
27+const (
28+ SessionDBusFlagOnly SessionDBusMode = iota // only when requested by flag
29+ SessionDBusAlways // always
30+)
31+
32+// AutoTerminalMode tells when a terminal is spawned at startup.
33+type AutoTerminalMode uint8
34+
35+const (
36+ AutoTerminalOff AutoTerminalMode = iota // never
37+ AutoTerminalConfig // per config
38+ AutoTerminalConfigOrFlag // per config, overridable by flag
39+)
40+
41+// BackendPlan is the per-backend decision table consumed by wiring.
42+type BackendPlan struct {
43+ KMS bool
44+ RequireRenderNode bool // false lets headless fall back to any Vulkan device
45+ FixedHeads HeadsSource
46+ IsolateVirtuals bool
47+ Input InputSource
48+ SessionDBus SessionDBusMode
49+ LogindPowerKeys bool
50+ PersistScales bool
51+ AutoTerminal AutoTerminalMode
52+ AllowTestFlags bool
53+}
54+
55+// PlanBackend returns the plan for b; an unknown backend yields the zero plan.
56+func PlanBackend(b domain.Backend) BackendPlan {
57+ switch b {
58+ case domain.BackendDRM:
59+ return BackendPlan{KMS: true, RequireRenderNode: true, FixedHeads: HeadsConnectors, IsolateVirtuals: true,
60+ Input: InputLibinputLibseat, SessionDBus: SessionDBusAlways, LogindPowerKeys: true, PersistScales: true,
61+ AutoTerminal: AutoTerminalConfig}
62+ case domain.BackendHeadless:
63+ return BackendPlan{FixedHeads: HeadsSized, IsolateVirtuals: true, Input: InputScript,
64+ SessionDBus: SessionDBusFlagOnly, AutoTerminal: AutoTerminalConfigOrFlag, AllowTestFlags: true}
65+ case domain.BackendServer:
66+ return BackendPlan{RequireRenderNode: true, FixedHeads: HeadsNone, Input: InputLibinputDirect,
67+ SessionDBus: SessionDBusAlways, PersistScales: true, AutoTerminal: AutoTerminalOff}
68+ }
69+ return BackendPlan{}
70+}
@@ -0,0 +1,70 @@
1+package core
2+
3+import "github.com/bnema/neferwl/internal/domain"
4+
5+// HeadsSource tells where a backend's fixed output heads come from.
6+type HeadsSource uint8
7+
8+const (
9+ HeadsNone HeadsSource = iota // no fixed heads
10+ HeadsConnectors // DRM connectors
11+ HeadsSized // headless heads of a configured size
12+)
13+
14+// InputSource tells how a backend receives input.
15+type InputSource uint8
16+
17+const (
18+ InputNone InputSource = iota
19+ InputLibinputLibseat // libinput with devices opened through libseat
20+ InputScript // scripted input (headless)
21+ InputLibinputDirect // libinput opening devices directly
22+)
23+
24+// SessionDBusMode tells when the session D-Bus services start.
25+type SessionDBusMode uint8
26+
27+const (
28+ SessionDBusFlagOnly SessionDBusMode = iota // only when requested by flag
29+ SessionDBusAlways // always
30+)
31+
32+// AutoTerminalMode tells when a terminal is spawned at startup.
33+type AutoTerminalMode uint8
34+
35+const (
36+ AutoTerminalOff AutoTerminalMode = iota // never
37+ AutoTerminalConfig // per config
38+ AutoTerminalConfigOrFlag // per config, overridable by flag
39+)
40+
41+// BackendPlan is the per-backend decision table consumed by wiring.
42+type BackendPlan struct {
43+ KMS bool
44+ RequireRenderNode bool // false lets headless fall back to any Vulkan device
45+ FixedHeads HeadsSource
46+ IsolateVirtuals bool
47+ Input InputSource
48+ SessionDBus SessionDBusMode
49+ LogindPowerKeys bool
50+ PersistScales bool
51+ AutoTerminal AutoTerminalMode
52+ AllowTestFlags bool
53+}
54+
55+// PlanBackend returns the plan for b; an unknown backend yields the zero plan.
56+func PlanBackend(b domain.Backend) BackendPlan {
57+ switch b {
58+ case domain.BackendDRM:
59+ return BackendPlan{KMS: true, RequireRenderNode: true, FixedHeads: HeadsConnectors, IsolateVirtuals: true,
60+ Input: InputLibinputLibseat, SessionDBus: SessionDBusAlways, LogindPowerKeys: true, PersistScales: true,
61+ AutoTerminal: AutoTerminalConfig}
62+ case domain.BackendHeadless:
63+ return BackendPlan{FixedHeads: HeadsSized, IsolateVirtuals: true, Input: InputScript,
64+ SessionDBus: SessionDBusFlagOnly, AutoTerminal: AutoTerminalConfigOrFlag, AllowTestFlags: true}
65+ case domain.BackendServer:
66+ return BackendPlan{RequireRenderNode: true, FixedHeads: HeadsNone, Input: InputLibinputDirect,
67+ SessionDBus: SessionDBusAlways, PersistScales: true, AutoTerminal: AutoTerminalOff}
68+ }
69+ return BackendPlan{}
70+}
A internal/core/backendplan_test.go +26 -0
@@ -0,0 +1,26 @@
1+package core
2+
3+import (
4+ "testing"
5+
6+ "github.com/bnema/neferwl/internal/domain"
7+ "github.com/stretchr/testify/assert"
8+)
9+
10+func TestPlanBackend(t *testing.T) {
11+ cases := map[domain.Backend]BackendPlan{
12+ domain.BackendDRM: {KMS: true, RequireRenderNode: true, FixedHeads: HeadsConnectors, IsolateVirtuals: true,
13+ Input: InputLibinputLibseat, SessionDBus: SessionDBusAlways, LogindPowerKeys: true, PersistScales: true,
14+ AutoTerminal: AutoTerminalConfig, AllowTestFlags: false},
15+ domain.BackendHeadless: {KMS: false, RequireRenderNode: false, FixedHeads: HeadsSized, IsolateVirtuals: true,
16+ Input: InputScript, SessionDBus: SessionDBusFlagOnly, LogindPowerKeys: false, PersistScales: false,
17+ AutoTerminal: AutoTerminalConfigOrFlag, AllowTestFlags: true},
18+ domain.BackendServer: {KMS: false, RequireRenderNode: true, FixedHeads: HeadsNone, IsolateVirtuals: false,
19+ Input: InputLibinputDirect, SessionDBus: SessionDBusAlways, LogindPowerKeys: false, PersistScales: true,
20+ AutoTerminal: AutoTerminalOff, AllowTestFlags: false},
21+ }
22+ for b, want := range cases {
23+ t.Run(string(b), func(t *testing.T) { assert.Equal(t, want, PlanBackend(b)) })
24+ }
25+ assert.Equal(t, BackendPlan{}, PlanBackend("bogus"))
26+}
@@ -0,0 +1,26 @@
1+package core
2+
3+import (
4+ "testing"
5+
6+ "github.com/bnema/neferwl/internal/domain"
7+ "github.com/stretchr/testify/assert"
8+)
9+
10+func TestPlanBackend(t *testing.T) {
11+ cases := map[domain.Backend]BackendPlan{
12+ domain.BackendDRM: {KMS: true, RequireRenderNode: true, FixedHeads: HeadsConnectors, IsolateVirtuals: true,
13+ Input: InputLibinputLibseat, SessionDBus: SessionDBusAlways, LogindPowerKeys: true, PersistScales: true,
14+ AutoTerminal: AutoTerminalConfig, AllowTestFlags: false},
15+ domain.BackendHeadless: {KMS: false, RequireRenderNode: false, FixedHeads: HeadsSized, IsolateVirtuals: true,
16+ Input: InputScript, SessionDBus: SessionDBusFlagOnly, LogindPowerKeys: false, PersistScales: false,
17+ AutoTerminal: AutoTerminalConfigOrFlag, AllowTestFlags: true},
18+ domain.BackendServer: {KMS: false, RequireRenderNode: true, FixedHeads: HeadsNone, IsolateVirtuals: false,
19+ Input: InputLibinputDirect, SessionDBus: SessionDBusAlways, LogindPowerKeys: false, PersistScales: true,
20+ AutoTerminal: AutoTerminalOff, AllowTestFlags: false},
21+ }
22+ for b, want := range cases {
23+ t.Run(string(b), func(t *testing.T) { assert.Equal(t, want, PlanBackend(b)) })
24+ }
25+ assert.Equal(t, BackendPlan{}, PlanBackend("bogus"))
26+}
M internal/core/core.go +3 -0
@@ -76,6 +76,9 @@ type Options struct {
7676 // HintDisabled, when set, is called the first time the hint action runs
7777 // without a scanner (hint mode off). It must not block.
7878 HintDisabled func()
79+ // PlaceVirtuals lays unplaced virtual outputs out like physical ones
80+ // instead of isolating them (server mode). The zero value isolates.
81+ PlaceVirtuals bool
7982 }
8083
8184 type binding struct {
@@ -76,6 +76,9 @@ type Options struct {
76 // HintDisabled, when set, is called the first time the hint action runs76 // HintDisabled, when set, is called the first time the hint action runs
77 // without a scanner (hint mode off). It must not block.77 // without a scanner (hint mode off). It must not block.
78 HintDisabled func()78 HintDisabled func()
79+ // PlaceVirtuals lays unplaced virtual outputs out like physical ones
80+ // instead of isolating them (server mode). The zero value isolates.
81+ PlaceVirtuals bool
79 }82 }
80 83
81 type binding struct {84 type binding struct {
M internal/core/devicefocus_test.go +26 -0
@@ -1,6 +1,7 @@
11 package core_test
22
33 import (
4+ "github.com/bnema/neferwl/internal/core"
45 "github.com/bnema/neferwl/internal/domain"
56 "github.com/bnema/neferwl/internal/ports"
67 "testing"
@@ -76,3 +77,28 @@ func TestSyncMotionPrecedesSameSurfaceClick(t *testing.T) {
7677 }
7778 })
7879 }
80+
81+func TestPlaceVirtualsSingleVirtualTakesFocus(t *testing.T) {
82+ synctest.Test(t, func(t *testing.T) {
83+ r := newDragRigWith(t, false, core.Options{PlaceVirtuals: true}, func(c *domain.Config) {
84+ c.Outputs = []domain.OutputConfig{{Name: "tv", Virtual: true}}
85+ }, domain.OutputInfo{Name: "tv", Virtual: true, Width: 640, Height: 360})
86+ r.client <- ports.WindowMapped{ID: 1}
87+ r.settle(t)
88+ if got := focusChanges(r.drain()); len(got) == 0 || got[len(got)-1] != 1 {
89+ t.Fatalf("startup focus %v", got)
90+ }
91+ r.in(ports.InputDeviceAdded{ID: 1, Name: "mouse"})
92+ r.in(ports.PointerMotion{Device: 1, X: 100, Y: 100})
93+ r.settle(t)
94+ reached := false
95+ for _, cmd := range r.drain() {
96+ if m, ok := cmd.(ports.PointerMotionTo); ok {
97+ reached = m.ID == 1
98+ }
99+ }
100+ if !reached {
101+ t.Fatal("unbound pointer did not reach the virtual output")
102+ }
103+ })
104+}
@@ -1,6 +1,7 @@
1 package core_test1 package core_test
2 2
3 import (3 import (
4+ "github.com/bnema/neferwl/internal/core"
4 "github.com/bnema/neferwl/internal/domain"5 "github.com/bnema/neferwl/internal/domain"
5 "github.com/bnema/neferwl/internal/ports"6 "github.com/bnema/neferwl/internal/ports"
6 "testing"7 "testing"
@@ -76,3 +77,28 @@ func TestSyncMotionPrecedesSameSurfaceClick(t *testing.T) {
76 }77 }
77 })78 })
78 }79 }
80+
81+func TestPlaceVirtualsSingleVirtualTakesFocus(t *testing.T) {
82+ synctest.Test(t, func(t *testing.T) {
83+ r := newDragRigWith(t, false, core.Options{PlaceVirtuals: true}, func(c *domain.Config) {
84+ c.Outputs = []domain.OutputConfig{{Name: "tv", Virtual: true}}
85+ }, domain.OutputInfo{Name: "tv", Virtual: true, Width: 640, Height: 360})
86+ r.client <- ports.WindowMapped{ID: 1}
87+ r.settle(t)
88+ if got := focusChanges(r.drain()); len(got) == 0 || got[len(got)-1] != 1 {
89+ t.Fatalf("startup focus %v", got)
90+ }
91+ r.in(ports.InputDeviceAdded{ID: 1, Name: "mouse"})
92+ r.in(ports.PointerMotion{Device: 1, X: 100, Y: 100})
93+ r.settle(t)
94+ reached := false
95+ for _, cmd := range r.drain() {
96+ if m, ok := cmd.(ports.PointerMotionTo); ok {
97+ reached = m.ID == 1
98+ }
99+ }
100+ if !reached {
101+ t.Fatal("unbound pointer did not reach the virtual output")
102+ }
103+ })
104+}
M internal/core/drag_test.go +7 -1
M internal/core/gpuplan.go +8 -1
M internal/core/gpuplan_test.go +7 -2
M internal/core/isolation_test.go +17 -0
M internal/core/screens.go +1 -1
A internal/domain/backend.go +21 -0
A internal/domain/backend_test.go +17 -0
M packaging/arch/PKGBUILD +1 -0
M packaging/aur/neferwl-git/PKGBUILD +1 -0
A packaging/neferwl-server.service +21 -0
M packaging/neferwl.service +3 -0

Comments00 unresolved

    no comments yet.

    Keyboard shortcuts

    Single-key shortcuts are on. ctrl k and esc work whatever this says.

    ctrl k :
    go to a section, branch, tag, file or repository
    ?
    this list
    j k
    move the row cursor down / up
    enter
    open the row under the cursor; on Files, a directory opens or closes in place
    ↑ ↓ ← → home end
    in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
    l h
    on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. On pages with a side panel: into the panel (on a merge request, its files) / back to the content; there j k move between its controls
    g g G
    first / last row
    /
    filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
    b
    switch branch or tag
    g s g f g c g b g m g i g r g a
    tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
    g h
    home
    w
    wide mode: use the whole width of the screen, or not (remembered)
    y
    copy a permalink pinned to the commit; in a file, click a line number to select it, shift-click for a range
    d u x
    diff: split / unified / collapse or expand all
    e E
    diff: the whole file in view / every file, with the lines the hunks hide
    n
    merge request: next note in the diff
    l
    merge request: the list of files (j k move, enter opens, esc back)
    M
    merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
    R
    merge request: mark the head read
    esc
    close a dialog, leave a field

    Branches 33

    Tags 15

    ↑↓ moveenter openesc close