v0.5.0 key releases: key model, protocol source, console sources (#12)

* key model for releases: KeyAction, SetKeyReport, focus and key report events, hold pairing

A key event now carries its Action: KeyPress, KeyRepeat or KeyRelease. Every
terminal still reports presses only, so Action stays KeyPress and every event
is what v0.4.3 sent, until a game asks with SetKeyReport. The ask names the
sources releases may come from (KeySourceConsole, KeySourceProtocol); an
EventKeyReport answers each ask with the level reached and its source. No
source exists yet, so every ask answers presses and nothing is written.

KeyHolds pairs a release with its press by physical key, so a release carries
what its press carried, and turns a source's lost reports into Lost releases.
It is exported for hosts that read native key events (KeySourceHost).

The reader sends keys through the level in force: at presses a repeat is a
press and a release is dropped; at releases a key with no physical key behind
it is a tap. Focus reports end every hold, Lost, before EventFocus; they are
read only once a source turns them on. Mouse events gain a Touch bit for hosts.

Terminal gains SetKeyReport, so this is v0.5.0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zCVjspRDuEuMrDTumVhp

* protocol source: releases from the terminal's key event protocol, Alacritty's

SetKeyReport with KeySourceProtocol asks the terminal whether it has the key
event protocol (CSI ? u, fenced by a DA1 request), pushes its flags (all five,
CSI > 31 u) and asks what they came to before reporting releases. A terminal
must confirm event types, every key as an escape code and the text keys type;
one that answers DA1 alone, takes the push without them, or answers nothing
within two seconds stays at presses, and is not asked again. Detection goes by
these answers only, never by TERM or the terminal's name.

While the flags are pushed, key reports are decoded into the events a legacy
terminal sends for the same keys, so a game can keep the protocol on for its
whole run: Shift goes into the character, Ctrl with a character into its
control key, Alt stays a modifier; Super, the locks, lone modifiers, media keys
and F13 and up report nothing. Ctrl with a character that has no control key
keeps ModCtrl. Releases pair with their presses through KeyHolds; a key the
terminal names none for (text from an input method) is a tap.

Focus reports come on with the protocol and end every hold, Lost, as focus
leaves. Going back to presses releases what is held, pops the flags and stops
focus reports, decoding until the terminal confirms the pop. Fini pops the
flags before the alternate screen goes, and EmergencyReset when they are
pushed. Fini now stops the input reader without holding the terminal's lock,
since the reader writes its requests through it.

Checked against Alacritty 0.13.2 on Xvfb with xdotool: 58 key combinations
read identically with the protocol on and off (Ctrl+1 keeps ModCtrl), every
press got its release, Shift released first still released 'A', focus loss
and a release swallowed by Alacritty's Vi mode ended holds Lost. Inside tmux
3.4 the ask came to presses.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zCVjspRDuEuMrDTumVhp

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
LixenandClaude Opus 5.5 authored and GitHub committed 2026-10-21 03:59:00 -04:00
1 parent a8805d9be1
commit 97f66b1f1c
10 files changed
+1311 -18

No files matched your search

+103 -15
View File
@@ -16,10 +16,12 @@ type EventType uint8
const (
EventKey EventType = iota
EventResize
EventPaste // Bracketed paste, Text holds it
EventMouse // SGR mouse reporting
EventError // Read error
EventClosed // Input closed
EventPaste // Bracketed paste, Text holds it
EventMouse // SGR mouse reporting
EventError // Read error
EventClosed // Input closed
EventFocus // The terminal gained or lost focus, while it reports releases through its protocol
EventKeyReport // What a SetKeyReport ask came to: Report through Source
)
// Event represents a terminal input event
@@ -28,16 +30,22 @@ type Event struct {
Key Key
Rune rune
Modifiers Modifier
Width int // For EventResize
Height int // For EventResize
Err error // For EventError
Text string // For EventPaste: the pasted bytes as sent, controls included
Action KeyAction // For EventKey: KeyPress unless the terminal reports releases
Lost bool // For a KeyRelease the package made for a hold whose own release can't arrive
Width int // For EventResize
Height int // For EventResize
Err error // For EventError
Text string // For EventPaste: the pasted bytes as sent, controls included
Focused bool // For EventFocus: whether the terminal now has focus
Report KeyReport // For EventKeyReport: what the terminal now reports of each key
Source KeySource // For EventKeyReport: the source releases come from, zero for presses
// Mouse event fields
MouseX int
MouseY int
MouseBtn MouseButton
MouseAction MouseAction
Touch bool // A touch, from a host that reads one; terminals report none
}
// inputReader handles raw stdin parsing
@@ -60,6 +68,34 @@ type inputReader struct {
// An over-long CSI sequence is being dropped up to its final byte
dropCSI bool
// Key reporting asks: the sources the backend has, the latest ask waiting
// for the reader, and how the reader writes to the terminal, false once it
// is closing; pushed is whether the protocol's flags are pushed after seq
sources KeySource
asks chan keyAsk
write func(seq []byte, pushed bool) bool
// Key reporting, the reader's own: the ask it works toward and whether it
// is still to be answered, what the terminal reports of each key and the
// source releases come from, whether focus reports are parsed, and the
// keys a source reports held down
want keyAsk
answer bool
report KeyReport
source KeySource
focus bool
holds KeyHolds
// The protocol: an exchange in flight and when it is given up, the flags
// the terminal reported in it (-1 for none), whether the terminal has the
// protocol (-1 no, 0 not known, 1 yes), and whether key reports are
// decoded, from the push until the terminal has the pop
exchange protoExchange
deadline time.Time
protoReported int
protoHas int8
decoding bool
mu sync.Mutex
running bool
}
@@ -69,6 +105,7 @@ func newInputReader(backend Backend) *inputReader {
return &inputReader{
backend: backend,
eventCh: make(chan Event, 256),
asks: make(chan keyAsk, 1),
stopCh: make(chan struct{}),
doneCh: make(chan struct{}),
buf: make([]byte, 0, 256),
@@ -128,9 +165,12 @@ func (r *inputReader) readLoop() {
}()
for {
r.serviceKeys()
// Blocking read from backend
data, err := r.backend.Read(r.stopCh)
if err != nil {
r.holds.ReleaseAll(r.sendEvent)
r.sendEvent(Event{Type: EventError, Err: err})
return
}
@@ -147,11 +187,12 @@ func (r *inputReader) readLoop() {
// Timeout (Unix poll) or empty read: a pending ESC, or two, was
// pressed alone; inside a paste it is text
if ev, ok := loneEscape[string(r.buf)]; ok && !r.pasting {
r.sendEvent(ev)
r.sendKey(0, ev)
r.buf = r.buf[:0]
}
select {
case <-r.stopCh:
r.holds.ReleaseAll(r.sendEvent)
r.sendEvent(Event{Type: EventClosed})
return
default:
@@ -226,7 +267,7 @@ func (r *inputReader) parseInput(data []byte) int {
// Fast path: printable ASCII
if b >= 0x20 && b < 0x7f {
r.sendEvent(Event{Type: EventKey, Key: KeyRune, Rune: rune(b)})
r.sendKey(0, Event{Type: EventKey, Key: KeyRune, Rune: rune(b)})
i++
continue
}
@@ -245,8 +286,10 @@ func (r *inputReader) parseInput(data []byte) int {
}
// Only emit if not a swallowed unknown sequence
if ev.Key != KeyNone || ev.Type != EventKey {
if ev.Type != EventKey {
r.sendEvent(ev)
} else if ev.Key != KeyNone {
r.sendKey(0, ev)
}
i += consumed
continue
@@ -254,14 +297,14 @@ func (r *inputReader) parseInput(data []byte) int {
// Control characters
if b < 0x20 {
r.sendEvent(r.parseControl(b))
r.sendKey(0, r.parseControl(b))
i++
continue
}
// DEL
if b == 0x7f {
r.sendEvent(Event{Type: EventKey, Key: KeyBackspace})
r.sendKey(0, Event{Type: EventKey, Key: KeyBackspace})
i++
continue
}
@@ -281,7 +324,7 @@ func (r *inputReader) parseInput(data []byte) int {
}
rn, size := decodeRune(data[i:])
r.sendEvent(Event{Type: EventKey, Key: KeyRune, Rune: rn})
r.sendKey(0, Event{Type: EventKey, Key: KeyRune, Rune: rn})
i += size
continue
}
@@ -432,6 +475,25 @@ func (r *inputReader) parseCSI(data []byte) (int, Event) {
return csiMaxLen, Event{Type: EventKey, Key: KeyNone}
case data[2] == '<' && (data[n-1] == 'M' || data[n-1] == 'm'):
return n, parseSGRMouse(data[3:n-1], data[n-1])
case r.focus && n == 3 && (data[2] == 'I' || data[2] == 'O'):
// Holds end as focus leaves, since their releases go elsewhere
if data[2] == 'O' {
r.holds.ReleaseAll(r.sendEvent)
}
return n, Event{Type: EventFocus, Focused: data[2] == 'I'}
case data[2] == '?' && data[n-1] == 'u':
// The protocol's flags in force, answering a query
if v, ok := parseKeyParams(data[3 : n-1]); ok {
r.protoReply(int(max(v[0][0], 0)))
}
return n, Event{Type: EventKey, Key: KeyNone}
case data[2] == '?' && data[n-1] == 'c':
// Device attributes, which close an exchange: the terminal has
// answered all asked before them
r.exchangeDone(true)
return n, Event{Type: EventKey, Key: KeyNone}
case r.decoding && r.protoKey(data[2:n-1], data[n-1]):
return n, Event{Type: EventKey, Key: KeyNone}
}
if key, mod, ok := lookupCSI(data[2:n]); ok {
@@ -448,7 +510,13 @@ func (r *inputReader) parseSS3(data []byte) (int, Event) {
return 0, Event{}
}
if key, mod, ok := lookupSS3(data[2:3]); ok {
return 3, Event{Type: EventKey, Key: key, Modifiers: mod}
ev := Event{Type: EventKey, Key: key, Modifiers: mod}
if r.decoding && key != KeyRune {
// A terminal reporting by the protocol names this key too
r.sendKey(protoNamed+uint32(key), ev)
return 3, Event{Type: EventKey, Key: KeyNone}
}
return 3, ev
}
// Unknown SS3 - consume to prevent garbage
return 3, Event{Type: EventKey, Key: KeyNone}
@@ -626,6 +694,26 @@ func parseSGRParams(data []byte) (btn, x, y int, ok bool) {
return btn, x, y, true
}
// sendKey sends a key event at the level the terminal reports. code names the
// physical key the event came from, zero for one the terminal names none for:
// at releases such a key can't be held, so its release follows at once.
func (r *inputReader) sendKey(code uint32, ev Event) {
switch {
case r.report == KeyReportPresses:
if ev.Action != KeyRelease {
ev.Action = KeyPress
r.sendEvent(ev)
}
case code == 0:
ev.Action = KeyPress
r.sendEvent(ev)
ev.Action = KeyRelease
r.sendEvent(ev)
default:
r.holds.Report(code, ev, r.sendEvent)
}
}
// sendEvent sends an event to the channel, non-blocking
func (r *inputReader) sendEvent(ev Event) {
select {