Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41552b4797 | ||
|
|
056cd5440a | ||
|
|
d3bc369164 | ||
|
|
b169a64ad5 | ||
|
|
53ab05ce12 | ||
|
|
a31bed8aeb |
@@ -1,33 +1,62 @@
|
|||||||
# Ground Station
|
# Ground Station
|
||||||
|
|
||||||
Orange Pi Zero 3W application for the custom OpenIPC/WFB ground station.
|
Orange Pi Zero 3W supervisor and kiosk display for the custom OpenIPC/WFB ground station.
|
||||||
|
|
||||||
## Current baseline
|
## Components
|
||||||
|
|
||||||
- receives framed GX12 RC channel data over the dedicated AUX1 UART at 115200 8N1;
|
The ARM64 artifact intentionally contains two executables:
|
||||||
|
|
||||||
|
- `groundstation-linux-arm64` — the long-running root supervisor. It owns the GX12 UART, logging, RC state, video lifecycle, and starts the display process.
|
||||||
|
- `groundstation-display-linux-arm64` — the unprivileged X11 kiosk renderer. It runs as `orangepi` on `DISPLAY=:0`; the supervisor owns it during normal use.
|
||||||
|
|
||||||
|
Current capabilities:
|
||||||
|
|
||||||
|
- receives framed GX12 RC channel data at 115200 8N1;
|
||||||
- validates protocol version, frame length and CRC-16;
|
- validates protocol version, frame length and CRC-16;
|
||||||
- logs final mixed channel values;
|
- logs channel changes instead of every frame;
|
||||||
- can start the existing `fpv-video` launcher for the Viture primary display.
|
- starts/stops `fpv-video` from the configured CH6 power/lifecycle control;
|
||||||
|
- starts an independent kiosk display before video, tolerates temporary X11 downtime without restarting the supervisor, and stops deterministically on shutdown;
|
||||||
|
- keeps the fullscreen fallback/menu canvas below `fpv-video`, showing `Brak połączenia WFB` only while video is absent;
|
||||||
|
- maps a transparent, input-transparent OSD overlay above `fpv-video` as the reserved flight OSD rendering surface: it never presents pixels over the video or intercepts its input.
|
||||||
|
|
||||||
The first baseline is intentionally small. It does **not** yet control an AUX, manipulate the flight-control link, or replace the primary video pipeline.
|
Future MIPI/touch targets use their own templates rather than sharing one global layout. The flight OSD will render on the existing transparent layer above video, preserving the pilot stream's priority.
|
||||||
|
|
||||||
## Run
|
## Installation on Orange Pi
|
||||||
|
|
||||||
|
Extract the artifact and install **both** files:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Hardware UART mode (device path will be confirmed during Orange Pi bring-up)
|
sudo install -m 0755 groundstation-linux-arm64 /usr/local/bin/groundstation
|
||||||
groundstation -serial /dev/ttyS1 -start-video
|
sudo install -m 0755 groundstation-display-linux-arm64 /usr/local/bin/groundstation-display
|
||||||
|
sudo systemctl restart groundstation
|
||||||
# Test input mode
|
|
||||||
groundstation -stdin
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Protocol
|
Check logs:
|
||||||
|
|
||||||
The v1 protocol is described in `AGENTS.md` once the repository policy file is approved. It carries 16 final EdgeTX channel outputs as a binary framed message with CRC.
|
```bash
|
||||||
|
systemctl status groundstation --no-pager
|
||||||
|
journalctl -u groundstation -b --no-pager -n 80
|
||||||
|
```
|
||||||
|
|
||||||
## Project direction
|
Do not run `groundstation-display` by hand during normal operation. It needs the X11 user/session environment and is managed by the supervisor. For isolated renderer debugging it supports:
|
||||||
|
|
||||||
1. GX12 Ground Station UART mode sends final RC/switch state to Orange Pi.
|
```bash
|
||||||
2. Orange Pi logs and renders state while supervising the FPV video launcher.
|
groundstation-display -target x11
|
||||||
3. Add WFB quality, recorder state, and MIPI touch display independently of pilot video.
|
```
|
||||||
4. Add a watchdog-protected override of exactly one reserved `SAFE/NORMAL/HIGH` AUX.
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
The service reads `/etc/groundstation/config.yml`. For the verified permanent GX12 connection, use:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
serial:
|
||||||
|
path: /dev/ttyS2
|
||||||
|
```
|
||||||
|
|
||||||
|
`/dev/ttyS0` is the Orange Pi boot/debug UART and must not be used for the permanently connected GX12.
|
||||||
|
|
||||||
|
## Runtime dependencies
|
||||||
|
|
||||||
|
- X11 session on `:0` owned by `orangepi`; the kiosk waits for X11 and reconnects after display-manager restarts;
|
||||||
|
- `wmctrl` for the fullscreen/stacking kiosk window states; without it the kiosk windows map as normal windows and the condition is logged;
|
||||||
|
- `runuser` from util-linux for the unprivileged kiosk launch.
|
||||||
|
|||||||
@@ -1,71 +1,62 @@
|
|||||||
|
// Command groundstation-display renders the Ground Station kiosk layers. It
|
||||||
|
// owns its display lifecycle independently of WFB, the transmitter and the
|
||||||
|
// video launcher: it waits for its target to appear, redraws as needed, and
|
||||||
|
// stops only when it receives SIGINT or SIGTERM.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
"github.com/BurntSushi/xgb"
|
"git.piksar.eu/piotr/groundstation/internal/display"
|
||||||
"github.com/BurntSushi/xgb/xproto"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
// buildTarget selects the target-specific layers. Each target owns its own
|
||||||
width = 1920
|
// backend and layouts; there is no shared global template. The Viture target
|
||||||
height = 1080
|
// builds two independent layers — the fullscreen fallback/menu canvas below
|
||||||
)
|
// video and the transparent OSD overlay above it — wired to one shared video
|
||||||
|
// presence signal: the sessions observe the video output lifecycle on the
|
||||||
func main() {
|
// display server and the templates draw or hide from it. WFB and video
|
||||||
conn, err := xgb.NewConn()
|
// decode never move into this process.
|
||||||
if err != nil {
|
func buildTarget(name string) ([]display.Layer, error) {
|
||||||
log.Fatal(err)
|
switch name {
|
||||||
}
|
case "x11":
|
||||||
defer conn.Close()
|
video := display.NewVideoPresence()
|
||||||
|
return []display.Layer{
|
||||||
screen := xproto.Setup(conn).DefaultScreen(conn)
|
{
|
||||||
window, err := xproto.NewWindowId(conn)
|
Name: "fallback-canvas",
|
||||||
if err != nil {
|
Opener: display.X11Opener{Video: video},
|
||||||
log.Fatal(err)
|
Template: display.NewFallbackTemplate(video, "Brak połączenia WFB"),
|
||||||
}
|
},
|
||||||
|
{
|
||||||
values := uint32(xproto.CwBackPixel | xproto.CwEventMask)
|
Name: "osd-overlay",
|
||||||
xproto.CreateWindow(conn, screen.RootDepth, window, screen.Root, 0, 0, width, height, 0,
|
Opener: display.X11Opener{Video: video, Role: display.RoleAbove},
|
||||||
xproto.WindowClassInputOutput, screen.RootVisual, values,
|
Template: display.NewOSDTemplate(video),
|
||||||
[]uint32{screen.BlackPixel, xproto.EventMaskExposure})
|
},
|
||||||
xproto.MapWindow(conn, window)
|
}, nil
|
||||||
conn.Sync()
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown display target %q (supported: x11)", name)
|
||||||
// XFCE owns the actual fullscreen policy; use its existing wmctrl helper.
|
|
||||||
_ = exec.Command("wmctrl", "-i", "-r", fmt.Sprintf("0x%08x", window), "-b", "add,fullscreen").Run()
|
|
||||||
|
|
||||||
gc, err := xproto.NewGcontextId(conn)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
xproto.CreateGC(conn, gc, xproto.Drawable(window), xproto.GcForeground|xproto.GcBackground,
|
|
||||||
[]uint32{screen.WhitePixel, screen.BlackPixel})
|
|
||||||
font := xproto.Font(window)
|
|
||||||
xproto.OpenFont(conn, font, uint16(len("fixed")), "fixed")
|
|
||||||
xproto.ChangeGC(conn, gc, xproto.GcFont, []uint32{uint32(font)})
|
|
||||||
|
|
||||||
draw := func() {
|
|
||||||
xproto.ClearArea(conn, false, window, 0, 0, width, height)
|
|
||||||
message := "Brak polaczenia WFB"
|
|
||||||
xproto.ImageText8(conn, byte(len(message)), xproto.Drawable(window), gc, 32, 56, message)
|
|
||||||
conn.Sync()
|
|
||||||
}
|
|
||||||
draw()
|
|
||||||
|
|
||||||
for {
|
|
||||||
event, err := conn.WaitForEvent()
|
|
||||||
if err != nil {
|
|
||||||
if os.IsTimeout(err) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, ok := event.(xproto.ExposeEvent); ok {
|
|
||||||
draw()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
target := flag.String("target", "x11", "display target: x11 (Viture) today; mipi planned")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
layers, err := buildTarget(*target)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
// Temporary X11 unavailability never exits this process; every layer
|
||||||
|
// keeps retrying internally until the context is cancelled.
|
||||||
|
display.RunLayers(ctx, layers)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.piksar.eu/piotr/groundstation/internal/display"
|
||||||
|
)
|
||||||
|
|
||||||
|
type recordingCanvas struct {
|
||||||
|
width, height int
|
||||||
|
lines []string
|
||||||
|
clears, flushes int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *recordingCanvas) Size() (int, int) { return c.width, c.height }
|
||||||
|
func (c *recordingCanvas) Clear() { c.clears++ }
|
||||||
|
func (c *recordingCanvas) Text(_, _ int, message string) {
|
||||||
|
c.lines = append(c.lines, message)
|
||||||
|
}
|
||||||
|
func (c *recordingCanvas) Flush() { c.flushes++ }
|
||||||
|
|
||||||
|
func TestBuildTargetBuildsIndependentVitureLayers(t *testing.T) {
|
||||||
|
layers, err := buildTarget("x11")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(layers) != 2 {
|
||||||
|
t.Fatalf("layers=%d want the fallback canvas and the OSD overlay", len(layers))
|
||||||
|
}
|
||||||
|
canvas, osd := layers[0], layers[1]
|
||||||
|
if canvas.Name != "fallback-canvas" || osd.Name != "osd-overlay" {
|
||||||
|
t.Fatalf("layer names %q/%q want fallback-canvas/osd-overlay", canvas.Name, osd.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
canvasOpener, ok := canvas.Opener.(display.X11Opener)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("canvas opener %T must be the X11 target", canvas.Opener)
|
||||||
|
}
|
||||||
|
if canvasOpener.Role != display.RoleBelow {
|
||||||
|
t.Fatalf("canvas layer role %v must stay below video", canvasOpener.Role)
|
||||||
|
}
|
||||||
|
osdOpener, ok := osd.Opener.(display.X11Opener)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("OSD opener %T must be the X11 target", osd.Opener)
|
||||||
|
}
|
||||||
|
if osdOpener.Role != display.RoleAbove {
|
||||||
|
t.Fatalf("OSD layer role %v must stay above video", osdOpener.Role)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both layers must share one presence signal so the video lifecycle
|
||||||
|
// observed by either session drives both templates.
|
||||||
|
if canvasOpener.Video == nil || osdOpener.Video == nil || canvasOpener.Video != osdOpener.Video {
|
||||||
|
t.Fatal("layers must share one video presence signal")
|
||||||
|
}
|
||||||
|
|
||||||
|
// The canvas layer keeps the target-specific fallback template with the
|
||||||
|
// exact fallback text.
|
||||||
|
canvasSurface := &recordingCanvas{width: 800, height: 600}
|
||||||
|
canvas.Template.Draw(canvasSurface)
|
||||||
|
if len(canvasSurface.lines) != 1 || canvasSurface.lines[0] != "Brak połączenia WFB" {
|
||||||
|
t.Fatalf("canvas lines=%q want the exact fallback text", canvasSurface.lines)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The OSD layer is the OSD surface, never the fallback.
|
||||||
|
osdSurface := &recordingCanvas{width: 800, height: 600}
|
||||||
|
osd.Template.Draw(osdSurface)
|
||||||
|
if len(osdSurface.lines) != 0 {
|
||||||
|
t.Fatalf("OSD lines=%q want none: the overlay must not duplicate the fallback", osdSurface.lines)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Video presence hides the fallback on the canvas layer only.
|
||||||
|
canvasOpener.Video.SetActive(true)
|
||||||
|
canvasSurface.lines = nil
|
||||||
|
canvas.Template.Draw(canvasSurface)
|
||||||
|
if len(canvasSurface.lines) != 0 {
|
||||||
|
t.Fatalf("canvas lines=%q must disappear while video is present", canvasSurface.lines)
|
||||||
|
}
|
||||||
|
canvasOpener.Video.SetActive(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildTargetRejectsUnknownTarget(t *testing.T) {
|
||||||
|
if _, err := buildTarget("hdmi-mirror"); err == nil {
|
||||||
|
t.Fatal("unknown target must fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.piksar.eu/piotr/groundstation/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// displaySupervisor keeps the independent kiosk display process running.
|
||||||
|
// X11 downtime never escalates here: the kiosk retries its target
|
||||||
|
// internally, and this loop only restarts the process if the kiosk itself
|
||||||
|
// dies. The Ground Station supervisor therefore stays up while X11 restarts.
|
||||||
|
type displaySupervisor struct {
|
||||||
|
launch func() (*exec.Cmd, error)
|
||||||
|
logger *log.Logger
|
||||||
|
// retryDelay is the first wait after a kiosk exit; it grows to maxDelay
|
||||||
|
// and resets after the kiosk stayed up for stableAfter.
|
||||||
|
retryDelay time.Duration
|
||||||
|
maxDelay time.Duration
|
||||||
|
stableAfter time.Duration
|
||||||
|
// stopGrace bounds the interrupt-to-kill window on shutdown.
|
||||||
|
stopGrace time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDisplaySupervisor(cfg config.Config, logger *log.Logger) *displaySupervisor {
|
||||||
|
return &displaySupervisor{
|
||||||
|
launch: func() (*exec.Cmd, error) { return startDisplayProcess(cfg.Display) },
|
||||||
|
logger: logger,
|
||||||
|
retryDelay: time.Second,
|
||||||
|
maxDelay: 30 * time.Second,
|
||||||
|
stableAfter: time.Minute,
|
||||||
|
stopGrace: 5 * time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *displaySupervisor) run(ctx context.Context) {
|
||||||
|
delay := s.retryDelay
|
||||||
|
for ctx.Err() == nil {
|
||||||
|
cmd, err := s.launch()
|
||||||
|
if err == nil {
|
||||||
|
err = cmd.Start()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Printf("display start: %v; retrying", err)
|
||||||
|
if !sleepFor(ctx, delay) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delay = nextBackoff(delay, s.maxDelay)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
started := time.Now()
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- cmd.Wait() }()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.logger.Printf("display exited: %v; restarting", err)
|
||||||
|
case <-ctx.Done():
|
||||||
|
stopDisplayProcess(cmd, done, s.stopGrace)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if time.Since(started) >= s.stableAfter {
|
||||||
|
delay = s.retryDelay
|
||||||
|
}
|
||||||
|
if !sleepFor(ctx, delay) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delay = nextBackoff(delay, s.maxDelay)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stopDisplayProcess shuts the kiosk down deterministically: the interrupt
|
||||||
|
// goes to the whole kiosk process group (runuser plus the kiosk itself,
|
||||||
|
// which runuser does not forward signals to), waits for the grace window,
|
||||||
|
// then kills the group and reaps the direct child. The direct child exiting
|
||||||
|
// does not prove the group is empty — a kiosk that ignored the interrupt
|
||||||
|
// would outlive an exiting runuser — so the group receives a final SIGKILL
|
||||||
|
// sweep; for an already-empty group that is a harmless no-op.
|
||||||
|
func stopDisplayProcess(cmd *exec.Cmd, done <-chan error, grace time.Duration) {
|
||||||
|
signalGroup := func(sig syscall.Signal) {
|
||||||
|
_ = syscall.Kill(-cmd.Process.Pid, sig)
|
||||||
|
}
|
||||||
|
signalGroup(syscall.SIGINT)
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(grace):
|
||||||
|
signalGroup(syscall.SIGKILL)
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
signalGroup(syscall.SIGKILL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// startDisplayProcess builds the kiosk launch command. It normally runs as
|
||||||
|
// the unprivileged desktop user against the session X server, in its own
|
||||||
|
// process group so shutdown can signal the whole kiosk tree.
|
||||||
|
func startDisplayProcess(cfg config.DisplayConfig) (*exec.Cmd, error) {
|
||||||
|
env := []string{
|
||||||
|
"DISPLAY=" + cfg.Display,
|
||||||
|
"XAUTHORITY=" + cfg.Xauthority,
|
||||||
|
}
|
||||||
|
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
if cfg.User == "" {
|
||||||
|
cmd = exec.Command(cfg.Command)
|
||||||
|
// Configured values must precede the inherited environment: the
|
||||||
|
// child resolves the first occurrence of each variable.
|
||||||
|
cmd.Env = append(env, os.Environ()...)
|
||||||
|
} else {
|
||||||
|
args := []string{"-u", cfg.User, "--", "env"}
|
||||||
|
args = append(args, env...)
|
||||||
|
args = append(args, cfg.Command)
|
||||||
|
cmd = exec.Command("runuser", args...)
|
||||||
|
}
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||||
|
return cmd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextBackoff(delay, max time.Duration) time.Duration {
|
||||||
|
delay *= 2
|
||||||
|
if delay > max {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return delay
|
||||||
|
}
|
||||||
|
|
||||||
|
func sleepFor(ctx context.Context, duration time.Duration) bool {
|
||||||
|
timer := time.NewTimer(duration)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false
|
||||||
|
case <-timer.C:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"os/signal"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.piksar.eu/piotr/groundstation/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStartDisplayProcessWrapsCommandForDesktopUser(t *testing.T) {
|
||||||
|
cmd, err := startDisplayProcess(config.DisplayConfig{
|
||||||
|
Command: "/usr/local/bin/groundstation-display",
|
||||||
|
User: "orangepi",
|
||||||
|
Display: ":0",
|
||||||
|
Xauthority: "/home/orangepi/.Xauthority",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := strings.Join(cmd.Args, " ")
|
||||||
|
want := "runuser -u orangepi -- env DISPLAY=:0 XAUTHORITY=/home/orangepi/.Xauthority /usr/local/bin/groundstation-display"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("args=%q want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartDisplayProcessRunsDirectlyWithoutUser(t *testing.T) {
|
||||||
|
t.Setenv("DISPLAY", ":9")
|
||||||
|
|
||||||
|
cmd, err := startDisplayProcess(config.DisplayConfig{
|
||||||
|
Command: "/bin/kiosk",
|
||||||
|
Display: ":1",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Join(cmd.Args, " ") != "/bin/kiosk" {
|
||||||
|
t.Fatalf("args=%v want [/bin/kiosk]", cmd.Args)
|
||||||
|
}
|
||||||
|
// The configured environment must precede the inherited environment so
|
||||||
|
// the child resolves the configured display, not a pre-existing one.
|
||||||
|
if len(cmd.Env) < 2 || cmd.Env[0] != "DISPLAY=:1" {
|
||||||
|
t.Fatalf("env %v must start with DISPLAY=:1 override", cmd.Env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStartDisplayProcessRunsInOwnProcessGroup(t *testing.T) {
|
||||||
|
for _, user := range []string{"", "orangepi"} {
|
||||||
|
cmd, err := startDisplayProcess(config.DisplayConfig{
|
||||||
|
Command: "/usr/local/bin/groundstation-display",
|
||||||
|
User: user,
|
||||||
|
Display: ":0",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cmd.SysProcAttr == nil || !cmd.SysProcAttr.Setpgid {
|
||||||
|
t.Fatalf("user %q: kiosk must start in its own process group", user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSupervisor(launch func() (*exec.Cmd, error)) *displaySupervisor {
|
||||||
|
return &displaySupervisor{
|
||||||
|
launch: launch,
|
||||||
|
logger: log.New(io.Discard, "", 0),
|
||||||
|
retryDelay: time.Millisecond,
|
||||||
|
maxDelay: 5 * time.Millisecond,
|
||||||
|
stableAfter: time.Hour,
|
||||||
|
stopGrace: time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisplaySupervisorRestartsKioskAfterUnexpectedExit(t *testing.T) {
|
||||||
|
var starts int32
|
||||||
|
supervisor := testSupervisor(func() (*exec.Cmd, error) {
|
||||||
|
atomic.AddInt32(&starts, 1)
|
||||||
|
return exec.Command("true"), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
supervisor.run(ctx)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitForCondition(t, func() bool { return atomic.LoadInt32(&starts) >= 3 }, "kiosk restarts")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("supervisor did not stop after cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisplaySupervisorKeepsRunningWhenLaunchFails(t *testing.T) {
|
||||||
|
var attempts int32
|
||||||
|
supervisor := testSupervisor(func() (*exec.Cmd, error) {
|
||||||
|
atomic.AddInt32(&attempts, 1)
|
||||||
|
return nil, errors.New("binary missing")
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
supervisor.run(ctx)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitForCondition(t, func() bool { return atomic.LoadInt32(&attempts) >= 3 }, "launch retries")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("supervisor did not stop after cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForCondition(t *testing.T, condition func() bool, description string) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if condition() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatalf("timed out waiting for %s", description)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisplaySupervisorStopsRunningKioskOnShutdown(t *testing.T) {
|
||||||
|
var started atomic.Pointer[exec.Cmd]
|
||||||
|
pipes := make(chan io.ReadCloser, 1)
|
||||||
|
supervisor := testSupervisor(func() (*exec.Cmd, error) {
|
||||||
|
cmd := exec.Command("sh", "-c", "echo started; exec sleep 60")
|
||||||
|
// Mirrors startDisplayProcess: the kiosk runs in its own group.
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
pipe, err := cmd.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
started.Store(cmd)
|
||||||
|
pipes <- pipe
|
||||||
|
return cmd, nil
|
||||||
|
})
|
||||||
|
supervisor.stopGrace = 200 * time.Millisecond
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
supervisor.run(ctx)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// The child signals readiness over its own pipe, which proves Start ran
|
||||||
|
// without racing on cmd fields written by Start.
|
||||||
|
pipe := <-pipes
|
||||||
|
greeting := make([]byte, len("started\n"))
|
||||||
|
if _, err := io.ReadFull(pipe, greeting); err != nil {
|
||||||
|
t.Fatalf("read readiness signal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("supervisor did not stop after cancel")
|
||||||
|
}
|
||||||
|
|
||||||
|
// After the supervisor goroutine has returned, its cmd usage is safely
|
||||||
|
// ordered; the process must be gone.
|
||||||
|
cmd := started.Load()
|
||||||
|
if err := cmd.Process.Signal(syscall.Signal(0)); err == nil {
|
||||||
|
t.Fatal("kiosk process must be gone after shutdown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// liveGroupMembers returns the non-zombie members of a process group. It
|
||||||
|
// relies on procfs and callers must skip on non-Linux platforms.
|
||||||
|
func liveGroupMembers(t *testing.T, pgid int) []string {
|
||||||
|
t.Helper()
|
||||||
|
entries, err := os.ReadDir("/proc")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var live []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
name := entry.Name()
|
||||||
|
pid, err := strconv.Atoi(name)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile("/proc/" + name + "/stat")
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
closing := bytes.LastIndexByte(data, ')')
|
||||||
|
fields := strings.Fields(string(data[closing+1:]))
|
||||||
|
if len(fields) < 3 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fields[0] != "Z" && fields[2] == strconv.Itoa(pgid) {
|
||||||
|
live = append(live, fmt.Sprintf("%d(%s)", pid, fields[0]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return live
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForEmptyGroup(t *testing.T, pgid int) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
for {
|
||||||
|
members := liveGroupMembers(t, pgid)
|
||||||
|
if len(members) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("process group %d still has live members: %v", pgid, members)
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopDisplayProcessTerminatesWholeProcessGroup(t *testing.T) {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
t.Skip("procfs-based group check requires Linux")
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.Command("sh", "-c", "echo started; sleep 60 & wait")
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
pipe, err := cmd.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
greeting := make([]byte, len("started\n"))
|
||||||
|
if _, err := io.ReadFull(pipe, greeting); err != nil {
|
||||||
|
t.Fatalf("read readiness signal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- cmd.Wait() }()
|
||||||
|
|
||||||
|
stopDisplayProcess(cmd, done, time.Second)
|
||||||
|
|
||||||
|
// The interrupt must reach the whole group, including the sleep
|
||||||
|
// descendant that runuser-style children would otherwise hide behind.
|
||||||
|
waitForEmptyGroup(t, cmd.Process.Pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopDisplayProcessEscalatesToKillWhenInterruptIgnored(t *testing.T) {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
t.Skip("procfs-based group check requires Linux")
|
||||||
|
}
|
||||||
|
// Ignored dispositions are inherited by the whole process tree, so the
|
||||||
|
// group ignores SIGINT from birth without a trap-setup race.
|
||||||
|
signal.Ignore(syscall.SIGINT)
|
||||||
|
defer signal.Reset(syscall.SIGINT)
|
||||||
|
|
||||||
|
// The group leader ignores SIGINT and never exits, forcing the
|
||||||
|
// SIGKILL escalation.
|
||||||
|
cmd := exec.Command("sh", "-c", "echo started; while :; do :; done")
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
pipe, err := cmd.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
greeting := make([]byte, len("started\n"))
|
||||||
|
if _, err := io.ReadFull(pipe, greeting); err != nil {
|
||||||
|
t.Fatalf("read readiness signal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- cmd.Wait() }()
|
||||||
|
|
||||||
|
grace := 200 * time.Millisecond
|
||||||
|
began := time.Now()
|
||||||
|
stopDisplayProcess(cmd, done, grace)
|
||||||
|
if elapsed := time.Since(began); elapsed < grace {
|
||||||
|
t.Fatalf("stop returned after %v, grace was %v", elapsed, grace)
|
||||||
|
}
|
||||||
|
|
||||||
|
waitForEmptyGroup(t, cmd.Process.Pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopDisplayProcessKillsGroupSurvivingDirectChildExit(t *testing.T) {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
t.Skip("procfs-based group check requires Linux")
|
||||||
|
}
|
||||||
|
// The tree ignores SIGINT via inheritance, so a group member can
|
||||||
|
// outlive the direct child exactly like a kiosk behind an exiting
|
||||||
|
// runuser; the stop must sweep it instead of trusting the child exit.
|
||||||
|
signal.Ignore(syscall.SIGINT)
|
||||||
|
defer signal.Reset(syscall.SIGINT)
|
||||||
|
|
||||||
|
cmd := exec.Command("sh", "-c", "echo started; sleep 60 & exit 0")
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
pipe, err := cmd.StdoutPipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
greeting := make([]byte, len("started\n"))
|
||||||
|
if _, err := io.ReadFull(pipe, greeting); err != nil {
|
||||||
|
t.Fatalf("read readiness signal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- cmd.Wait() }()
|
||||||
|
|
||||||
|
stopDisplayProcess(cmd, done, 200*time.Millisecond)
|
||||||
|
|
||||||
|
waitForEmptyGroup(t, cmd.Process.Pid)
|
||||||
|
}
|
||||||
+28
-21
@@ -8,9 +8,9 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -20,30 +20,45 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
os.Exit(runMain())
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMain() int {
|
||||||
configPath := flag.String("config", "/etc/groundstation/config.yml", "Ground Station YAML configuration")
|
configPath := flag.String("config", "/etc/groundstation/config.yml", "Ground Station YAML configuration")
|
||||||
stdin := flag.Bool("stdin", false, "read framed data from standard input")
|
stdin := flag.Bool("stdin", false, "read framed data from standard input")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
cfg, err := config.Load(*configPath)
|
cfg, err := config.Load(*configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("load config: %v", err)
|
log.Printf("load config: %v", err)
|
||||||
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
logger, closeLog, err := setupLogger(cfg)
|
logger, closeLog, err := setupLogger(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Print(err)
|
||||||
|
return 1
|
||||||
}
|
}
|
||||||
defer closeLog()
|
defer closeLog()
|
||||||
|
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
if display, err := startDisplay(); err != nil {
|
// Shutdown order is deterministic: video stops first, then the kiosk
|
||||||
log.Printf("display start deferred: %v", err)
|
// display. The defers below run in reverse registration order.
|
||||||
} else {
|
var displayWG sync.WaitGroup
|
||||||
defer func() {
|
defer displayWG.Wait()
|
||||||
_ = display.Process.Signal(os.Interrupt)
|
|
||||||
_ = display.Wait()
|
displayCtx, stopDisplay := context.WithCancel(ctx)
|
||||||
|
defer stopDisplay()
|
||||||
|
|
||||||
|
// The kiosk canvas starts before the video launcher so it is already
|
||||||
|
// mapped on DISPLAY=:0 when video appears.
|
||||||
|
if cfg.Display.Enabled {
|
||||||
|
displayWG.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer displayWG.Done()
|
||||||
|
newDisplaySupervisor(cfg, logger).run(displayCtx)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,9 +70,10 @@ func main() {
|
|||||||
|
|
||||||
if *stdin {
|
if *stdin {
|
||||||
if err := run(ctx, os.Stdin, logger, video, cfg); err != nil && !errors.Is(err, context.Canceled) {
|
if err := run(ctx, os.Stdin, logger, video, cfg); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
log.Fatal(err)
|
logger.Printf("stdin run: %v", err)
|
||||||
|
return 1
|
||||||
}
|
}
|
||||||
return
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
@@ -78,16 +94,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
wait(ctx, time.Second)
|
wait(ctx, time.Second)
|
||||||
}
|
}
|
||||||
}
|
return 0
|
||||||
|
|
||||||
func startDisplay() (*exec.Cmd, error) {
|
|
||||||
cmd := exec.Command("runuser", "-u", "orangepi", "--", "env",
|
|
||||||
"DISPLAY=:0", "XAUTHORITY=/home/orangepi/.Xauthority", "/usr/local/bin/groundstation-display")
|
|
||||||
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
|
||||||
if err := cmd.Start(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return cmd, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupLogger(cfg config.Config) (*log.Logger, func(), error) {
|
func setupLogger(cfg config.Config) (*log.Logger, func(), error) {
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
display:
|
||||||
|
enabled: true
|
||||||
|
# Independent kiosk canvas process. It waits for X11 itself, keeps the
|
||||||
|
# fullscreen black canvas below video, and stops only on shutdown.
|
||||||
|
command: /usr/local/bin/groundstation-display
|
||||||
|
user: orangepi
|
||||||
|
display: :0
|
||||||
|
xauthority: /home/orangepi/.Xauthority
|
||||||
|
|
||||||
serial:
|
serial:
|
||||||
path: /dev/ttyS0
|
path: /dev/ttyS0
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Ground Station RC and video supervisor
|
Description=Ground Station RC, kiosk display and video supervisor
|
||||||
Wants=graphical.target
|
Wants=graphical.target
|
||||||
After=graphical.target display-manager.service
|
After=graphical.target display-manager.service
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,18 @@ import (
|
|||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// DisplayConfig configures the independent kiosk canvas process.
|
||||||
|
type DisplayConfig struct {
|
||||||
|
Enabled bool `yaml:"enabled"`
|
||||||
|
Command string `yaml:"command"`
|
||||||
|
User string `yaml:"user"`
|
||||||
|
Display string `yaml:"display"`
|
||||||
|
Xauthority string `yaml:"xauthority"`
|
||||||
|
}
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Serial struct {
|
Display DisplayConfig `yaml:"display"`
|
||||||
|
Serial struct {
|
||||||
Path string `yaml:"path"`
|
Path string `yaml:"path"`
|
||||||
} `yaml:"serial"`
|
} `yaml:"serial"`
|
||||||
Video struct {
|
Video struct {
|
||||||
@@ -24,6 +34,7 @@ type Config struct {
|
|||||||
|
|
||||||
func Default() Config {
|
func Default() Config {
|
||||||
var c Config
|
var c Config
|
||||||
|
c.Display = DefaultDisplay()
|
||||||
c.Serial.Path = "/dev/ttyS0"
|
c.Serial.Path = "/dev/ttyS0"
|
||||||
c.Video.Enabled = true
|
c.Video.Enabled = true
|
||||||
c.Video.AuxIndex = 5 // AUX2, zero-based
|
c.Video.AuxIndex = 5 // AUX2, zero-based
|
||||||
@@ -33,6 +44,18 @@ func Default() Config {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DefaultDisplay starts the kiosk canvas before video on the desktop X
|
||||||
|
// server owned by the unprivileged display user.
|
||||||
|
func DefaultDisplay() DisplayConfig {
|
||||||
|
return DisplayConfig{
|
||||||
|
Enabled: true,
|
||||||
|
Command: "/usr/local/bin/groundstation-display",
|
||||||
|
User: "orangepi",
|
||||||
|
Display: ":0",
|
||||||
|
Xauthority: "/home/orangepi/.Xauthority",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func Load(path string) (Config, error) {
|
func Load(path string) (Config, error) {
|
||||||
config := Default()
|
config := Default()
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultConfigStartsKioskDisplay(t *testing.T) {
|
||||||
|
cfg := Default()
|
||||||
|
|
||||||
|
if !cfg.Display.Enabled {
|
||||||
|
t.Fatal("kiosk display must be enabled by default")
|
||||||
|
}
|
||||||
|
if cfg.Display.Command != "/usr/local/bin/groundstation-display" {
|
||||||
|
t.Fatalf("command=%q", cfg.Display.Command)
|
||||||
|
}
|
||||||
|
if cfg.Display.User != "orangepi" {
|
||||||
|
t.Fatalf("user=%q", cfg.Display.User)
|
||||||
|
}
|
||||||
|
if cfg.Display.Display != ":0" {
|
||||||
|
t.Fatalf("display=%q want :0", cfg.Display.Display)
|
||||||
|
}
|
||||||
|
if cfg.Display.Xauthority != "/home/orangepi/.Xauthority" {
|
||||||
|
t.Fatalf("xauthority=%q", cfg.Display.Xauthority)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadOverridesDisplaySettings(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
body := "display:\n enabled: false\n command: /bin/kiosk\n"
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := Load(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Display.Enabled {
|
||||||
|
t.Fatal("display override must disable the kiosk")
|
||||||
|
}
|
||||||
|
if cfg.Display.Command != "/bin/kiosk" {
|
||||||
|
t.Fatalf("command=%q want /bin/kiosk", cfg.Display.Command)
|
||||||
|
}
|
||||||
|
if cfg.Display.Display != ":0" {
|
||||||
|
t.Fatalf("display=%q want default :0", cfg.Display.Display)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Package display owns the Ground Station kiosk layers. The kiosk runs
|
||||||
|
// independently of WFB, the transmitter and the RC video knob: it waits for
|
||||||
|
// its rendering target to appear, keeps its windows alive and stops only
|
||||||
|
// when told to. Each target drives two independent visual layers: a
|
||||||
|
// fullscreen fallback/menu canvas below video, visible while decoded pilot
|
||||||
|
// video is absent, and a transparent, input-transparent OSD overlay above
|
||||||
|
// video, reserved as the future flight OSD rendering surface. When video
|
||||||
|
// output is presented the video window takes rendering priority and the
|
||||||
|
// fallback disappears, returning when video ends. Presence is observed from
|
||||||
|
// the video output itself on the display server, never from WFB or launcher
|
||||||
|
// processes, and the video pipeline is never moved into, coupled to or
|
||||||
|
// touched by this package. Each target (X11/Viture today, MIPI/touch later)
|
||||||
|
// provides its own openers and templates instead of one global layout.
|
||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Canvas is the minimal drawing surface a Template renders onto.
|
||||||
|
type Canvas interface {
|
||||||
|
Size() (width, height int)
|
||||||
|
Clear()
|
||||||
|
Text(x, y int, message string)
|
||||||
|
Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Template renders one target-specific layout. Templates belong to a display
|
||||||
|
// target; there is no shared global layout across targets.
|
||||||
|
type Template interface {
|
||||||
|
Draw(canvas Canvas)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session is one live connection to a display target.
|
||||||
|
type Session interface {
|
||||||
|
Canvas() Canvas
|
||||||
|
// WaitEvent blocks until the target asks for a refresh, the context is
|
||||||
|
// done, or the session fails. redraw reports whether the template should
|
||||||
|
// be drawn again.
|
||||||
|
WaitEvent(ctx context.Context) (redraw bool, err error)
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opener connects to a display target. Implementations are called repeatedly
|
||||||
|
// while the target is unavailable and must stay safe for that.
|
||||||
|
type Opener interface {
|
||||||
|
Open(ctx context.Context) (Session, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options tune the kiosk lifecycle loop. Zero values select the defaults.
|
||||||
|
type Options struct {
|
||||||
|
// RetryDelay is the first wait after a failed connect or lost session.
|
||||||
|
RetryDelay time.Duration
|
||||||
|
// MaxDelay bounds the exponential reconnect backoff.
|
||||||
|
MaxDelay time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o Options) withDefaults() Options {
|
||||||
|
if o.RetryDelay <= 0 {
|
||||||
|
o.RetryDelay = 500 * time.Millisecond
|
||||||
|
}
|
||||||
|
if o.MaxDelay <= 0 {
|
||||||
|
o.MaxDelay = 5 * time.Second
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run owns the kiosk display lifecycle until ctx is cancelled. Temporary
|
||||||
|
// unavailability of the target, for example X11 not being up yet, never
|
||||||
|
// returns an error: Run retries with bounded backoff and only stops when the
|
||||||
|
// context is cancelled, so the Ground Station supervisor stays up.
|
||||||
|
func Run(ctx context.Context, opener Opener, template Template, options Options) error {
|
||||||
|
opts := options.withDefaults()
|
||||||
|
delay := opts.RetryDelay
|
||||||
|
for {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
session, err := opener.Open(ctx)
|
||||||
|
if err != nil {
|
||||||
|
if !sleep(ctx, delay) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
delay = nextDelay(delay, opts.MaxDelay)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay = opts.RetryDelay
|
||||||
|
canvas := session.Canvas()
|
||||||
|
template.Draw(canvas)
|
||||||
|
for ctx.Err() == nil {
|
||||||
|
redraw, err := session.WaitEvent(ctx)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if redraw {
|
||||||
|
template.Draw(canvas)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = session.Close()
|
||||||
|
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !sleep(ctx, delay) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
delay = nextDelay(delay, opts.MaxDelay)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layer is one independent visual layer of a display target: its own
|
||||||
|
// connection, window role and template. A lost or degraded layer never
|
||||||
|
// affects the others, so a missing overlay cannot disturb the fallback
|
||||||
|
// canvas and neither can disturb pilot video.
|
||||||
|
type Layer struct {
|
||||||
|
// Name identifies the layer in diagnostics.
|
||||||
|
Name string
|
||||||
|
// Opener connects to the layer's own window on the target.
|
||||||
|
Opener Opener
|
||||||
|
// Template renders the layer's target-specific layout.
|
||||||
|
Template Template
|
||||||
|
// Options tune the layer's lifecycle loop. Zero values select the
|
||||||
|
// defaults.
|
||||||
|
Options Options
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunLayers drives every layer of a display target until ctx is cancelled,
|
||||||
|
// each on its own connection with its own reconnect backoff. A layer whose
|
||||||
|
// target keeps failing keeps retrying and never stops the other layers, so
|
||||||
|
// the Ground Station supervisor stays up. RunLayers returns only after every
|
||||||
|
// layer has stopped.
|
||||||
|
func RunLayers(ctx context.Context, layers []Layer) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for _, layer := range layers {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(layer Layer) {
|
||||||
|
defer wg.Done()
|
||||||
|
_ = Run(ctx, layer.Opener, layer.Template, layer.Options)
|
||||||
|
}(layer)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextDelay(delay, max time.Duration) time.Duration {
|
||||||
|
delay *= 2
|
||||||
|
if delay > max {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return delay
|
||||||
|
}
|
||||||
|
|
||||||
|
func sleep(ctx context.Context, duration time.Duration) bool {
|
||||||
|
timer := time.NewTimer(duration)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false
|
||||||
|
case <-timer.C:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeCanvas struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
width, height int
|
||||||
|
clears int
|
||||||
|
texts []string
|
||||||
|
flushes int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeCanvas) Size() (int, int) { return c.width, c.height }
|
||||||
|
func (c *fakeCanvas) Clear() {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.clears++
|
||||||
|
}
|
||||||
|
func (c *fakeCanvas) Text(_, _ int, message string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.texts = append(c.texts, message)
|
||||||
|
}
|
||||||
|
func (c *fakeCanvas) Flush() {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.flushes++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeCanvas) lineCount() int {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return len(c.texts)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeCanvas) lines() []string {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return append([]string(nil), c.texts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *fakeCanvas) drawCounts() (clears, flushes int) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return c.clears, c.flushes
|
||||||
|
}
|
||||||
|
|
||||||
|
type eventResult struct {
|
||||||
|
redraw bool
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeSession struct {
|
||||||
|
canvas *fakeCanvas
|
||||||
|
events chan eventResult
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
closed int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFakeSession() *fakeSession {
|
||||||
|
return &fakeSession{
|
||||||
|
canvas: &fakeCanvas{width: 800, height: 600},
|
||||||
|
events: make(chan eventResult, 8),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeSession) Canvas() Canvas { return s.canvas }
|
||||||
|
|
||||||
|
func (s *fakeSession) WaitEvent(ctx context.Context) (bool, error) {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false, ctx.Err()
|
||||||
|
case result := <-s.events:
|
||||||
|
return result.redraw, result.err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeSession) Close() error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.closed++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *fakeSession) closeCount() int {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.closed
|
||||||
|
}
|
||||||
|
|
||||||
|
type fakeOpener struct {
|
||||||
|
open func(attempt int) (Session, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o fakeOpener) Open(context.Context) (Session, error) {
|
||||||
|
return o.open(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitFor(t *testing.T, condition func() bool, description string) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if condition() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatalf("timed out waiting for %s", description)
|
||||||
|
}
|
||||||
|
|
||||||
|
func tinyOptions() Options {
|
||||||
|
return Options{RetryDelay: time.Millisecond, MaxDelay: 2 * time.Millisecond}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunDrawsTemplateWhenTargetConnects(t *testing.T) {
|
||||||
|
session := newFakeSession()
|
||||||
|
opener := fakeOpener{open: func(int) (Session, error) { return session, nil }}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- Run(ctx, opener, NewStatusTemplate("hello"), tinyOptions())
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool { return session.canvas.lineCount() > 0 }, "initial template draw")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run did not stop after cancel")
|
||||||
|
}
|
||||||
|
|
||||||
|
if clears, flushes := session.canvas.drawCounts(); clears == 0 || flushes == 0 {
|
||||||
|
t.Fatalf("template must clear and flush the canvas (clears=%d flushes=%d)", clears, flushes)
|
||||||
|
}
|
||||||
|
if session.closeCount() != 1 {
|
||||||
|
t.Fatalf("session closed %d times, want 1", session.closeCount())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunKeepsRetryingWhileTargetUnavailable(t *testing.T) {
|
||||||
|
session := newFakeSession()
|
||||||
|
var opens int32
|
||||||
|
opener := fakeOpener{open: func(int) (Session, error) {
|
||||||
|
if atomic.AddInt32(&opens, 1) <= 2 {
|
||||||
|
return nil, errors.New("x11 down")
|
||||||
|
}
|
||||||
|
return session, nil
|
||||||
|
}}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- Run(ctx, opener, NewStatusTemplate("hello"), tinyOptions())
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
return atomic.LoadInt32(&opens) >= 3 && session.canvas.lineCount() > 0
|
||||||
|
}, "connect after retries")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run did not stop after cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunRedrawsTemplateOnEvent(t *testing.T) {
|
||||||
|
session := newFakeSession()
|
||||||
|
opener := fakeOpener{open: func(int) (Session, error) { return session, nil }}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- Run(ctx, opener, NewStatusTemplate("hello"), tinyOptions())
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool { return session.canvas.lineCount() == 1 }, "initial template draw")
|
||||||
|
session.events <- eventResult{redraw: true}
|
||||||
|
waitFor(t, func() bool { return session.canvas.lineCount() == 2 }, "redraw on event")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run did not stop after cancel")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunReconnectsAfterSessionFailure(t *testing.T) {
|
||||||
|
first := newFakeSession()
|
||||||
|
second := newFakeSession()
|
||||||
|
var opens int32
|
||||||
|
opener := fakeOpener{open: func(int) (Session, error) {
|
||||||
|
if atomic.AddInt32(&opens, 1) == 1 {
|
||||||
|
return first, nil
|
||||||
|
}
|
||||||
|
return second, nil
|
||||||
|
}}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- Run(ctx, opener, NewStatusTemplate("hello"), tinyOptions())
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool { return first.canvas.lineCount() == 1 }, "draw on first session")
|
||||||
|
first.events <- eventResult{err: errors.New("connection lost")}
|
||||||
|
waitFor(t, func() bool { return second.canvas.lineCount() == 1 }, "draw on reconnected session")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("run: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run did not stop after cancel")
|
||||||
|
}
|
||||||
|
|
||||||
|
if first.closeCount() != 1 {
|
||||||
|
t.Fatalf("failed session closed %d times, want 1", first.closeCount())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunLayersDrawsEveryLayerOnItsOwnCanvas(t *testing.T) {
|
||||||
|
canvasSession := newFakeSession()
|
||||||
|
osdSession := newFakeSession()
|
||||||
|
layers := []Layer{
|
||||||
|
{
|
||||||
|
Name: "fallback-canvas",
|
||||||
|
Opener: fakeOpener{open: func(int) (Session, error) { return canvasSession, nil }},
|
||||||
|
Template: NewStatusTemplate("canvas"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "osd-overlay",
|
||||||
|
Opener: fakeOpener{open: func(int) (Session, error) { return osdSession, nil }},
|
||||||
|
Template: NewOSDTemplate(NewVideoPresence()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
RunLayers(ctx, layers)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool { return canvasSession.canvas.lineCount() == 1 }, "canvas layer draw")
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
clears, _ := osdSession.canvas.drawCounts()
|
||||||
|
return clears == 1
|
||||||
|
}, "osd layer transparent clear")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run layers did not stop after cancel")
|
||||||
|
}
|
||||||
|
if got := canvasSession.closeCount(); got != 1 {
|
||||||
|
t.Fatalf("canvas session closed %d times, want 1", got)
|
||||||
|
}
|
||||||
|
if got := osdSession.closeCount(); got != 1 {
|
||||||
|
t.Fatalf("osd session closed %d times, want 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunLayersKeepsOtherLayerAliveWhenOneTargetFails(t *testing.T) {
|
||||||
|
alive := newFakeSession()
|
||||||
|
layers := []Layer{
|
||||||
|
{
|
||||||
|
Name: "dead",
|
||||||
|
Opener: fakeOpener{open: func(int) (Session, error) { return nil, errors.New("target down") }},
|
||||||
|
Template: NewStatusTemplate("never drawn"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "alive",
|
||||||
|
Opener: fakeOpener{open: func(int) (Session, error) { return alive, nil }},
|
||||||
|
Template: NewOSDTemplate(NewVideoPresence()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
RunLayers(ctx, layers)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitFor(t, func() bool {
|
||||||
|
clears, _ := alive.canvas.drawCounts()
|
||||||
|
return clears == 1
|
||||||
|
}, "alive layer keeps drawing while the other target fails")
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("run layers did not stop after cancel")
|
||||||
|
}
|
||||||
|
if got := alive.closeCount(); got != 1 {
|
||||||
|
t.Fatalf("alive session closed %d times, want 1", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunStopsWithoutConnectingWhenContextAlreadyCancelled(t *testing.T) {
|
||||||
|
var opens int32
|
||||||
|
opener := fakeOpener{open: func(int) (Session, error) {
|
||||||
|
atomic.AddInt32(&opens, 1)
|
||||||
|
return nil, errors.New("must not be called")
|
||||||
|
}}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
if err := Run(ctx, opener, NewStatusTemplate("hello"), tinyOptions()); err != nil {
|
||||||
|
t.Fatalf("run: %v", err)
|
||||||
|
}
|
||||||
|
if atomic.LoadInt32(&opens) != 0 {
|
||||||
|
t.Fatalf("opener called %d times after cancellation", opens)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
// FallbackTemplate is the no-video kiosk layout: a cleared black canvas with
|
||||||
|
// the fallback lines. While decoded video is present the fallback
|
||||||
|
// disappears: the canvas stays plain black so the video window keeps
|
||||||
|
// rendering priority without stale text around or behind it, and the exact
|
||||||
|
// fallback lines return when video ends.
|
||||||
|
type FallbackTemplate struct {
|
||||||
|
fallback StatusTemplate
|
||||||
|
video *VideoPresence
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFallbackTemplate builds a template that draws the given fallback lines
|
||||||
|
// only while the shared presence reports no video.
|
||||||
|
func NewFallbackTemplate(video *VideoPresence, lines ...string) FallbackTemplate {
|
||||||
|
return FallbackTemplate{fallback: NewStatusTemplate(lines...), video: video}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t FallbackTemplate) Draw(canvas Canvas) {
|
||||||
|
canvas.Clear()
|
||||||
|
if !t.video.Active() {
|
||||||
|
drawLines(canvas, t.fallback.lines)
|
||||||
|
}
|
||||||
|
canvas.Flush()
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
const wantFallbackText = "Brak połączenia WFB"
|
||||||
|
|
||||||
|
func TestFallbackTemplateShowsExactTextWhileVideoAbsent(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
|
||||||
|
NewFallbackTemplate(presence, wantFallbackText).Draw(canvas)
|
||||||
|
|
||||||
|
clears, flushes := canvas.drawCounts()
|
||||||
|
if clears != 1 || flushes != 1 {
|
||||||
|
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
|
||||||
|
}
|
||||||
|
lines := canvas.lines()
|
||||||
|
if len(lines) != 1 || lines[0] != wantFallbackText {
|
||||||
|
t.Fatalf("lines=%q want [%q]", lines, wantFallbackText)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFallbackTemplateDisappearsWhileVideoPresent(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
presence.SetActive(true)
|
||||||
|
|
||||||
|
NewFallbackTemplate(presence, wantFallbackText).Draw(canvas)
|
||||||
|
|
||||||
|
clears, flushes := canvas.drawCounts()
|
||||||
|
if clears != 1 || flushes != 1 {
|
||||||
|
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
|
||||||
|
}
|
||||||
|
if lines := canvas.lines(); len(lines) != 0 {
|
||||||
|
t.Fatalf("video has priority: fallback lines %q must disappear", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFallbackTemplateReturnsWhenVideoEnds(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
presence.SetActive(true)
|
||||||
|
template := NewFallbackTemplate(presence, wantFallbackText)
|
||||||
|
|
||||||
|
template.Draw(canvas)
|
||||||
|
if lines := canvas.lines(); len(lines) != 0 {
|
||||||
|
t.Fatalf("lines=%q must stay empty while video is present", lines)
|
||||||
|
}
|
||||||
|
|
||||||
|
presence.SetActive(false)
|
||||||
|
template.Draw(canvas)
|
||||||
|
|
||||||
|
lines := canvas.lines()
|
||||||
|
if len(lines) != 1 || lines[0] != wantFallbackText {
|
||||||
|
t.Fatalf("lines=%q want fallback [%q] after video end", lines, wantFallbackText)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
// OSDTemplate is the flight OSD layout of a display target: a transparent,
|
||||||
|
// input-transparent surface above pilot video, reserved as the future OSD
|
||||||
|
// rendering surface. It presents nothing yet and never draws the fallback:
|
||||||
|
// the OSD is a telemetry surface, not a video substitute, and WFB or video
|
||||||
|
// decode never move into the UI process to feed it. Flight telemetry
|
||||||
|
// rendering arrives in later Ground Station work; the shared presence keeps
|
||||||
|
// the OSD on the same video lifecycle as the fallback canvas, so the session
|
||||||
|
// redraws it on every presence transition.
|
||||||
|
type OSDTemplate struct {
|
||||||
|
video *VideoPresence
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewOSDTemplate builds the OSD surface for a target.
|
||||||
|
func NewOSDTemplate(video *VideoPresence) OSDTemplate {
|
||||||
|
return OSDTemplate{video: video}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t OSDTemplate) Draw(canvas Canvas) {
|
||||||
|
canvas.Clear()
|
||||||
|
canvas.Flush()
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestOSDTemplateStaysTransparentWhileVideoAbsent(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
|
||||||
|
NewOSDTemplate(NewVideoPresence()).Draw(canvas)
|
||||||
|
|
||||||
|
clears, flushes := canvas.drawCounts()
|
||||||
|
if clears != 1 || flushes != 1 {
|
||||||
|
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
|
||||||
|
}
|
||||||
|
if lines := canvas.lines(); len(lines) != 0 {
|
||||||
|
t.Fatalf("OSD lines=%q want none: the OSD is a telemetry surface, not a fallback", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOSDTemplateStaysTransparentWhileVideoPresent(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
presence.SetActive(true)
|
||||||
|
|
||||||
|
NewOSDTemplate(presence).Draw(canvas)
|
||||||
|
|
||||||
|
if lines := canvas.lines(); len(lines) != 0 {
|
||||||
|
t.Fatalf("OSD lines=%q want none while video is present", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOSDTemplateNeverDrawsTheFallbackText(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
template := NewOSDTemplate(presence)
|
||||||
|
|
||||||
|
for _, active := range []bool{false, true, false} {
|
||||||
|
presence.SetActive(active)
|
||||||
|
template.Draw(canvas)
|
||||||
|
if lines := canvas.lines(); len(lines) != 0 {
|
||||||
|
t.Fatalf("lines=%q after presence=%v want none", lines, active)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
// StatusTemplate is the fallback kiosk layout: a cleared black canvas with
|
||||||
|
// status lines. It is the "no pilot video" state of a display target.
|
||||||
|
type StatusTemplate struct {
|
||||||
|
lines []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewStatusTemplate builds a template that draws the given status lines.
|
||||||
|
func NewStatusTemplate(lines ...string) StatusTemplate {
|
||||||
|
return StatusTemplate{lines: lines}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t StatusTemplate) Draw(canvas Canvas) {
|
||||||
|
canvas.Clear()
|
||||||
|
drawLines(canvas, t.lines)
|
||||||
|
canvas.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawLines(canvas Canvas, lines []string) {
|
||||||
|
_, height := canvas.Size()
|
||||||
|
y := height / 2
|
||||||
|
for _, line := range lines {
|
||||||
|
canvas.Text(32, y, line)
|
||||||
|
y += 32
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestStatusTemplateDrawsBlackCanvasWithLine(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
|
||||||
|
NewStatusTemplate("Brak polaczenia WFB").Draw(canvas)
|
||||||
|
|
||||||
|
clears, flushes := canvas.drawCounts()
|
||||||
|
if clears != 1 || flushes != 1 {
|
||||||
|
t.Fatalf("clears=%d flushes=%d want 1 and 1", clears, flushes)
|
||||||
|
}
|
||||||
|
lines := canvas.lines()
|
||||||
|
if len(lines) != 1 || lines[0] != "Brak polaczenia WFB" {
|
||||||
|
t.Fatalf("lines=%v want [Brak polaczenia WFB]", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusTemplateDrawsEveryProvidedLine(t *testing.T) {
|
||||||
|
canvas := &fakeCanvas{width: 800, height: 600}
|
||||||
|
|
||||||
|
NewStatusTemplate("first", "second").Draw(canvas)
|
||||||
|
|
||||||
|
lines := canvas.lines()
|
||||||
|
if len(lines) != 2 || lines[0] != "first" || lines[1] != "second" {
|
||||||
|
t.Fatalf("lines=%v want [first second]", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import "sync/atomic"
|
||||||
|
|
||||||
|
// VideoPresence is the shared decoded-video signal between a display target
|
||||||
|
// session and the templates it drives. Sessions update it from
|
||||||
|
// display-server events about the video output itself: a presented video
|
||||||
|
// window is presence, its unmap or destroy is video end. Nothing here
|
||||||
|
// inspects WFB or launcher processes, so a running-but-silent receiver never
|
||||||
|
// hides the fallback and the video pipeline is never touched.
|
||||||
|
type VideoPresence struct {
|
||||||
|
active atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewVideoPresence starts with video absent, so the fallback is visible
|
||||||
|
// before the first presented video output.
|
||||||
|
func NewVideoPresence() *VideoPresence {
|
||||||
|
return &VideoPresence{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active reports whether decoded video output is being presented.
|
||||||
|
func (p *VideoPresence) Active() bool {
|
||||||
|
return p.active.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetActive records video presence and reports whether the state changed, so
|
||||||
|
// callers can trigger exactly one redraw per lifecycle transition.
|
||||||
|
func (p *VideoPresence) SetActive(active bool) bool {
|
||||||
|
return p.active.Swap(active) != active
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestVideoPresenceTransitionsReportChange(t *testing.T) {
|
||||||
|
presence := NewVideoPresence()
|
||||||
|
|
||||||
|
if presence.Active() {
|
||||||
|
t.Fatal("video must be absent before any signal")
|
||||||
|
}
|
||||||
|
if !presence.SetActive(true) {
|
||||||
|
t.Fatal("first video appearance must report a change")
|
||||||
|
}
|
||||||
|
if !presence.Active() {
|
||||||
|
t.Fatal("video must be active after appearance")
|
||||||
|
}
|
||||||
|
if presence.SetActive(true) {
|
||||||
|
t.Fatal("repeated appearance must not report a change")
|
||||||
|
}
|
||||||
|
if !presence.SetActive(false) {
|
||||||
|
t.Fatal("video end must report a change")
|
||||||
|
}
|
||||||
|
if presence.Active() {
|
||||||
|
t.Fatal("video must be inactive after end")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,748 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf16"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/xgb"
|
||||||
|
"github.com/BurntSushi/xgb/shape"
|
||||||
|
"github.com/BurntSushi/xgb/xproto"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// iso10646FontPattern selects a Unicode-capable fixed font so the exact
|
||||||
|
// fallback text keeps its diacritics on screen.
|
||||||
|
iso10646FontPattern = "*fixed*iso10646-1"
|
||||||
|
// asciiFontName is the degradation path when no Unicode font exists;
|
||||||
|
// text drawn with it is folded to ASCII.
|
||||||
|
asciiFontName = "fixed"
|
||||||
|
// maxImageText16Units bounds one ImageText16 request to the protocol's
|
||||||
|
// 1-byte string length (2 bytes per unit).
|
||||||
|
maxImageText16Units = 127
|
||||||
|
// windowTypePropertyName is the EWMH property naming a window's role.
|
||||||
|
windowTypePropertyName = "_NET_WM_WINDOW_TYPE"
|
||||||
|
// layerMarkerPropertyName tags Ground Station layer windows so sibling
|
||||||
|
// layers — and their window-manager frames — never count as video
|
||||||
|
// output for each other.
|
||||||
|
layerMarkerPropertyName = "_GROUNDSTATION_LAYER"
|
||||||
|
)
|
||||||
|
|
||||||
|
// osdEventMask selects only repaint bookkeeping for the OSD overlay: no
|
||||||
|
// pointer, key or motion events, so the server never routes device input to
|
||||||
|
// the overlay even before its empty input shape is applied.
|
||||||
|
const osdEventMask = xproto.EventMaskExposure
|
||||||
|
|
||||||
|
// deviceInputEventMask are the pointer and key selection bits a layer above
|
||||||
|
// video must never select: device input belongs to the windows below.
|
||||||
|
const deviceInputEventMask = xproto.EventMaskKeyPress | xproto.EventMaskKeyRelease |
|
||||||
|
xproto.EventMaskButtonPress | xproto.EventMaskButtonRelease |
|
||||||
|
xproto.EventMaskPointerMotion
|
||||||
|
|
||||||
|
// LayerRole orders a Ground Station window against presented video output.
|
||||||
|
// The fallback/menu canvas stays below video; the OSD overlay stays above.
|
||||||
|
type LayerRole int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// RoleBelow marks the fullscreen fallback/menu canvas under video.
|
||||||
|
RoleBelow LayerRole = iota
|
||||||
|
// RoleAbove marks the transparent, input-transparent OSD overlay above
|
||||||
|
// video.
|
||||||
|
RoleAbove
|
||||||
|
)
|
||||||
|
|
||||||
|
// layerMarkerValue is the layer marker payload identifying a role's window
|
||||||
|
// as our own.
|
||||||
|
func layerMarkerValue(role LayerRole) string {
|
||||||
|
if role == RoleAbove {
|
||||||
|
return "osd"
|
||||||
|
}
|
||||||
|
return "kiosk"
|
||||||
|
}
|
||||||
|
|
||||||
|
// markerIsGroundstation reports whether a layer marker payload marks one of
|
||||||
|
// our own windows: those are Ground Station layers, never video output.
|
||||||
|
func markerIsGroundstation(marker string) bool {
|
||||||
|
return marker == layerMarkerValue(RoleBelow) || marker == layerMarkerValue(RoleAbove)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ewmhWindowTypeName is the EWMH window role announced for a layer. The OSD
|
||||||
|
// overlay announces DOCK, the always-above helper role, so window managers
|
||||||
|
// never decorate or bury it; the fallback canvas keeps announcing nothing,
|
||||||
|
// as before.
|
||||||
|
func ewmhWindowTypeName(role LayerRole) string {
|
||||||
|
if role == RoleAbove {
|
||||||
|
return "_NET_WM_WINDOW_TYPE_DOCK"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// fullscreenState is the wmctrl stacking state for a layer role.
|
||||||
|
func fullscreenState(role LayerRole) string {
|
||||||
|
if role == RoleAbove {
|
||||||
|
return "above"
|
||||||
|
}
|
||||||
|
return "below"
|
||||||
|
}
|
||||||
|
|
||||||
|
// stackModeForVideoAppear is where a layer goes relative to the first
|
||||||
|
// presented video window: the canvas parks below it, the OSD rises above it.
|
||||||
|
func stackModeForVideoAppear(role LayerRole) uint32 {
|
||||||
|
if role == RoleAbove {
|
||||||
|
return xproto.StackModeAbove
|
||||||
|
}
|
||||||
|
return xproto.StackModeBelow
|
||||||
|
}
|
||||||
|
|
||||||
|
// raisesOnVideoEnd reports whether a layer raises itself when video ends:
|
||||||
|
// only the below canvas needs that to make the fallback visible again; the
|
||||||
|
// OSD overlay is already above everything.
|
||||||
|
func raisesOnVideoEnd(role LayerRole) bool {
|
||||||
|
return role == RoleBelow
|
||||||
|
}
|
||||||
|
|
||||||
|
// transparentShapeKinds are the shape regions cleared to empty so the OSD
|
||||||
|
// overlay is transparent and passes input through: an empty input shape
|
||||||
|
// never receives pointer or key events, and an empty bounding shape presents
|
||||||
|
// nothing over the video below — with or without a compositor.
|
||||||
|
func transparentShapeKinds() []shape.Kind {
|
||||||
|
return []shape.Kind{shape.SkInput, shape.SkBounding}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ewmhNonVideoTypes are EWMH auxiliary window roles that never count as
|
||||||
|
// video output: desktop shells, panels, menus, dialogs and notifications
|
||||||
|
// must not suppress the fallback. Windows without the property — typical
|
||||||
|
// for plain video output — count as video.
|
||||||
|
var ewmhNonVideoTypes = map[string]bool{
|
||||||
|
"DESKTOP": true,
|
||||||
|
"DOCK": true,
|
||||||
|
"TOOLBAR": true,
|
||||||
|
"MENU": true,
|
||||||
|
"UTILITY": true,
|
||||||
|
"SPLASH": true,
|
||||||
|
"DIALOG": true,
|
||||||
|
"NOTIFICATION": true,
|
||||||
|
"TOOLTIP": true,
|
||||||
|
"COMBO": true,
|
||||||
|
"DROPDOWN_MENU": true,
|
||||||
|
"POPUP_MENU": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// X11Opener connects to an X server (selected by DISPLAY in the environment)
|
||||||
|
// and maps one fullscreen kiosk window for the layer role it is built with:
|
||||||
|
// the fallback/menu canvas below video (RoleBelow) or the transparent,
|
||||||
|
// input-transparent OSD overlay above video (RoleAbove). It is the display
|
||||||
|
// target for the Viture screen; future targets such as MIPI/touch provide
|
||||||
|
// their own Opener and templates.
|
||||||
|
type X11Opener struct {
|
||||||
|
// PollInterval is how often X events are drained while waiting, so that
|
||||||
|
// cancellation stays responsive. Zero selects 100 ms.
|
||||||
|
PollInterval time.Duration
|
||||||
|
// Fullscreen applies the fullscreen window state. It defaults to
|
||||||
|
// shelling out to wmctrl; tests may replace it. A failure is logged and
|
||||||
|
// the window degrades to a plain window.
|
||||||
|
Fullscreen func(args []string) error
|
||||||
|
// Video is the shared decoded-video presence signal. The session feeds
|
||||||
|
// it from the video output window's own lifecycle on the root screen;
|
||||||
|
// templates consume it to show or hide themselves. When nil the opener
|
||||||
|
// tracks presence in a private signal.
|
||||||
|
Video *VideoPresence
|
||||||
|
// Role orders this layer's window against presented video: RoleBelow
|
||||||
|
// for the fallback/menu canvas, RoleAbove for the OSD overlay.
|
||||||
|
Role LayerRole
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o X11Opener) presence() *VideoPresence {
|
||||||
|
if o.Video != nil {
|
||||||
|
return o.Video
|
||||||
|
}
|
||||||
|
return NewVideoPresence()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o X11Opener) applyFullscreen(args []string) error {
|
||||||
|
if o.Fullscreen != nil {
|
||||||
|
return o.Fullscreen(args)
|
||||||
|
}
|
||||||
|
return exec.Command("wmctrl", args...).Run()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o X11Opener) pollInterval() time.Duration {
|
||||||
|
if o.PollInterval > 0 {
|
||||||
|
return o.PollInterval
|
||||||
|
}
|
||||||
|
return 100 * time.Millisecond
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open connects to the X server and maps the kiosk window. Failure is
|
||||||
|
// expected while the display manager is starting; the caller retries.
|
||||||
|
func (o X11Opener) Open(ctx context.Context) (Session, error) {
|
||||||
|
conn, err := xgb.NewConn()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("connect X11: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
screen := xproto.Setup(conn).DefaultScreen(conn)
|
||||||
|
window, err := xproto.NewWindowId(conn)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, fmt.Errorf("allocate window: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The OSD overlay selects no device input even before its empty input
|
||||||
|
// shape exists; the canvas keeps its legacy exposure-only mask.
|
||||||
|
eventMask := uint32(xproto.EventMaskExposure)
|
||||||
|
if o.Role == RoleAbove {
|
||||||
|
eventMask = osdEventMask
|
||||||
|
}
|
||||||
|
values := uint32(xproto.CwBackPixel | xproto.CwEventMask)
|
||||||
|
xproto.CreateWindow(conn, screen.RootDepth, window, screen.Root,
|
||||||
|
0, 0, screen.WidthInPixels, screen.HeightInPixels, 0,
|
||||||
|
xproto.WindowClassInputOutput, screen.RootVisual, values,
|
||||||
|
[]uint32{screen.BlackPixel, eventMask})
|
||||||
|
// Tag the window as a Ground Station layer and announce its EWMH role
|
||||||
|
// before mapping, so no observer or window manager ever sees an
|
||||||
|
// untagged frame of our own layers.
|
||||||
|
markerAtom := internAtom(conn, layerMarkerPropertyName)
|
||||||
|
if markerAtom != 0 {
|
||||||
|
marker := layerMarkerValue(o.Role)
|
||||||
|
xproto.ChangeProperty(conn, xproto.PropModeReplace, window, markerAtom,
|
||||||
|
xproto.AtomString, 8, uint32(len(marker)), []byte(marker))
|
||||||
|
}
|
||||||
|
if name := ewmhWindowTypeName(o.Role); name != "" {
|
||||||
|
typeProp := internAtom(conn, windowTypePropertyName)
|
||||||
|
roleAtom := internAtom(conn, name)
|
||||||
|
if typeProp != 0 && roleAtom != 0 {
|
||||||
|
value := make([]byte, 4)
|
||||||
|
binary.LittleEndian.PutUint32(value, uint32(roleAtom))
|
||||||
|
xproto.ChangeProperty(conn, xproto.PropModeReplace, window, typeProp,
|
||||||
|
xproto.AtomAtom, 32, 1, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The OSD overlay must be transparent and input-transparent from its
|
||||||
|
// first mapped frame: the shapes are emptied before mapping, and a
|
||||||
|
// server without the shape extension never gets the overlay at all, so
|
||||||
|
// it can never present an unshaped frame over pilot video.
|
||||||
|
if o.Role == RoleAbove {
|
||||||
|
if err := applyTransparentShapes(conn, window); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xproto.MapWindow(conn, window)
|
||||||
|
// Watch the root screen so video output announces itself: a video
|
||||||
|
// window mapping is the first presented video frame, its unmap or
|
||||||
|
// destroy is video end. WFB and launcher processes are never consulted.
|
||||||
|
xproto.ChangeWindowAttributes(conn, screen.Root,
|
||||||
|
xproto.CwEventMask, []uint32{xproto.EventMaskSubstructureNotify})
|
||||||
|
// Round trip confirms the window is mapped and the server is alive.
|
||||||
|
if err := xproto.GetInputFocus(conn).Check(); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, fmt.Errorf("map kiosk window: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A layer reconnect must never cover running video: if video windows
|
||||||
|
// are already presented, record presence and take our side relative to
|
||||||
|
// the topmost one before anything is drawn.
|
||||||
|
presence := o.presence()
|
||||||
|
typeAtom := internWindowTypeAtom(conn)
|
||||||
|
videoWindows := scanVideoWindows(conn, screen.Root, window, typeAtom, markerAtom)
|
||||||
|
if len(videoWindows) > 0 {
|
||||||
|
presence.SetActive(true)
|
||||||
|
stackWindowRelative(conn, window, videoWindows[len(videoWindows)-1],
|
||||||
|
stackModeForVideoAppear(o.Role))
|
||||||
|
} else {
|
||||||
|
presence.SetActive(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fullscreen on the root screen, on our side of the video window: pilot
|
||||||
|
// video owns rendering priority whenever it is available. The canvas
|
||||||
|
// raises itself only after video ends, to bring the fallback back; the
|
||||||
|
// OSD overlay is already above video. A missing wmctrl only degrades to
|
||||||
|
// a plain window and must not kill the layer.
|
||||||
|
if err := o.applyFullscreen(x11FullscreenArgs(uint32(window), o.Role)); err != nil {
|
||||||
|
log.Printf("kiosk fullscreen state: %v (window stays a plain window)", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gc, err := xproto.NewGcontextId(conn)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, fmt.Errorf("allocate graphics context: %w", err)
|
||||||
|
}
|
||||||
|
font, err := xproto.NewFontId(conn)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, fmt.Errorf("allocate font: %w", err)
|
||||||
|
}
|
||||||
|
// Prefer a Unicode font so the exact fallback text renders with its
|
||||||
|
// diacritics; without one, drawn text degrades to ASCII.
|
||||||
|
fontName, unicodeFont := selectFontName(conn)
|
||||||
|
xproto.OpenFont(conn, font, uint16(len(fontName)), fontName)
|
||||||
|
xproto.CreateGC(conn, gc, xproto.Drawable(window),
|
||||||
|
xproto.GcForeground|xproto.GcBackground|xproto.GcFont,
|
||||||
|
[]uint32{screen.WhitePixel, screen.BlackPixel, uint32(font)})
|
||||||
|
|
||||||
|
return &x11Session{
|
||||||
|
conn: conn,
|
||||||
|
window: window,
|
||||||
|
gc: gc,
|
||||||
|
width: int(screen.WidthInPixels),
|
||||||
|
height: int(screen.HeightInPixels),
|
||||||
|
black: screen.BlackPixel,
|
||||||
|
white: screen.WhitePixel,
|
||||||
|
poll: o.pollInterval(),
|
||||||
|
video: presence,
|
||||||
|
videoWindows: videoWindowSet(videoWindows),
|
||||||
|
typeAtom: typeAtom,
|
||||||
|
markerAtom: markerAtom,
|
||||||
|
role: o.Role,
|
||||||
|
unicodeFont: unicodeFont,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func videoWindowSet(windows []xproto.Window) map[xproto.Window]struct{} {
|
||||||
|
set := make(map[xproto.Window]struct{}, len(windows))
|
||||||
|
for _, w := range windows {
|
||||||
|
set[w] = struct{}{}
|
||||||
|
}
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
|
||||||
|
func x11FullscreenArgs(window uint32, role LayerRole) []string {
|
||||||
|
return []string{"-i", "-r", fmt.Sprintf("0x%08x", window),
|
||||||
|
"-b", "add,fullscreen," + fullscreenState(role)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyTransparentShapes empties the overlay's input and bounding shapes
|
||||||
|
// before it is mapped: it then never intercepts pointer or key input and
|
||||||
|
// never presents pixels over pilot video, with or without a compositor.
|
||||||
|
// Future OSD content will punch its output shape per drawn region.
|
||||||
|
func applyTransparentShapes(conn *xgb.Conn, window xproto.Window) error {
|
||||||
|
if err := shape.Init(conn); err != nil {
|
||||||
|
return fmt.Errorf("shape extension: %w", err)
|
||||||
|
}
|
||||||
|
for _, kind := range transparentShapeKinds() {
|
||||||
|
if err := shape.RectanglesChecked(conn, shape.SoSet, kind, 0,
|
||||||
|
window, 0, 0, nil).Check(); err != nil {
|
||||||
|
return fmt.Errorf("empty shape region %d: %w", kind, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scanVideoWindows lists already-presented video windows on the root screen
|
||||||
|
// in bottom-to-top stacking order, so a layer reconnect can take its side
|
||||||
|
// relative to the topmost one and never cover running video.
|
||||||
|
func scanVideoWindows(conn *xgb.Conn, root, own xproto.Window, typeAtom, markerAtom xproto.Atom) []xproto.Window {
|
||||||
|
tree, err := xproto.QueryTree(conn, root).Reply()
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var windows []xproto.Window
|
||||||
|
for _, w := range tree.Children {
|
||||||
|
if w != own && presentedVideoWindow(conn, w, typeAtom, markerAtom) {
|
||||||
|
windows = append(windows, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return windows
|
||||||
|
}
|
||||||
|
|
||||||
|
// windowFacts is the presentation evidence gathered for one candidate
|
||||||
|
// window, so the video decision stays a pure function.
|
||||||
|
type windowFacts struct {
|
||||||
|
inputOutput bool
|
||||||
|
overrideRedirect bool
|
||||||
|
viewable bool
|
||||||
|
auxiliary bool
|
||||||
|
groundstation bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// isPresentedVideoWindow decides whether a window is video output. Only a
|
||||||
|
// real, presented output window counts as video: input-only and
|
||||||
|
// override-redirect helpers such as menus or notifications never do, and
|
||||||
|
// neither do windows carrying an EWMH auxiliary window type or a Ground
|
||||||
|
// Station layer marker.
|
||||||
|
func isPresentedVideoWindow(f windowFacts) bool {
|
||||||
|
return f.inputOutput && !f.overrideRedirect && f.viewable &&
|
||||||
|
!f.auxiliary && !f.groundstation
|
||||||
|
}
|
||||||
|
|
||||||
|
// presentedVideoWindow gathers the presentation facts of w.
|
||||||
|
func presentedVideoWindow(conn *xgb.Conn, w xproto.Window, typeAtom, markerAtom xproto.Atom) bool {
|
||||||
|
attrs, err := xproto.GetWindowAttributes(conn, w).Reply()
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return isPresentedVideoWindow(windowFacts{
|
||||||
|
inputOutput: attrs.Class == xproto.WindowClassInputOutput,
|
||||||
|
overrideRedirect: attrs.OverrideRedirect,
|
||||||
|
viewable: attrs.MapState == xproto.MapStateViewable,
|
||||||
|
auxiliary: auxiliaryWindowType(conn, w, typeAtom),
|
||||||
|
groundstation: groundstationLayerWindow(conn, w, markerAtom),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// markerWalkBounds bound the descendant search for layer markers: window
|
||||||
|
// managers reparent client windows into frame windows, so a Ground Station
|
||||||
|
// layer must be recognized through its frame, and the search must stay
|
||||||
|
// cheap even on a busy desktop screen. depth must cover our window below
|
||||||
|
// one window-manager frame; nodes bounds the total windows inspected.
|
||||||
|
func markerWalkBounds() (depth, nodes int) {
|
||||||
|
return 4, 64
|
||||||
|
}
|
||||||
|
|
||||||
|
// groundstationLayerWindow reports whether w itself or any window below it
|
||||||
|
// carries our layer marker. Window managers frame our windows, so the
|
||||||
|
// marker must be found through frame windows too: otherwise a framed
|
||||||
|
// Ground Station layer could count as video output and permanently
|
||||||
|
// suppress the fallback. When the search hits its bounds or the server
|
||||||
|
// refuses, it reports not-found, degrading to the plain window checks.
|
||||||
|
func groundstationLayerWindow(conn *xgb.Conn, w xproto.Window, markerAtom xproto.Atom) bool {
|
||||||
|
if markerAtom == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
depth, nodes := markerWalkBounds()
|
||||||
|
visited := 0
|
||||||
|
var walk func(xproto.Window, int) bool
|
||||||
|
walk = func(w xproto.Window, depth int) bool {
|
||||||
|
if visited >= nodes {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
visited++
|
||||||
|
if carriesLayerMarker(conn, w, markerAtom) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if depth <= 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
tree, err := xproto.QueryTree(conn, w).Reply()
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, child := range tree.Children {
|
||||||
|
if walk(child, depth-1) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return walk(w, depth)
|
||||||
|
}
|
||||||
|
|
||||||
|
// carriesLayerMarker reports whether w itself carries our layer marker.
|
||||||
|
func carriesLayerMarker(conn *xgb.Conn, w xproto.Window, markerAtom xproto.Atom) bool {
|
||||||
|
reply, err := xproto.GetProperty(conn, false, w, markerAtom,
|
||||||
|
xproto.GetPropertyTypeAny, 0, 64).Reply()
|
||||||
|
if err != nil || reply.ValueLen == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return markerIsGroundstation(string(reply.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
// internAtom resolves an atom by name, or 0 when the server refuses,
|
||||||
|
// disabling the checks that would use it.
|
||||||
|
func internAtom(conn *xgb.Conn, name string) xproto.Atom {
|
||||||
|
reply, err := xproto.InternAtom(conn, false,
|
||||||
|
uint16(len(name)), name).Reply()
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return reply.Atom
|
||||||
|
}
|
||||||
|
|
||||||
|
func internWindowTypeAtom(conn *xgb.Conn) xproto.Atom {
|
||||||
|
return internAtom(conn, windowTypePropertyName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// auxiliaryWindowType reports whether the window carries an EWMH window
|
||||||
|
// type naming a non-video helper role. A missing property means the window
|
||||||
|
// counts as video.
|
||||||
|
func auxiliaryWindowType(conn *xgb.Conn, w xproto.Window, typeAtom xproto.Atom) bool {
|
||||||
|
if typeAtom == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
reply, err := xproto.GetProperty(conn, false, w, typeAtom,
|
||||||
|
xproto.GetPropertyTypeAny, 0, 32).Reply()
|
||||||
|
if err != nil || reply.ValueLen < 4 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i+4 <= len(reply.Value); i += 4 {
|
||||||
|
atom := xproto.Atom(binary.LittleEndian.Uint32(reply.Value[i : i+4]))
|
||||||
|
name, err := xproto.GetAtomName(conn, atom).Reply()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ewmhNonVideoTypes[name.Name] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// stackWindowRelative moves window to the given side of sibling.
|
||||||
|
func stackWindowRelative(conn *xgb.Conn, window, sibling xproto.Window, mode uint32) {
|
||||||
|
xproto.ConfigureWindow(conn, window,
|
||||||
|
xproto.ConfigWindowSibling|xproto.ConfigWindowStackMode,
|
||||||
|
[]uint32{uint32(sibling), mode})
|
||||||
|
}
|
||||||
|
|
||||||
|
// videoChange is the video-lifecycle meaning of one root structure event.
|
||||||
|
type videoChange int
|
||||||
|
|
||||||
|
const (
|
||||||
|
videoUnrelated videoChange = iota
|
||||||
|
videoAppeared
|
||||||
|
videoDisappeared
|
||||||
|
)
|
||||||
|
|
||||||
|
// classifyVideoChange maps a root structure event onto the video lifecycle.
|
||||||
|
// own is the kiosk window. The video output windows themselves are the
|
||||||
|
// presence signal: their maps are the first presented video output and
|
||||||
|
// their unmaps or destroys are video ends, so neither WFB nor launcher
|
||||||
|
// processes are ever consulted. Whether an announced window actually is
|
||||||
|
// video is decided by the session using the presented-window checks.
|
||||||
|
func classifyVideoChange(event xgb.Event, own xproto.Window) (videoChange, xproto.Window) {
|
||||||
|
switch e := event.(type) {
|
||||||
|
case xproto.MapNotifyEvent:
|
||||||
|
if e.Window == own {
|
||||||
|
return videoUnrelated, 0
|
||||||
|
}
|
||||||
|
return videoAppeared, e.Window
|
||||||
|
case xproto.UnmapNotifyEvent:
|
||||||
|
if e.Window == own {
|
||||||
|
return videoUnrelated, 0
|
||||||
|
}
|
||||||
|
return videoDisappeared, e.Window
|
||||||
|
case xproto.DestroyNotifyEvent:
|
||||||
|
return videoDisappeared, e.Window
|
||||||
|
}
|
||||||
|
return videoUnrelated, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// addVideoWindow records w as presented video output and reports whether
|
||||||
|
// presence changed (the set went from empty to non-empty).
|
||||||
|
func addVideoWindow(windows map[xproto.Window]struct{}, w xproto.Window) bool {
|
||||||
|
if _, tracked := windows[w]; tracked {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
wasEmpty := len(windows) == 0
|
||||||
|
windows[w] = struct{}{}
|
||||||
|
return wasEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
// removeVideoWindow drops w from the presented video windows and reports
|
||||||
|
// whether presence changed (the set became empty).
|
||||||
|
func removeVideoWindow(windows map[xproto.Window]struct{}, w xproto.Window) bool {
|
||||||
|
if _, tracked := windows[w]; !tracked {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
delete(windows, w)
|
||||||
|
return len(windows) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// x11Session implements both Session and Canvas for one X11 connection.
|
||||||
|
type x11Session struct {
|
||||||
|
conn *xgb.Conn
|
||||||
|
window xproto.Window
|
||||||
|
gc xproto.Gcontext
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
black uint32
|
||||||
|
white uint32
|
||||||
|
poll time.Duration
|
||||||
|
video *VideoPresence
|
||||||
|
videoWindows map[xproto.Window]struct{}
|
||||||
|
typeAtom xproto.Atom
|
||||||
|
markerAtom xproto.Atom
|
||||||
|
role LayerRole
|
||||||
|
unicodeFont bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *x11Session) Canvas() Canvas { return s }
|
||||||
|
|
||||||
|
func (s *x11Session) Size() (int, int) { return s.width, s.height }
|
||||||
|
|
||||||
|
func (s *x11Session) Clear() {
|
||||||
|
// ClearArea tiles the window background (black, set at creation); it
|
||||||
|
// involves no graphics context.
|
||||||
|
xproto.ClearArea(s.conn, false, s.window, 0, 0,
|
||||||
|
uint16(s.width), uint16(s.height))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *x11Session) Text(x, y int, message string) {
|
||||||
|
xproto.ChangeGC(s.conn, s.gc, xproto.GcForeground, []uint32{s.white})
|
||||||
|
if s.unicodeFont {
|
||||||
|
chars := utf16Char2b(message, maxImageText16Units)
|
||||||
|
xproto.ImageText16(s.conn, byte(len(chars)), xproto.Drawable(s.window), s.gc,
|
||||||
|
int16(x), int16(y), chars)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
message = foldToASCII(message)
|
||||||
|
if len(message) > 255 {
|
||||||
|
message = message[:255]
|
||||||
|
}
|
||||||
|
xproto.ImageText8(s.conn, byte(len(message)), xproto.Drawable(s.window), s.gc,
|
||||||
|
int16(x), int16(y), message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *x11Session) Flush() {
|
||||||
|
s.conn.Sync()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *x11Session) WaitEvent(ctx context.Context) (bool, error) {
|
||||||
|
ticker := time.NewTicker(s.poll)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
for {
|
||||||
|
event, err := s.conn.PollForEvent()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
if event == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if x11WantsRedraw(event) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if s.applyVideoChange(event) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Round trip keeps the connection liveness visible even without
|
||||||
|
// incoming events.
|
||||||
|
if err := xproto.GetInputFocus(s.conn).Check(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return false, ctx.Err()
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyVideoChange folds one root structure event into the shared video
|
||||||
|
// presence and restacks this layer so video keeps rendering priority: the
|
||||||
|
// canvas parks below video and the OSD overlay rises above it. It reports
|
||||||
|
// whether the template must be redrawn: video appearing makes the fallback
|
||||||
|
// disappear and video ending brings it back. Presence follows the set of
|
||||||
|
// presented video windows, so an unrelated window appearing or ending can
|
||||||
|
// never hide or resurrect a template on its own.
|
||||||
|
func (s *x11Session) applyVideoChange(event xgb.Event) bool {
|
||||||
|
change, w := classifyVideoChange(event, s.window)
|
||||||
|
switch change {
|
||||||
|
case videoAppeared:
|
||||||
|
// Menus, notifications, other auxiliary windows and our own sibling
|
||||||
|
// layers never count as video; only a presented output window does.
|
||||||
|
if !presentedVideoWindow(s.conn, w, s.typeAtom, s.markerAtom) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !addVideoWindow(s.videoWindows, w) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// The first presented video output takes priority: park on our side
|
||||||
|
// of it.
|
||||||
|
stackWindowRelative(s.conn, s.window, w, stackModeForVideoAppear(s.role))
|
||||||
|
return s.video.SetActive(true)
|
||||||
|
case videoDisappeared:
|
||||||
|
if !removeVideoWindow(s.videoWindows, w) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Only the below canvas raises itself so the fallback returns
|
||||||
|
// visibly even if some other window was stacked above it; the OSD
|
||||||
|
// overlay is already above video.
|
||||||
|
if raisesOnVideoEnd(s.role) {
|
||||||
|
xproto.ConfigureWindow(s.conn, s.window,
|
||||||
|
xproto.ConfigWindowStackMode, []uint32{xproto.StackModeAbove})
|
||||||
|
}
|
||||||
|
return s.video.SetActive(false)
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func x11WantsRedraw(event xgb.Event) bool {
|
||||||
|
switch event.(type) {
|
||||||
|
case xproto.ExposeEvent:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// selectFontName resolves a Unicode-capable font for the fallback text. It
|
||||||
|
// reports false when none is installed, in which case drawn text is folded
|
||||||
|
// to ASCII.
|
||||||
|
func selectFontName(conn *xgb.Conn) (string, bool) {
|
||||||
|
reply, err := xproto.ListFontsWithInfo(conn, 1,
|
||||||
|
uint16(len(iso10646FontPattern)), iso10646FontPattern).Reply()
|
||||||
|
if err != nil || reply.NameLen == 0 {
|
||||||
|
return asciiFontName, false
|
||||||
|
}
|
||||||
|
return reply.Name, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// utf16Char2b encodes the message as UTF-16 units for ImageText16 so the
|
||||||
|
// exact fallback text keeps its diacritics, truncating to maxUnits because
|
||||||
|
// the request carries a 1-byte string length. A cut never splits a
|
||||||
|
// surrogate pair.
|
||||||
|
func utf16Char2b(message string, maxUnits int) []xproto.Char2b {
|
||||||
|
if maxUnits <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
units := utf16.Encode([]rune(message))
|
||||||
|
if len(units) > maxUnits {
|
||||||
|
units = units[:maxUnits]
|
||||||
|
if last := units[len(units)-1]; last >= 0xD800 && last <= 0xDBFF {
|
||||||
|
units = units[:len(units)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chars := make([]xproto.Char2b, len(units))
|
||||||
|
for i, unit := range units {
|
||||||
|
chars[i] = xproto.Char2b{Byte1: byte(unit >> 8), Byte2: byte(unit)}
|
||||||
|
}
|
||||||
|
return chars
|
||||||
|
}
|
||||||
|
|
||||||
|
// latinFolds maps the Polish diacritics to plain ASCII for fonts without
|
||||||
|
// Unicode glyphs.
|
||||||
|
var latinFolds = map[rune]byte{
|
||||||
|
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
|
||||||
|
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
// foldToASCII degrades text for legacy fonts: Polish diacritics fold to
|
||||||
|
// their base letters and other non-ASCII runes are dropped.
|
||||||
|
func foldToASCII(message string) string {
|
||||||
|
ascii := true
|
||||||
|
for _, r := range message {
|
||||||
|
if r >= 0x80 {
|
||||||
|
ascii = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ascii {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range message {
|
||||||
|
if r < 0x80 {
|
||||||
|
b.WriteRune(r)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if folded, ok := latinFolds[r]; ok {
|
||||||
|
b.WriteByte(folded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *x11Session) Close() error {
|
||||||
|
// Closing the connection makes the X server destroy the kiosk window.
|
||||||
|
s.conn.Close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
package display
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/BurntSushi/xgb/shape"
|
||||||
|
"github.com/BurntSushi/xgb/xproto"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestX11FullscreenArgsOrderByRole(t *testing.T) {
|
||||||
|
below := strings.Join(x11FullscreenArgs(0x1a2b, RoleBelow), " ")
|
||||||
|
if !strings.Contains(below, "add,fullscreen,below") {
|
||||||
|
t.Fatalf("args %q must request fullscreen with below stacking", below)
|
||||||
|
}
|
||||||
|
if !strings.Contains(below, "0x00001a2b") {
|
||||||
|
t.Fatalf("args %q must reference the kiosk window id", below)
|
||||||
|
}
|
||||||
|
|
||||||
|
above := strings.Join(x11FullscreenArgs(0x1a2b, RoleAbove), " ")
|
||||||
|
if strings.Contains(above, "below") {
|
||||||
|
t.Fatalf("args %q must never stack the OSD overlay below video", above)
|
||||||
|
}
|
||||||
|
if !strings.Contains(above, "add,fullscreen,above") {
|
||||||
|
t.Fatalf("args %q must request fullscreen with above stacking", above)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestX11SessionRedrawsOnlyOnExpose(t *testing.T) {
|
||||||
|
if !x11WantsRedraw(xproto.ExposeEvent{}) {
|
||||||
|
t.Fatal("expose events must trigger a redraw")
|
||||||
|
}
|
||||||
|
if x11WantsRedraw(xproto.MapNotifyEvent{}) {
|
||||||
|
t.Fatal("map notify events must not trigger a redraw")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestX11OpenerAppliesFullscreenArgsThroughHook(t *testing.T) {
|
||||||
|
var got [][]string
|
||||||
|
opener := X11Opener{Fullscreen: func(args []string) error {
|
||||||
|
got = append(got, args)
|
||||||
|
return errors.New("wmctrl missing")
|
||||||
|
}}
|
||||||
|
|
||||||
|
if err := opener.applyFullscreen(x11FullscreenArgs(0x42, RoleBelow)); err == nil {
|
||||||
|
t.Fatal("hook error must propagate for logging")
|
||||||
|
}
|
||||||
|
if len(got) != 1 || !strings.Contains(strings.Join(got[0], " "), "add,fullscreen,below") {
|
||||||
|
t.Fatalf("hook args %v must request fullscreen with below stacking", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClassifyVideoChangeTracksVideoWindowLifecycle(t *testing.T) {
|
||||||
|
const own = xproto.Window(0x10)
|
||||||
|
const video = xproto.Window(0x20)
|
||||||
|
const other = xproto.Window(0x30)
|
||||||
|
|
||||||
|
change, w := classifyVideoChange(xproto.MapNotifyEvent{Window: video}, own)
|
||||||
|
if change != videoAppeared || w != video {
|
||||||
|
t.Fatalf("map of a foreign window must announce video, got %v %v", change, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, _ = classifyVideoChange(xproto.MapNotifyEvent{Window: own}, own)
|
||||||
|
if change != videoUnrelated {
|
||||||
|
t.Fatalf("map of the kiosk window must be unrelated, got %v", change)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, w = classifyVideoChange(xproto.UnmapNotifyEvent{Window: video}, own)
|
||||||
|
if change != videoDisappeared || w != video {
|
||||||
|
t.Fatalf("unmap must announce a video end candidate, got %v %v", change, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, _ = classifyVideoChange(xproto.UnmapNotifyEvent{Window: own}, own)
|
||||||
|
if change != videoUnrelated {
|
||||||
|
t.Fatalf("unmap of the kiosk window must be unrelated, got %v", change)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, w = classifyVideoChange(xproto.UnmapNotifyEvent{Window: other}, own)
|
||||||
|
if change != videoDisappeared || w != other {
|
||||||
|
t.Fatalf("unmap of a foreign window must be an end candidate, got %v %v", change, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, w = classifyVideoChange(xproto.DestroyNotifyEvent{Window: video}, own)
|
||||||
|
if change != videoDisappeared || w != video {
|
||||||
|
t.Fatalf("destroy must announce a video end candidate, got %v %v", change, w)
|
||||||
|
}
|
||||||
|
|
||||||
|
change, _ = classifyVideoChange(xproto.ExposeEvent{}, own)
|
||||||
|
if change != videoUnrelated {
|
||||||
|
t.Fatalf("expose must not change video presence, got %v", change)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAddAndRemoveVideoWindowTrackPresenceTransitions(t *testing.T) {
|
||||||
|
const video = xproto.Window(0x20)
|
||||||
|
const second = xproto.Window(0x30)
|
||||||
|
windows := make(map[xproto.Window]struct{})
|
||||||
|
|
||||||
|
if !addVideoWindow(windows, video) {
|
||||||
|
t.Fatal("first video window must change presence")
|
||||||
|
}
|
||||||
|
if addVideoWindow(windows, video) {
|
||||||
|
t.Fatal("re-adding the tracked window must not change presence")
|
||||||
|
}
|
||||||
|
if addVideoWindow(windows, second) {
|
||||||
|
t.Fatal("a second video window must not change presence")
|
||||||
|
}
|
||||||
|
if removeVideoWindow(windows, second) {
|
||||||
|
t.Fatal("removing one of two video windows must not change presence")
|
||||||
|
}
|
||||||
|
if !removeVideoWindow(windows, video) {
|
||||||
|
t.Fatal("removing the last video window must change presence")
|
||||||
|
}
|
||||||
|
if removeVideoWindow(windows, video) {
|
||||||
|
t.Fatal("removing an untracked window must not change presence")
|
||||||
|
}
|
||||||
|
if len(windows) != 0 {
|
||||||
|
t.Fatalf("set %v must be empty after all video ended", windows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEWMHNonVideoWindowTypesExcludeDesktopHelpers(t *testing.T) {
|
||||||
|
for _, name := range []string{"DOCK", "DESKTOP", "TOOLBAR", "MENU", "UTILITY", "SPLASH", "DIALOG", "NOTIFICATION", "TOOLTIP"} {
|
||||||
|
if !ewmhNonVideoTypes[name] {
|
||||||
|
t.Fatalf("window type %q must not count as video", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, name := range []string{"NORMAL", "", "VIDEO_PLAY"} {
|
||||||
|
if ewmhNonVideoTypes[name] {
|
||||||
|
t.Fatalf("window type %q must count as video", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUTF16Char2bEncodesPolishFallbackText(t *testing.T) {
|
||||||
|
chars := utf16Char2b(wantFallbackText, maxImageText16Units)
|
||||||
|
want := []xproto.Char2b{
|
||||||
|
{Byte1: 0, Byte2: 'B'}, {Byte1: 0, Byte2: 'r'}, {Byte1: 0, Byte2: 'a'}, {Byte1: 0, Byte2: 'k'}, {Byte1: 0, Byte2: ' '},
|
||||||
|
{Byte1: 0, Byte2: 'p'}, {Byte1: 0, Byte2: 'o'},
|
||||||
|
{Byte1: 0x01, Byte2: 0x42}, // ł
|
||||||
|
{Byte1: 0x01, Byte2: 0x05}, // ą
|
||||||
|
{Byte1: 0, Byte2: 'c'}, {Byte1: 0, Byte2: 'z'}, {Byte1: 0, Byte2: 'e'}, {Byte1: 0, Byte2: 'n'}, {Byte1: 0, Byte2: 'i'}, {Byte1: 0, Byte2: 'a'}, {Byte1: 0, Byte2: ' '},
|
||||||
|
{Byte1: 0, Byte2: 'W'}, {Byte1: 0, Byte2: 'F'}, {Byte1: 0, Byte2: 'B'},
|
||||||
|
}
|
||||||
|
if len(chars) != len(want) {
|
||||||
|
t.Fatalf("units=%v want %v", chars, want)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if chars[i] != want[i] {
|
||||||
|
t.Fatalf("unit %d=%v want %v", i, chars[i], want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUTF16Char2bTruncatesToOneRequestLength(t *testing.T) {
|
||||||
|
if chars := utf16Char2b(wantFallbackText, 10); len(chars) != 10 {
|
||||||
|
t.Fatalf("units=%d want 10", len(chars))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUTF16Char2bNeverSplitsSurrogatePairs(t *testing.T) {
|
||||||
|
// U+1F3A5 encodes as a surrogate pair (0xD83C, 0xDFA5): a cut that would
|
||||||
|
// land between the two units must back off instead of splitting it.
|
||||||
|
if chars := utf16Char2b("a🎥", 2); len(chars) != 1 || chars[0].Byte2 != 'a' {
|
||||||
|
t.Fatalf("units=%v want only the leading ASCII unit", chars)
|
||||||
|
}
|
||||||
|
if chars := utf16Char2b("🎥", 1); len(chars) != 0 {
|
||||||
|
t.Fatalf("units=%v want none, the pair does not fit", chars)
|
||||||
|
}
|
||||||
|
if chars := utf16Char2b("🎥", 2); len(chars) != 2 {
|
||||||
|
t.Fatalf("units=%v want the intact pair", chars)
|
||||||
|
}
|
||||||
|
if chars := utf16Char2b(wantFallbackText, 0); len(chars) != 0 {
|
||||||
|
t.Fatalf("units=%v want none for a zero limit", chars)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFoldToASCIIStripsPolishDiacritics(t *testing.T) {
|
||||||
|
if got := foldToASCII(wantFallbackText); got != "Brak polaczenia WFB" {
|
||||||
|
t.Fatalf("foldToASCII=%q want %q", got, "Brak polaczenia WFB")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFoldToASCIIKeepsPlainASCIIUntouched(t *testing.T) {
|
||||||
|
if got := foldToASCII("plain text"); got != "plain text" {
|
||||||
|
t.Fatalf("foldToASCII=%q want %q", got, "plain text")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestX11FontPatternRequestsUnicodeFixedFont(t *testing.T) {
|
||||||
|
if !strings.Contains(iso10646FontPattern, "fixed") {
|
||||||
|
t.Fatalf("font pattern %q must select a fixed font", iso10646FontPattern)
|
||||||
|
}
|
||||||
|
if !strings.Contains(iso10646FontPattern, "iso10646") {
|
||||||
|
t.Fatalf("font pattern %q must select a Unicode encoding for the exact fallback text", iso10646FontPattern)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLayerMarkerIdentifiesOwnLayerWindows(t *testing.T) {
|
||||||
|
if layerMarkerValue(RoleBelow) == layerMarkerValue(RoleAbove) {
|
||||||
|
t.Fatal("roles must carry distinct marker payloads")
|
||||||
|
}
|
||||||
|
for _, role := range []LayerRole{RoleBelow, RoleAbove} {
|
||||||
|
if !markerIsGroundstation(layerMarkerValue(role)) {
|
||||||
|
t.Fatalf("marker %q must identify our own window", layerMarkerValue(role))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, foreign := range []string{"", "video", "desktop", "groundstation-fake"} {
|
||||||
|
if markerIsGroundstation(foreign) {
|
||||||
|
t.Fatalf("foreign marker payload %q must not identify our windows", foreign)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMarkerWalkBoundsStayBoundedAndCoverFrameDepth(t *testing.T) {
|
||||||
|
depth, nodes := markerWalkBounds()
|
||||||
|
if depth <= 0 || nodes <= 0 {
|
||||||
|
t.Fatalf("marker walk bounds depth=%d nodes=%d must be positive", depth, nodes)
|
||||||
|
}
|
||||||
|
if nodes < depth {
|
||||||
|
t.Fatalf("node budget %d must cover at least a depth-%d ancestor chain", nodes, depth)
|
||||||
|
}
|
||||||
|
// A reparenting window manager puts each of our two layer windows inside
|
||||||
|
// its own frame, so the walk must reach our window below one frame.
|
||||||
|
if depth < 2 {
|
||||||
|
t.Fatalf("marker walk depth %d must cover our window below a window-manager frame", depth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEWMHWindowTypeAnnouncesOverlayRoleOnly(t *testing.T) {
|
||||||
|
if name := ewmhWindowTypeName(RoleAbove); !strings.Contains(name, "DOCK") {
|
||||||
|
t.Fatalf("OSD overlay window type %q must be the always-above helper role", name)
|
||||||
|
}
|
||||||
|
if name := ewmhWindowTypeName(RoleBelow); name != "" {
|
||||||
|
t.Fatalf("fallback canvas must keep announcing no window type, got %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPresentedVideoDecisionExcludesOwnLayersAndHelpers(t *testing.T) {
|
||||||
|
video := windowFacts{inputOutput: true, viewable: true}
|
||||||
|
if !isPresentedVideoWindow(video) {
|
||||||
|
t.Fatal("a presented output window must count as video")
|
||||||
|
}
|
||||||
|
for name, facts := range map[string]windowFacts{
|
||||||
|
"input-only": {viewable: true},
|
||||||
|
"override-redirect": {inputOutput: true, viewable: true, overrideRedirect: true},
|
||||||
|
"unmapped": {inputOutput: true},
|
||||||
|
"auxiliary": {inputOutput: true, viewable: true, auxiliary: true},
|
||||||
|
"groundstation-canvas": {inputOutput: true, viewable: true, groundstation: true},
|
||||||
|
"groundstation-osd": {inputOutput: true, viewable: true, groundstation: true},
|
||||||
|
} {
|
||||||
|
if isPresentedVideoWindow(facts) {
|
||||||
|
t.Fatalf("%s window must never count as video", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Window-manager frames around our layer windows carry no marker of
|
||||||
|
// their own; groundstationLayerWindow finds the marker below the frame,
|
||||||
|
// so framed Ground Station layers land in these same excluded facts.
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStackOrderByRoleKeepsLayersOnTheirSideOfVideo(t *testing.T) {
|
||||||
|
if mode := stackModeForVideoAppear(RoleBelow); mode != xproto.StackModeBelow {
|
||||||
|
t.Fatalf("canvas must park below appearing video, got %v", mode)
|
||||||
|
}
|
||||||
|
if mode := stackModeForVideoAppear(RoleAbove); mode != xproto.StackModeAbove {
|
||||||
|
t.Fatalf("OSD overlay must rise above appearing video, got %v", mode)
|
||||||
|
}
|
||||||
|
if !raisesOnVideoEnd(RoleBelow) {
|
||||||
|
t.Fatal("canvas must raise itself when video ends so the fallback returns")
|
||||||
|
}
|
||||||
|
if raisesOnVideoEnd(RoleAbove) {
|
||||||
|
t.Fatal("OSD overlay is already above video and must not restack on video end")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOSDEventMaskNeverSelectsDeviceInput(t *testing.T) {
|
||||||
|
if osdEventMask&deviceInputEventMask != 0 {
|
||||||
|
t.Fatalf("OSD event mask must not select pointer or key input: %b", osdEventMask)
|
||||||
|
}
|
||||||
|
if osdEventMask&xproto.EventMaskExposure == 0 {
|
||||||
|
t.Fatal("OSD event mask must still select exposure for redraws")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransparentShapesEmptyInputAndOutput(t *testing.T) {
|
||||||
|
var input, output bool
|
||||||
|
for _, kind := range transparentShapeKinds() {
|
||||||
|
switch kind {
|
||||||
|
case shape.SkInput:
|
||||||
|
input = true
|
||||||
|
case shape.SkBounding:
|
||||||
|
output = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !input || !output {
|
||||||
|
t.Fatalf("shape kinds %v must empty both the input and the bounding region", transparentShapeKinds())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,19 +19,45 @@ func Open115200(path string) (*os.File, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
termios.Iflag = 0
|
configureRaw115200(termios)
|
||||||
termios.Oflag = 0
|
|
||||||
termios.Lflag = 0
|
|
||||||
termios.Cflag &^= unix.CSIZE | unix.PARENB | unix.CSTOPB | unix.CRTSCTS
|
|
||||||
termios.Cflag |= unix.CS8 | unix.CREAD | unix.CLOCAL
|
|
||||||
termios.Ispeed = unix.B115200
|
|
||||||
termios.Ospeed = unix.B115200
|
|
||||||
termios.Cc[unix.VMIN] = 1
|
|
||||||
termios.Cc[unix.VTIME] = 0
|
|
||||||
|
|
||||||
if err := unix.IoctlSetTermios(int(file.Fd()), unix.TCSETS, termios); err != nil {
|
if err := unix.IoctlSetTermios(int(file.Fd()), unix.TCSETS, termios); err != nil {
|
||||||
file.Close()
|
file.Close()
|
||||||
return nil, fmt.Errorf("configure %s: %w", path, err)
|
return nil, fmt.Errorf("configure %s: %w", path, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
effective, err := unix.IoctlGetTermios(int(file.Fd()), unix.TCGETS)
|
||||||
|
if err != nil {
|
||||||
|
file.Close()
|
||||||
|
return nil, fmt.Errorf("read back %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if err := verifyBaud(*effective, unix.B115200); err != nil {
|
||||||
|
file.Close()
|
||||||
|
return nil, fmt.Errorf("verify %s: %w", path, err)
|
||||||
|
}
|
||||||
return file, nil
|
return file, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// configureRaw115200 keeps the raw 115200 8N1 blocking-read configuration.
|
||||||
|
// On Linux TCSETS takes the line speed from the CBAUD bits in Cflag, so
|
||||||
|
// CBAUD must be cleared and B115200 selected there; Ispeed/Ospeed alone
|
||||||
|
// leave an inherited baud (for example 9600 from boot defaults) in effect.
|
||||||
|
func configureRaw115200(termios *unix.Termios) {
|
||||||
|
termios.Iflag = 0
|
||||||
|
termios.Oflag = 0
|
||||||
|
termios.Lflag = 0
|
||||||
|
termios.Cflag &^= unix.CSIZE | unix.PARENB | unix.CSTOPB | unix.CRTSCTS | unix.CBAUD
|
||||||
|
termios.Cflag |= unix.B115200
|
||||||
|
termios.Cflag |= unix.CS8 | unix.CREAD | unix.CLOCAL
|
||||||
|
termios.Ispeed = unix.B115200
|
||||||
|
termios.Ospeed = unix.B115200
|
||||||
|
termios.Cc[unix.VMIN] = 1
|
||||||
|
termios.Cc[unix.VTIME] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyBaud(termios unix.Termios, baud uint32) error {
|
||||||
|
if got := termios.Cflag & unix.CBAUD; got != baud {
|
||||||
|
return fmt.Errorf("effective baud bits %#o, want %#o", got, baud)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package serialport
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfigureRaw115200OverridesInheritedBaud(t *testing.T) {
|
||||||
|
var termios unix.Termios
|
||||||
|
termios.Iflag = unix.IGNBRK | unix.ICRNL
|
||||||
|
termios.Oflag = unix.OPOST
|
||||||
|
termios.Lflag = unix.ICANON | unix.ECHO
|
||||||
|
termios.Cflag = unix.B9600 | unix.CS8 | unix.CREAD | unix.CLOCAL | unix.HUPCL
|
||||||
|
termios.Ispeed = unix.B9600
|
||||||
|
termios.Ospeed = unix.B9600
|
||||||
|
|
||||||
|
configureRaw115200(&termios)
|
||||||
|
|
||||||
|
if got := termios.Cflag & unix.CBAUD; got != unix.B115200 {
|
||||||
|
t.Fatalf("effective baud bits=%#o want %#o", got, unix.B115200)
|
||||||
|
}
|
||||||
|
if got := termios.Cflag & unix.CSIZE; got != unix.CS8 {
|
||||||
|
t.Fatalf("character size bits=%#o want %#o", got, unix.CS8)
|
||||||
|
}
|
||||||
|
for _, flag := range []uint32{unix.CREAD, unix.CLOCAL} {
|
||||||
|
if termios.Cflag&flag == 0 {
|
||||||
|
t.Fatalf("flag %#o lost", flag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, flag := range []uint32{unix.PARENB, unix.CSTOPB, unix.CRTSCTS} {
|
||||||
|
if termios.Cflag&flag != 0 {
|
||||||
|
t.Fatalf("flag %#o must be cleared", flag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if termios.Iflag != 0 || termios.Oflag != 0 || termios.Lflag != 0 {
|
||||||
|
t.Fatal("raw mode must clear Iflag, Oflag and Lflag")
|
||||||
|
}
|
||||||
|
if termios.Ispeed != unix.B115200 || termios.Ospeed != unix.B115200 {
|
||||||
|
t.Fatalf("speed fields=%d/%d want 115200/115200", termios.Ispeed, termios.Ospeed)
|
||||||
|
}
|
||||||
|
if termios.Cc[unix.VMIN] != 1 || termios.Cc[unix.VTIME] != 0 {
|
||||||
|
t.Fatalf("VMIN=%d VTIME=%d want 1/0", termios.Cc[unix.VMIN], termios.Cc[unix.VTIME])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyBaudAcceptsOnlyConfiguredLineSpeed(t *testing.T) {
|
||||||
|
var inherited unix.Termios
|
||||||
|
inherited.Cflag = unix.B9600 | unix.CS8
|
||||||
|
if err := verifyBaud(inherited, unix.B115200); err == nil {
|
||||||
|
t.Fatal("inherited 9600 line speed must fail verification")
|
||||||
|
}
|
||||||
|
|
||||||
|
var configured unix.Termios
|
||||||
|
configured.Cflag = unix.B115200 | unix.CS8 | unix.CREAD
|
||||||
|
if err := verifyBaud(configured, unix.B115200); err != nil {
|
||||||
|
t.Fatalf("115200 line speed must verify: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user