* 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>
187 lines
3.8 KiB
Go
187 lines
3.8 KiB
Go
//go:build unix
|
|
|
|
package terminal
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
|
|
"golang.org/x/sys/unix"
|
|
"golang.org/x/term"
|
|
)
|
|
|
|
type unixBackend struct {
|
|
in *os.File
|
|
out *os.File
|
|
inFd int
|
|
outFd int
|
|
tty *os.File // the controlling terminal, opened for a redirected end
|
|
oldTerm *term.State
|
|
|
|
resizeStopCh chan struct{}
|
|
resizeDoneCh chan struct{}
|
|
}
|
|
|
|
const escapeTimeoutMs = 10
|
|
|
|
func newBackend() Backend {
|
|
return &unixBackend{
|
|
in: os.Stdin,
|
|
out: os.Stdout,
|
|
inFd: int(os.Stdin.Fd()),
|
|
outFd: int(os.Stdout.Fd()),
|
|
}
|
|
}
|
|
|
|
// Init draws on the controlling terminal in place of a redirected stdin or
|
|
// stdout, so `app > file` and `cmd | app` keep both as data
|
|
func (b *unixBackend) Init() error {
|
|
if os.Getenv("TERM") == "dumb" {
|
|
return errors.New("TERM=dumb cannot address the cursor")
|
|
}
|
|
if !term.IsTerminal(b.inFd) || !term.IsTerminal(b.outFd) {
|
|
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
|
if err != nil {
|
|
return fmt.Errorf("no terminal: %w", err)
|
|
}
|
|
b.tty = tty
|
|
if !term.IsTerminal(b.inFd) {
|
|
b.in, b.inFd = tty, int(tty.Fd())
|
|
}
|
|
if !term.IsTerminal(b.outFd) {
|
|
b.out, b.outFd = tty, int(tty.Fd())
|
|
}
|
|
}
|
|
|
|
old, err := term.MakeRaw(b.inFd)
|
|
if err != nil {
|
|
b.closeTTY()
|
|
return err
|
|
}
|
|
b.oldTerm = old
|
|
return nil
|
|
}
|
|
|
|
// closeTTY closes the controlling terminal Init opened, if any
|
|
func (b *unixBackend) closeTTY() {
|
|
if b.tty != nil {
|
|
b.tty.Close()
|
|
b.tty = nil
|
|
}
|
|
}
|
|
|
|
func (b *unixBackend) Fini() {
|
|
if b.resizeStopCh != nil {
|
|
close(b.resizeStopCh)
|
|
<-b.resizeDoneCh
|
|
b.resizeStopCh = nil
|
|
}
|
|
if b.oldTerm != nil {
|
|
term.Restore(b.inFd, b.oldTerm)
|
|
}
|
|
b.closeTTY()
|
|
}
|
|
|
|
// Size delegates to exported WindowSize; getTerminalSize deleted
|
|
func (b *unixBackend) Size() (int, int) {
|
|
if w, h, ok := WindowSize(b.out); ok {
|
|
return w, h
|
|
}
|
|
return 80, 24 // Fallback
|
|
}
|
|
|
|
// WindowSize queries terminal dimensions for f without raw mode or
|
|
// Terminal lifecycle. ok=false when f is not a terminal.
|
|
func WindowSize(f *os.File) (w, h int, ok bool) {
|
|
ws, err := unix.IoctlGetWinsize(int(f.Fd()), unix.TIOCGWINSZ)
|
|
if err != nil || ws.Col == 0 {
|
|
return 0, 0, false
|
|
}
|
|
return int(ws.Col), int(ws.Row), true
|
|
}
|
|
|
|
func (b *unixBackend) Write(p []byte) error {
|
|
_, err := b.out.Write(p)
|
|
return err
|
|
}
|
|
|
|
// Read implements the polling logic previously in input.go
|
|
func (b *unixBackend) Read(stopCh <-chan struct{}) ([]byte, error) {
|
|
// Buffer for single read
|
|
buf := make([]byte, 256)
|
|
|
|
for {
|
|
select {
|
|
case <-stopCh:
|
|
return nil, nil
|
|
default:
|
|
}
|
|
|
|
// Poll with timeout to allow checking stopCh
|
|
fds := []unix.PollFd{
|
|
{Fd: int32(b.inFd), Events: unix.POLLIN},
|
|
}
|
|
|
|
// Timeout to differentiate standalone ESC from escape sequences
|
|
n, err := unix.Poll(fds, escapeTimeoutMs)
|
|
if err != nil {
|
|
if errors.Is(err, unix.EINTR) {
|
|
continue
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
if n == 0 {
|
|
// Timeout - return empty to let readLoop handle pending ESC
|
|
return nil, nil
|
|
}
|
|
|
|
// Read data
|
|
rn, err := unix.Read(b.inFd, buf)
|
|
if err != nil {
|
|
if errors.Is(err, unix.EINTR) || errors.Is(err, unix.EAGAIN) {
|
|
continue
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
if rn == 0 {
|
|
// EOF
|
|
return nil, nil
|
|
}
|
|
|
|
// Return copy of data
|
|
ret := make([]byte, rn)
|
|
copy(ret, buf[:rn])
|
|
return ret, nil
|
|
}
|
|
}
|
|
|
|
// keySources: the key protocol, which the terminal is asked about
|
|
func (b *unixBackend) keySources() KeySource { return KeySourceProtocol }
|
|
|
|
func (b *unixBackend) SetResizeHandler(handler func(width, height int)) {
|
|
b.resizeStopCh = make(chan struct{})
|
|
b.resizeDoneCh = make(chan struct{})
|
|
|
|
go func() {
|
|
defer close(b.resizeDoneCh)
|
|
sigCh := make(chan os.Signal, 1)
|
|
signal.Notify(sigCh, syscall.SIGWINCH)
|
|
defer signal.Stop(sigCh)
|
|
|
|
for {
|
|
select {
|
|
case <-b.resizeStopCh:
|
|
return
|
|
case <-sigCh:
|
|
w, h := b.Size()
|
|
handler(w, h)
|
|
}
|
|
}
|
|
}()
|
|
}
|