feat: add bounded display_diag journal diagnostics for the OSD (#3)
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// DiagTag prefixes every diagnostic line so the journal can be
|
||||
// filtered to the stream with a plain grep.
|
||||
DiagTag = "display_diag"
|
||||
// DiagCap bounds the unique diagnostic records a process emits: the
|
||||
// stream is small by construction, and only the close summary passes
|
||||
// once the cap is reached.
|
||||
DiagCap = 64
|
||||
// DiagCollectCommand is the documented collection command: current
|
||||
// boot, only diagnostic lines, capped output.
|
||||
DiagCollectCommand = "journalctl -u groundstation -b --no-pager | grep " + DiagTag + " | tail -60"
|
||||
)
|
||||
|
||||
// Diag emits compact, stable key=value diagnostics into the systemd
|
||||
// journal stream (standard output of the display process). The schema is a
|
||||
// fixed whitelist — process metadata, role and window identifiers,
|
||||
// geometry and shape extents, state enums, stack position, bounded
|
||||
// counters and operation errors — so diagnostics can never carry RC
|
||||
// channel values, telemetry payloads, file contents, environment or
|
||||
// credentials. Records are state-transition-driven: identical consecutive
|
||||
// transitions are deduplicated, the total number of records is capped,
|
||||
// and only the close summary bypasses the cap.
|
||||
type Diag struct {
|
||||
mu sync.Mutex
|
||||
out io.Writer
|
||||
cap int
|
||||
last map[string]string
|
||||
count int
|
||||
}
|
||||
|
||||
// NewDiag builds a diagnostics emitter writing to out.
|
||||
func NewDiag(out io.Writer) *Diag {
|
||||
return &Diag{out: out, cap: DiagCap, last: map[string]string{}}
|
||||
}
|
||||
|
||||
// FormatDiagLine renders one diagnostic record in the exact stable schema.
|
||||
func FormatDiagLine(kind, role string, fields ...string) string {
|
||||
b := &strings.Builder{}
|
||||
b.WriteString(DiagTag)
|
||||
b.WriteString(" kind=")
|
||||
b.WriteString(kind)
|
||||
if role != "" {
|
||||
b.WriteString(" role=")
|
||||
b.WriteString(role)
|
||||
}
|
||||
for _, field := range fields {
|
||||
if field != "" {
|
||||
b.WriteString(" ")
|
||||
b.WriteString(field)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Emit records a state transition or event; identical consecutive records
|
||||
// are deduplicated and the total is capped.
|
||||
func (d *Diag) Emit(kind, role string, fields ...string) {
|
||||
d.emit(kind, role, false, fields...)
|
||||
}
|
||||
|
||||
// EmitForced records a record that must never be dropped by the cap, such
|
||||
// as the close summary.
|
||||
func (d *Diag) EmitForced(kind, role string, fields ...string) {
|
||||
d.emit(kind, role, true, fields...)
|
||||
}
|
||||
|
||||
func (d *Diag) emit(kind, role string, forced bool, fields ...string) {
|
||||
if d == nil {
|
||||
return
|
||||
}
|
||||
line := FormatDiagLine(kind, role, fields...)
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if !forced {
|
||||
if d.count >= d.cap {
|
||||
return
|
||||
}
|
||||
key := kind + "|" + role
|
||||
if d.last[key] == line {
|
||||
return
|
||||
}
|
||||
d.last[key] = line
|
||||
}
|
||||
d.count++
|
||||
if d.out != nil {
|
||||
fmt.Fprintln(d.out, line)
|
||||
}
|
||||
}
|
||||
|
||||
// diagValue sanitizes a free-text diagnostic value: line breaks are
|
||||
// collapsed so a hostile or multiline error can never inject journal lines
|
||||
// into the display_diag stream, and the value is length-bounded. Values
|
||||
// without free text (identifiers, dimensions, enums) bypass this and are
|
||||
// formatted from trusted numeric sources only.
|
||||
func diagValue(text string) string {
|
||||
if text == "" {
|
||||
return text
|
||||
}
|
||||
if len(text) > diagValueMaxLen {
|
||||
text = text[:diagValueMaxLen]
|
||||
}
|
||||
return strings.ReplaceAll(strings.ReplaceAll(text, "\n", " "), "\r", " ")
|
||||
}
|
||||
|
||||
// diagValueMaxLen bounds free-text diagnostic values so a chatty error can
|
||||
// never bloat the journal stream.
|
||||
const diagValueMaxLen = 160
|
||||
|
||||
// VCSRevision returns the VCS revision the binary was built from, or
|
||||
// unknown when the build carried none. No other build or environment
|
||||
// metadata is exposed.
|
||||
func VCSRevision() string {
|
||||
if info, ok := debug.ReadBuildInfo(); ok {
|
||||
for _, setting := range info.Settings {
|
||||
if setting.Key == "vcs.revision" && setting.Value != "" {
|
||||
return setting.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatDiagLineRendersTheExactStableSchema(t *testing.T) {
|
||||
got := FormatDiagLine("first_redraw", "osd",
|
||||
"trigger=initial", "ops=3", "regions=3", "bounds=196x106+28+15",
|
||||
"snap=none", "video=off", "stack=top")
|
||||
want := "display_diag kind=first_redraw role=osd trigger=initial ops=3 regions=3 bounds=196x106+28+15 snap=none video=off stack=top"
|
||||
if got != want {
|
||||
t.Fatalf("line=%q want %q", got, want)
|
||||
}
|
||||
|
||||
// A start record has no role: the role field is omitted entirely.
|
||||
got = FormatDiagLine("start", "", "pid=123", "vcs=unknown")
|
||||
want = "display_diag kind=start pid=123 vcs=unknown"
|
||||
if got != want {
|
||||
t.Fatalf("line=%q want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagCollectCommandTargetsTheStableTagWithATailCap(t *testing.T) {
|
||||
// The documented collection command must filter the journal on the
|
||||
// stable tag and cap the output, so it stays pasteable.
|
||||
if !strings.Contains(DiagCollectCommand, DiagTag) {
|
||||
t.Fatalf("collect command %q must target the stable tag %q", DiagCollectCommand, DiagTag)
|
||||
}
|
||||
if !strings.Contains(DiagCollectCommand, "tail") || !strings.Contains(DiagCollectCommand, "--no-pager") {
|
||||
t.Fatalf("collect command %q must cap with tail and disable paging", DiagCollectCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagDeduplicatesIdenticalStateTransitions(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
d := NewDiag(&buf)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
d.Emit("snap", "osd", "state=fresh")
|
||||
}
|
||||
d.Emit("snap", "osd", "state=stale")
|
||||
d.Emit("snap", "osd", "state=stale")
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("lines=%d (%v) want one fresh and one stale record", len(lines), lines)
|
||||
}
|
||||
if !strings.Contains(lines[0], "state=fresh") || !strings.Contains(lines[1], "state=stale") {
|
||||
t.Fatalf("lines=%v want state transitions only", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagCapsRecordsAndForcesOnlyTheSummary(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
d := NewDiag(&buf)
|
||||
d.cap = 3
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
d.Emit("snap", "osd", "state="+[]string{"fresh", "stale"}[i%2])
|
||||
}
|
||||
d.EmitForced("summary", "osd", "flushes=1")
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
if len(lines) != 4 {
|
||||
t.Fatalf("lines=%d (%v) want the cap plus one forced summary", len(lines), lines)
|
||||
}
|
||||
if !strings.Contains(lines[len(lines)-1], "kind=summary") {
|
||||
t.Fatalf("last line=%q want the forced summary", lines[len(lines)-1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagNilReceiverIsSafe(t *testing.T) {
|
||||
var d *Diag
|
||||
d.Emit("snap", "osd", "state=fresh")
|
||||
d.EmitForced("summary", "osd", "flushes=0")
|
||||
}
|
||||
|
||||
func TestDiagValueSanitizesNewlinesAndBoundsLength(t *testing.T) {
|
||||
// A hostile or multiline error can never inject journal lines into the
|
||||
// display_diag stream: line breaks collapse to spaces and the value is
|
||||
// length-bounded.
|
||||
hostile := "line one\nline two\rinjected line\n" + strings.Repeat("x", 400)
|
||||
got := diagValue(hostile)
|
||||
if strings.ContainsAny(got, "\n\r") {
|
||||
t.Fatalf("sanitized value=%q still carries line breaks", got)
|
||||
}
|
||||
if len(got) != diagValueMaxLen {
|
||||
t.Fatalf("len=%d want the %d-byte bound", len(got), diagValueMaxLen)
|
||||
}
|
||||
if !strings.HasPrefix(got, "line one line two injected line ") {
|
||||
t.Fatalf("sanitized value=%q must preserve content with spaces", got)
|
||||
}
|
||||
if diagValue("") != "" {
|
||||
t.Fatal("an empty value stays empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVCSRevisionReturnsASafeSingleToken(t *testing.T) {
|
||||
// The revision is either the embedded build revision or the explicit
|
||||
// unknown marker: a single token without whitespace either way, safe
|
||||
// for the key=value schema under any build mode.
|
||||
got := VCSRevision()
|
||||
if got == "" || strings.ContainsAny(got, " \t\n\r") {
|
||||
t.Fatalf("vcs revision=%q must be a single safe token", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagLinesCarryNoSensitiveValues(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
d := NewDiag(&buf)
|
||||
|
||||
// Everything the diagnostics can ever emit: process metadata, role and
|
||||
// window identifiers, geometry and shape extents, state enums, stack
|
||||
// position, bounded counters and operation errors. No RC channel
|
||||
// values, telemetry payloads, file contents, environment or
|
||||
// credentials have a field in the schema.
|
||||
d.EmitForced("start", "", "pid=4321", "vcs=0123abcd")
|
||||
d.Emit("open", "osd", "window=0x600001", "root=0x2a0", "cfg=1920x1080",
|
||||
"root_geom=1920x1080", "client_geom=1920x1080", "refresh=1s",
|
||||
"type=DOCK", "wm_state=FULLSCREEN+ABOVE", "shape_init=empty/empty")
|
||||
d.Emit("first_redraw", "osd", "trigger=initial", "ops=3", "regions=3",
|
||||
"bounds=196x106+28+15", "snap=none", "video=off", "stack=top")
|
||||
d.Emit("query", "osd", "shape=196x106+28+15", "geom=1920x1080+0+26",
|
||||
"parent=0x1a00001", "stack=1/3")
|
||||
d.Emit("snap", "osd", "state=stale")
|
||||
d.Emit("video", "osd", "state=on")
|
||||
d.Emit("stack", "osd", "target=video/0x2c00002")
|
||||
d.Emit("reconnect", "osd", "event=open_failed", "error=connect refused", "retry_delay=500ms")
|
||||
d.Emit("error", "osd", "op=shape", "err=bounding shape: BadWindow")
|
||||
d.EmitForced("summary", "osd", "redraws=12", "flushes=12", "errors=1", "snap=stale", "video=on")
|
||||
|
||||
schema := regexp.MustCompile(`^display_diag kind=[a-z_]+( role=[a-z]+)?( [a-z_0-9]+="?[^\s"]+( [^\s"]+)*"?)?$`)
|
||||
for _, line := range strings.Split(strings.TrimSpace(buf.String()), "\n") {
|
||||
if !strings.HasPrefix(line, DiagTag+" ") {
|
||||
t.Fatalf("line=%q must carry the stable tag", line)
|
||||
}
|
||||
if !schema.MatchString(line) {
|
||||
t.Fatalf("line=%q does not match the whitelisted schema", line)
|
||||
}
|
||||
for _, forbidden := range []string{"channel", "channels", "gps", "battery", "attitude", "Xauthority", "env", "password"} {
|
||||
if strings.Contains(strings.ToLower(line), forbidden+"=") {
|
||||
t.Fatalf("line=%q must never carry a %q field", line, forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,11 @@ func NewOSDTemplate(video *VideoPresence, source SnapshotSource) OSDTemplate {
|
||||
func (t OSDTemplate) Draw(canvas Canvas) {
|
||||
canvas.Clear()
|
||||
snapshot, state := t.source.Latest()
|
||||
// Report the snapshot state into the layer's diagnostic stream when
|
||||
// the canvas supports it; transitions are deduplicated there.
|
||||
if reporter, ok := canvas.(interface{ SetDiagSnapshot(string) }); ok {
|
||||
reporter.SetDiagSnapshot(snapshotStateName(state))
|
||||
}
|
||||
t.draw(canvas, snapshot, state)
|
||||
canvas.Flush()
|
||||
}
|
||||
@@ -77,6 +82,17 @@ func armLine(snapshot osd.Snapshot) string {
|
||||
return "ARM OFF"
|
||||
}
|
||||
|
||||
// snapshotStateName names a snapshot state in diagnostics.
|
||||
func snapshotStateName(state osd.SnapshotState) string {
|
||||
switch state {
|
||||
case osd.SnapshotFresh:
|
||||
return "fresh"
|
||||
case osd.SnapshotStale:
|
||||
return "stale"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
func videoState(active bool) string {
|
||||
if active {
|
||||
return "ON"
|
||||
|
||||
+327
-15
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
@@ -348,6 +349,9 @@ type X11Opener struct {
|
||||
// templates consume it to show or hide themselves. When nil the opener
|
||||
// tracks presence in a private signal.
|
||||
Video *VideoPresence
|
||||
// Diag emits the bounded display_diag journal stream for this layer.
|
||||
// Nil disables diagnostics.
|
||||
Diag *Diag
|
||||
// Role orders this layer's window against presented video: RoleBelow
|
||||
// for the fallback/menu canvas, RoleAbove for the OSD overlay.
|
||||
Role LayerRole
|
||||
@@ -579,7 +583,7 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) {
|
||||
}
|
||||
}
|
||||
|
||||
return &x11Session{
|
||||
s := &x11Session{
|
||||
conn: conn,
|
||||
window: window,
|
||||
gc: gc,
|
||||
@@ -587,6 +591,7 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) {
|
||||
height: int(screen.HeightInPixels),
|
||||
black: screen.BlackPixel,
|
||||
white: screen.WhitePixel,
|
||||
root: screen.Root,
|
||||
poll: o.pollInterval(),
|
||||
refresh: o.RefreshInterval,
|
||||
video: presence,
|
||||
@@ -597,12 +602,50 @@ func (o X11Opener) Open(ctx context.Context) (Session, error) {
|
||||
role: o.Role,
|
||||
unicodeFont: unicodeFont,
|
||||
cursor: cursor,
|
||||
diag: o.Diag,
|
||||
queries: connQueries{conn: conn, root: screen.Root},
|
||||
lastTrigger: "initial",
|
||||
fontAscent: ascent,
|
||||
fontDescent: descent,
|
||||
fontCell: cell,
|
||||
pollEvent: conn.PollForEvent,
|
||||
probe: connLivenessProbe(conn),
|
||||
}, nil
|
||||
}
|
||||
s.recordOpen(o.RefreshInterval)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// recordOpen emits the one per-role open record: role, window and root
|
||||
// identifiers, configured/root/client geometry, refresh interval, the EWMH
|
||||
// type/state intent, and the initial shape intent. The one synchronous
|
||||
// geometry round trip runs here, where first-open queries are allowed.
|
||||
func (s *x11Session) recordOpen(refresh time.Duration) {
|
||||
if s.diag == nil {
|
||||
return
|
||||
}
|
||||
clientGeom := "unknown"
|
||||
if reply, err := xproto.GetGeometry(s.conn, xproto.Drawable(s.window)).Reply(); err == nil {
|
||||
clientGeom = fmt.Sprintf("%dx%d+%d+%d", reply.Width, reply.Height, reply.X, reply.Y)
|
||||
}
|
||||
wmType := ewmhWindowTypeName(s.role)
|
||||
if wmType == "" {
|
||||
wmType = "none"
|
||||
}
|
||||
shapeInit := "unshaped"
|
||||
if s.role == RoleAbove {
|
||||
shapeInit = "empty/empty"
|
||||
}
|
||||
s.diag.Emit("open", roleName(s.role),
|
||||
fmt.Sprintf("window=0x%x", s.window),
|
||||
fmt.Sprintf("root=0x%x", s.root),
|
||||
fmt.Sprintf("cfg=%dx%d", s.width, s.height),
|
||||
fmt.Sprintf("root_geom=%dx%d", s.width, s.height),
|
||||
"client_geom="+clientGeom,
|
||||
"refresh="+refresh.String(),
|
||||
"type="+wmType,
|
||||
"wm_state="+strings.Join(fullscreenStateAtoms(s.role), "+"),
|
||||
"shape_init="+shapeInit,
|
||||
)
|
||||
}
|
||||
|
||||
func videoWindowSet(windows []xproto.Window) map[xproto.Window]struct{} {
|
||||
@@ -854,6 +897,7 @@ type x11Session struct {
|
||||
height int
|
||||
black uint32
|
||||
white uint32
|
||||
root xproto.Window
|
||||
poll time.Duration
|
||||
refresh time.Duration
|
||||
video *VideoPresence
|
||||
@@ -869,6 +913,21 @@ type x11Session struct {
|
||||
// cursor is the blank cursor applied to the layer window at creation;
|
||||
// it is freed when the session closes.
|
||||
cursor xproto.Cursor
|
||||
// Diagnostics: the emitter, a checked query seam for the one-time
|
||||
// post-first-flush evidence, the trigger of the current draw pass,
|
||||
// the snapshot state reported by the template, per-pass template
|
||||
// operation counts, bounded counters, and the last announced stack
|
||||
// target. All fields are touched only on the layer's own goroutine.
|
||||
diag *Diag
|
||||
queries xquery
|
||||
lastTrigger string
|
||||
diagSnap string
|
||||
passOps int
|
||||
flushes int
|
||||
redraws int
|
||||
errors int
|
||||
firstFlush bool
|
||||
lastStack string
|
||||
// fontAscent, fontDescent and fontCell describe the drawn font so the
|
||||
// OSD overlay can punch its output shape around each text's glyph cell.
|
||||
fontAscent int16
|
||||
@@ -893,6 +952,7 @@ func (s *x11Session) Clear() {
|
||||
// A fresh draw pass starts with no output regions: the OSD overlay's
|
||||
// next flush re-punches its shape over exactly what this pass draws.
|
||||
s.resetOSDRegions()
|
||||
s.passOps = 0
|
||||
// ClearArea tiles the window background (black, set at creation); it
|
||||
// involves no graphics context.
|
||||
xproto.ClearArea(s.conn, false, s.window, 0, 0,
|
||||
@@ -911,6 +971,7 @@ func (s *x11Session) Text(x, y int, message string) {
|
||||
xproto.ImageText16(s.conn, byte(len(chars)), xproto.Drawable(s.window), s.gc,
|
||||
int16(x), int16(y), chars)
|
||||
s.recordOSDText(x, y, len(chars))
|
||||
s.passOps++
|
||||
return
|
||||
}
|
||||
message = foldToASCII(message)
|
||||
@@ -920,6 +981,7 @@ func (s *x11Session) Text(x, y int, message string) {
|
||||
xproto.ImageText8(s.conn, byte(len(message)), xproto.Drawable(s.window), s.gc,
|
||||
int16(x), int16(y), message)
|
||||
s.recordOSDText(x, y, len(message))
|
||||
s.passOps++
|
||||
}
|
||||
|
||||
// recordOSDText remembers one drawn text's output region so the overlay's
|
||||
@@ -933,20 +995,228 @@ func (s *x11Session) recordOSDText(x, y, units int) {
|
||||
osdTextRect(x, y, units, s.fontCell, s.fontAscent, s.fontDescent))
|
||||
}
|
||||
|
||||
// Flush presents pixels only where this draw pass put text (the overlay's
|
||||
// bounding shape is re-punched over the recorded regions while its input
|
||||
// shape stays empty), records the bounded diagnostics for the pass, and
|
||||
// syncs the connection.
|
||||
func (s *x11Session) Flush() {
|
||||
// The OSD overlay presents pixels only where this draw pass put text:
|
||||
// its bounding shape is re-punched over the recorded regions while its
|
||||
// input shape stays empty, so it never covers video elsewhere and
|
||||
// never intercepts input. A failure here is a broken connection; the
|
||||
// liveness probe below ends the session and the layer reconnects.
|
||||
var shapeErr error
|
||||
if s.role == RoleAbove {
|
||||
if err := applyOSDShapes(s.conn, s.window, s.drawn); err != nil {
|
||||
log.Printf("osd overlay shapes: %v", err)
|
||||
if shapeErr = applyOSDShapes(s.conn, s.window, s.drawn); shapeErr != nil {
|
||||
log.Printf("osd overlay shapes: %v", shapeErr)
|
||||
s.errors++
|
||||
}
|
||||
}
|
||||
s.recordFlush(shapeErr)
|
||||
s.conn.Sync()
|
||||
}
|
||||
|
||||
// recordFlush emits the first-flush evidence — trigger, template
|
||||
// operations, requested regions, snapshot and video state, stack target,
|
||||
// and the shape result — plus, once, the queried actual shape extents,
|
||||
// client geometry, parent and stack position. Everything after this
|
||||
// record is state-transition-driven: no per-refresh diagnostics exist.
|
||||
// Diagnostics never make synchronous hot-path round trips; the one query
|
||||
// bundle runs right after the first flush, where it is allowed.
|
||||
func (s *x11Session) recordFlush(shapeErr error) {
|
||||
s.flushes++
|
||||
if s.diag == nil || s.firstFlush {
|
||||
return
|
||||
}
|
||||
s.firstFlush = true
|
||||
|
||||
video := "off"
|
||||
if s.video != nil && s.video.Active() {
|
||||
video = "on"
|
||||
}
|
||||
snap := s.diagSnap
|
||||
if snap == "" {
|
||||
snap = "none"
|
||||
}
|
||||
bounds, regions := osdRegionBounds(s.drawn)
|
||||
fields := []string{
|
||||
"trigger=" + s.lastTrigger,
|
||||
fmt.Sprintf("ops=%d", s.passOps),
|
||||
fmt.Sprintf("regions=%d", regions),
|
||||
"bounds=" + bounds,
|
||||
"snap=" + snap,
|
||||
"video=" + video,
|
||||
"stack=" + s.stackTarget(),
|
||||
}
|
||||
if shapeErr != nil {
|
||||
fields = append(fields, "ok=no", "err="+diagValue(shapeErr.Error()))
|
||||
} else {
|
||||
fields = append(fields, "ok")
|
||||
}
|
||||
s.diag.Emit("first_redraw", roleName(s.role), fields...)
|
||||
s.emitQueryBundle(roleName(s.role))
|
||||
}
|
||||
|
||||
// emitQueryBundle asks the server, once, for the actual shape extents,
|
||||
// client geometry, parent and stacking position of the layer window, and
|
||||
// records them with any errors attached. Best-effort: failures become
|
||||
// diagnostic fields, never layer failures.
|
||||
func (s *x11Session) emitQueryBundle(role string) {
|
||||
if s.queries == nil {
|
||||
return
|
||||
}
|
||||
var fields, errs []string
|
||||
if v, err := s.queries.ShapeExtents(s.window); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
} else {
|
||||
fields = append(fields, "shape="+v)
|
||||
}
|
||||
if v, err := s.queries.Geometry(s.window); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
} else {
|
||||
fields = append(fields, "geom="+v)
|
||||
}
|
||||
if v, err := s.queries.Parent(s.window); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
} else {
|
||||
fields = append(fields, "parent="+v)
|
||||
}
|
||||
if pos, of, err := s.queries.StackPosition(s.window); err != nil {
|
||||
errs = append(errs, err.Error())
|
||||
} else {
|
||||
fields = append(fields, "stack="+pos+"/"+of)
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
fields = append(fields, "err="+diagValue(strings.Join(errs, "; ")))
|
||||
}
|
||||
s.diag.Emit("query", role, fields...)
|
||||
}
|
||||
|
||||
// osdRegionBounds returns the union bounds of the drawn regions in
|
||||
// xwininfo-style WxH+X+Y notation, plus the region count.
|
||||
func osdRegionBounds(rects []xproto.Rectangle) (string, int) {
|
||||
if len(rects) == 0 {
|
||||
return "none", 0
|
||||
}
|
||||
minX, minY := int32(1<<30), int32(1<<30)
|
||||
maxX, maxY := int32(-1<<30), int32(-1<<30)
|
||||
for _, r := range rects {
|
||||
minX = minInt32(minX, int32(r.X))
|
||||
minY = minInt32(minY, int32(r.Y))
|
||||
maxX = maxInt32(maxX, int32(r.X)+int32(r.Width))
|
||||
maxY = maxInt32(maxY, int32(r.Y)+int32(r.Height))
|
||||
}
|
||||
return fmt.Sprintf("%dx%d+%d+%d", maxX-minX, maxY-minY, minX, minY), len(rects)
|
||||
}
|
||||
|
||||
func minInt32(a, b int32) int32 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func maxInt32(a, b int32) int32 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// SetDiagSnapshot records the snapshot state the template just rendered
|
||||
// with; identical consecutive states are deduplicated by the emitter.
|
||||
// It is satisfied only by the real session canvas, so fakes are unaffected.
|
||||
func (s *x11Session) SetDiagSnapshot(state string) {
|
||||
s.diagSnap = state
|
||||
if s.diag != nil {
|
||||
s.diag.Emit("snap", roleName(s.role), "state="+state)
|
||||
}
|
||||
}
|
||||
|
||||
// xquery is the checked query surface used for the one-time post-first-
|
||||
// flush evidence: actual shape extents, client geometry, parent window and
|
||||
// stacking position. Production adapts the connection; tests script it.
|
||||
type xquery interface {
|
||||
ShapeExtents(window xproto.Window) (string, error)
|
||||
Geometry(window xproto.Window) (string, error)
|
||||
Parent(window xproto.Window) (string, error)
|
||||
StackPosition(window xproto.Window) (string, string, error)
|
||||
}
|
||||
|
||||
// connQueries implements xquery over the real connection. The stacking
|
||||
// position is read from the window manager's _NET_CLIENT_LIST_STACKING
|
||||
// property; a missing property reports an error rather than guessing.
|
||||
type connQueries struct {
|
||||
conn *xgb.Conn
|
||||
root xproto.Window
|
||||
}
|
||||
|
||||
func (q connQueries) ShapeExtents(window xproto.Window) (string, error) {
|
||||
reply, err := shape.QueryExtents(q.conn, window).Reply()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%dx%d+%d+%d", reply.BoundingShapeExtentsWidth, reply.BoundingShapeExtentsHeight, reply.BoundingShapeExtentsX, reply.BoundingShapeExtentsY), nil
|
||||
}
|
||||
|
||||
func (q connQueries) Geometry(window xproto.Window) (string, error) {
|
||||
reply, err := xproto.GetGeometry(q.conn, xproto.Drawable(window)).Reply()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%dx%d+%d+%d", reply.Width, reply.Height, reply.X, reply.Y), nil
|
||||
}
|
||||
|
||||
func (q connQueries) Parent(window xproto.Window) (string, error) {
|
||||
reply, err := xproto.QueryTree(q.conn, window).Reply()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("0x%x", reply.Parent), nil
|
||||
}
|
||||
|
||||
func (q connQueries) StackPosition(window xproto.Window) (string, string, error) {
|
||||
atom := internAtom(q.conn, "_NET_CLIENT_LIST_STACKING")
|
||||
if atom == 0 {
|
||||
return "", "", fmt.Errorf("stacking property unavailable")
|
||||
}
|
||||
reply, err := xproto.GetProperty(q.conn, false, q.root, atom,
|
||||
xproto.GetPropertyTypeAny, 0, 256).Reply()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
total := 0
|
||||
position := -1
|
||||
for i := 0; i+4 <= len(reply.Value); i += 4 {
|
||||
total++
|
||||
if xproto.Window(binary.LittleEndian.Uint32(reply.Value[i:i+4])) == window {
|
||||
position = total
|
||||
}
|
||||
}
|
||||
if position < 0 {
|
||||
return "", "", fmt.Errorf("window is not a managed client")
|
||||
}
|
||||
return strconv.Itoa(position), strconv.Itoa(total), nil
|
||||
}
|
||||
|
||||
// stackTarget names where the OSD overlay currently re-asserts its place:
|
||||
// above the tracked video window, on top of the stack while video is
|
||||
// absent, or none when the overlay has no restack policy for the state.
|
||||
func (s *x11Session) stackTarget() string {
|
||||
videoActive := s.video != nil && s.video.Active()
|
||||
sibling, _, ok := stackReassert(s.role, videoActive, s.topVideo, s.videoWindows)
|
||||
if !ok {
|
||||
return "none"
|
||||
}
|
||||
if sibling == 0 {
|
||||
return "top"
|
||||
}
|
||||
return fmt.Sprintf("video/0x%x", sibling)
|
||||
}
|
||||
|
||||
// roleName names a layer role in diagnostics.
|
||||
func roleName(role LayerRole) string {
|
||||
if role == RoleAbove {
|
||||
return "osd"
|
||||
}
|
||||
return "canvas"
|
||||
}
|
||||
|
||||
// applyOSDShapes sets the overlay's bounding shape to the drawn regions
|
||||
// (possibly none) and keeps its input shape empty.
|
||||
func applyOSDShapes(conn *xgb.Conn, window xproto.Window, rects []xproto.Rectangle) error {
|
||||
@@ -980,9 +1250,11 @@ func (s *x11Session) WaitEvent(ctx context.Context) (bool, error) {
|
||||
break
|
||||
}
|
||||
if x11WantsRedraw(event) {
|
||||
s.noteRedraw("expose")
|
||||
return true, nil
|
||||
}
|
||||
if s.applyVideoChange(event) {
|
||||
s.noteRedraw("video")
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
@@ -996,6 +1268,7 @@ func (s *x11Session) WaitEvent(ctx context.Context) (bool, error) {
|
||||
// above fullscreen video: window managers may have promoted
|
||||
// the video window back on top since the appear restack.
|
||||
s.reassertStacking()
|
||||
s.noteRedraw("refresh")
|
||||
return true, nil
|
||||
}
|
||||
// Round trip keeps the connection liveness visible even without
|
||||
@@ -1012,16 +1285,31 @@ func (s *x11Session) WaitEvent(ctx context.Context) (bool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// noteRedraw counts a redraw and records what triggered it for the
|
||||
// first-flush diagnostic record.
|
||||
func (s *x11Session) noteRedraw(trigger string) {
|
||||
s.redraws++
|
||||
s.lastTrigger = trigger
|
||||
}
|
||||
|
||||
// reassertStacking re-claims the overlay's stacking place on the OSD's
|
||||
// slower refresh cadence: above the live video window, or on top of the
|
||||
// stack while video is absent so the fallback canvas can never bury it. A
|
||||
// no-op for the canvas layer.
|
||||
// no-op for the canvas layer. Target changes are announced in diagnostics;
|
||||
// identical targets are deduplicated by the emitter.
|
||||
func (s *x11Session) reassertStacking() {
|
||||
videoActive := s.video != nil && s.video.Active()
|
||||
sibling, mode, ok := stackReassert(s.role, videoActive, s.topVideo, s.videoWindows)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
target := s.stackTarget()
|
||||
if target != s.lastStack {
|
||||
s.lastStack = target
|
||||
if s.diag != nil {
|
||||
s.diag.Emit("stack", roleName(s.role), "target="+target)
|
||||
}
|
||||
}
|
||||
if sibling != 0 {
|
||||
stackWindowRelative(s.conn, s.window, sibling, mode)
|
||||
return
|
||||
@@ -1053,7 +1341,11 @@ func (s *x11Session) applyVideoChange(event xgb.Event) bool {
|
||||
// of it, and remember it as the restack target for later re-claims.
|
||||
s.topVideo = w
|
||||
stackWindowRelative(s.conn, s.window, w, stackModeForVideoAppear(s.role))
|
||||
return s.video.SetActive(true)
|
||||
changed := s.video.SetActive(true)
|
||||
if changed && s.diag != nil {
|
||||
s.diag.Emit("video", roleName(s.role), "state=on")
|
||||
}
|
||||
return changed
|
||||
case videoDisappeared:
|
||||
if !removeVideoWindow(s.videoWindows, w) {
|
||||
return false
|
||||
@@ -1068,7 +1360,11 @@ func (s *x11Session) applyVideoChange(event xgb.Event) bool {
|
||||
xproto.ConfigureWindow(s.conn, s.window,
|
||||
xproto.ConfigWindowStackMode, []uint32{xproto.StackModeAbove})
|
||||
}
|
||||
return s.video.SetActive(false)
|
||||
changed := s.video.SetActive(false)
|
||||
if changed && s.diag != nil {
|
||||
s.diag.Emit("video", roleName(s.role), "state=off")
|
||||
}
|
||||
return changed
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -1151,9 +1447,25 @@ func foldToASCII(message string) string {
|
||||
}
|
||||
|
||||
func (s *x11Session) Close() error {
|
||||
// Free the blank cursor when one was created; closing the connection
|
||||
// then makes the X server reclaim everything else, including the kiosk
|
||||
// window.
|
||||
// One bounded summary closes this session's diagnostic stream, then
|
||||
// the blank cursor is freed and the connection drop makes the X
|
||||
// server reclaim everything else, including the kiosk window.
|
||||
if s.diag != nil {
|
||||
snap := s.diagSnap
|
||||
if snap == "" {
|
||||
snap = "none"
|
||||
}
|
||||
video := "off"
|
||||
if s.video != nil && s.video.Active() {
|
||||
video = "on"
|
||||
}
|
||||
s.diag.EmitForced("summary", roleName(s.role),
|
||||
fmt.Sprintf("redraws=%d", s.redraws),
|
||||
fmt.Sprintf("flushes=%d", s.flushes),
|
||||
fmt.Sprintf("errors=%d", s.errors),
|
||||
"snap="+snap,
|
||||
"video="+video)
|
||||
}
|
||||
if s.cursor != 0 {
|
||||
xproto.FreeCursor(s.conn, s.cursor)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -498,6 +499,121 @@ func TestCreateWindowValuesOmitCursorWhenUnavailable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// scriptedQueries scripts the one-time query bundle: fixed answers for
|
||||
// shape extents, geometry, parent and stacking position, with an optional
|
||||
// shape query error.
|
||||
type scriptedQueries struct {
|
||||
shape string
|
||||
geom string
|
||||
parent string
|
||||
pos string
|
||||
of string
|
||||
shapeErr error
|
||||
}
|
||||
|
||||
func (q *scriptedQueries) ShapeExtents(xproto.Window) (string, error) {
|
||||
return q.shape, q.shapeErr
|
||||
}
|
||||
|
||||
func (q *scriptedQueries) Geometry(xproto.Window) (string, error) {
|
||||
return q.geom, nil
|
||||
}
|
||||
|
||||
func (q *scriptedQueries) Parent(xproto.Window) (string, error) {
|
||||
return q.parent, nil
|
||||
}
|
||||
|
||||
func (q *scriptedQueries) StackPosition(xproto.Window) (string, string, error) {
|
||||
return q.pos, q.of, nil
|
||||
}
|
||||
|
||||
func TestRecordFlushEmitsFirstRedrawAndQueryBundleOnce(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
presence := NewVideoPresence()
|
||||
session := &x11Session{
|
||||
role: RoleAbove,
|
||||
diag: NewDiag(&buf),
|
||||
video: presence,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
lastTrigger: "initial",
|
||||
queries: &scriptedQueries{
|
||||
shape: "196x106+28+15", geom: "1920x1080+0+26",
|
||||
parent: "0x1a00001", pos: "1", of: "3",
|
||||
},
|
||||
}
|
||||
session.drawn = []xproto.Rectangle{
|
||||
{X: 30, Y: 19, Width: 58, Height: 18},
|
||||
{X: 30, Y: 51, Width: 196, Height: 18},
|
||||
{X: 30, Y: 83, Width: 120, Height: 18},
|
||||
}
|
||||
|
||||
session.recordFlush(nil)
|
||||
session.recordFlush(nil) // the bundle and the first-redraw record are once-only
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("lines=%v want exactly the first_redraw and query records", lines)
|
||||
}
|
||||
wantFirst := "display_diag kind=first_redraw role=osd trigger=initial ops=0 regions=3 bounds=196x82+30+19 snap=none video=off stack=top ok"
|
||||
if lines[0] != wantFirst {
|
||||
t.Fatalf("first_redraw=%q want %q", lines[0], wantFirst)
|
||||
}
|
||||
wantQuery := "display_diag kind=query role=osd shape=196x106+28+15 geom=1920x1080+0+26 parent=0x1a00001 stack=1/3"
|
||||
if lines[1] != wantQuery {
|
||||
t.Fatalf("query=%q want %q", lines[1], wantQuery)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordFlushReportsShapeErrorsWithoutBlockingTheLayer(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
session := &x11Session{
|
||||
role: RoleAbove,
|
||||
diag: NewDiag(&buf),
|
||||
video: NewVideoPresence(),
|
||||
lastTrigger: "refresh",
|
||||
queries: &scriptedQueries{shapeErr: errors.New("BadWindow")},
|
||||
}
|
||||
|
||||
// The shape error arrives with the first flush: it must be carried by
|
||||
// the first_redraw record and the query bundle reports its own query
|
||||
// failure alongside.
|
||||
session.recordFlush(errors.New("bounding shape: BadWindow"))
|
||||
session.recordFlush(nil)
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
if len(lines) != 2 {
|
||||
t.Fatalf("lines=%v want the first_redraw error record and the query error record", lines)
|
||||
}
|
||||
if !strings.Contains(lines[0], "ok=no") || !strings.Contains(lines[0], "err=bounding shape: BadWindow") {
|
||||
t.Fatalf("first_redraw=%q must carry the shape error", lines[0])
|
||||
}
|
||||
if !strings.Contains(lines[1], "err=") {
|
||||
t.Fatalf("query=%q must carry the query error", lines[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetDiagSnapshotEmitsTransitionsOnly(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
session := &x11Session{role: RoleAbove, diag: NewDiag(&buf)}
|
||||
|
||||
session.SetDiagSnapshot("none")
|
||||
session.SetDiagSnapshot("none")
|
||||
session.SetDiagSnapshot("fresh")
|
||||
session.SetDiagSnapshot("fresh")
|
||||
session.SetDiagSnapshot("stale")
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("lines=%v want none, fresh and stale transitions only", lines)
|
||||
}
|
||||
for i, want := range []string{"none", "fresh", "stale"} {
|
||||
if !strings.Contains(lines[i], "kind=snap") || !strings.Contains(lines[i], "state="+want) {
|
||||
t.Fatalf("line %d=%q want the %s transition", i, lines[i], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransparentShapesEmptyInputAndOutput(t *testing.T) {
|
||||
var input, output bool
|
||||
for _, kind := range transparentShapeKinds() {
|
||||
|
||||
Reference in New Issue
Block a user