feat: add bounded display_diag journal diagnostics for the OSD (#3)

This commit is contained in:
2026-11-24 15:24:39 +01:00
parent 5d067ee82d
commit 903c5c69b6
8 changed files with 779 additions and 28 deletions
+327 -15
View File
@@ -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)
}