Files
rgoue/term/tcell.go
clawbot 0dc4c70f18 fix: take the signal-time autosave on the game goroutine (closes #24)
The SIGHUP/SIGTERM handler gob-encoded the live game tree from the signal
goroutine while the game goroutine was mid-turn mutating it, and AutoSave
removed the save file before encoding — so the failure mode was not a
stale save but a deleted one followed by a possibly torn replacement,
with a window in which the player had neither. The suite has run under
-race since 2026-08-09 and was green because nothing had ever driven the
turn loop concurrently with a signal: evidence of untested, not of safe.

The handler no longer writes anything. AutoSaveOnSignal posts a request,
wakes the input read, and waits up to signalSaveTimeout for the game
goroutine to take it; the encode runs on the goroutine that owns the
state, at the three points where that goroutine can sit: between turns
(command), on waking from a blocked readchar, and while parked in the `!`
shell escape (runShellEscape, which now runs the shell on a helper
goroutine so a hangup during it still rescues the game).

Blocked on input is the case that matters — a dropped connection lands
while the player is thinking, so a flag checked only between turns would
never be looked at. Terminal.ReadChar therefore returns (byte, bool),
with ok false meaning "woken by Interrupt, no key", and term.Tcell posts
a tcell.EventInterrupt onto tcell's own event queue to unpark PollEvent.
readchar services the request and reads again, so no caller sees it.

Running the shell on a helper goroutine would also have moved
term.Tcell.ShellEscape's panic on a failed Screen.Resume onto it, and a
panic at the top of any goroutine terminates the process without running
the deferred calls of the others — including cmd/rogue/main.go's
`defer t.Fini()`. The tty would have been left raw on precisely the path
where the terminal is already broken, which is issue #12's failure on a
path this change created. runShellEscape therefore recovers the helper's
panic and re-raises it on the game goroutine, whose stack has the restore
in it, so "every path restores the terminal via Terminal.Fini before
exiting" stays true.

saveFile writes a temporary file in the save's own directory, fsyncs it
and renames it over the target instead of truncating in place, so a save
that fails — or never happens because the deadline ran out — leaves the
player's previous save whole.

What the handoff guarantees is stated exactly rather than flatteringly:
the encode runs on the state-owning goroutine, so the snapshot is
internally consistent and restorable, but it is not necessarily taken
between commands. readchar is reached from mid-command prompts (--More--,
askOverwrite, getStr, the direction and pack prompts) and the command has
already mutated state by then, so a save taken there freezes that command
half applied and restoring loses the rest of it.

The SIGINT/SIGQUIT no-save decision and the single-signal-read ordering
guarantee are untouched. pendingSaver reads the game out from under its
mutex rather than delegating with it held, because the delegated call now
blocks until the save is taken.
2026-08-09 07:07:23 +00:00

224 lines
5.5 KiB
Go

// Package term provides the tcell-backed Terminal for the Rogue port. It
// replaces curses and the 900-line escape-sequence decoder in mdport.c:
// tcell delivers decoded key events, which are translated here to the
// single-byte command codes the game understands.
package term
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"github.com/gdamore/tcell/v2"
"git.eeqj.de/sneak/rgoue/game"
)
// Tcell renders game Windows on a tcell screen and turns key events into
// Rogue input bytes.
type Tcell struct {
screen tcell.Screen
last *game.Window // last rendered window, for resize redraws
}
// ErrScreenTooSmall reports a terminal below the required 80x24.
var ErrScreenTooSmall = errors.New("screen too small")
// New initializes the terminal. The screen must be at least 80x24, as the
// C game required.
func New() (*Tcell, error) {
s, err := tcell.NewScreen()
if err != nil {
return nil, err
}
initErr := s.Init()
if initErr != nil {
return nil, initErr
}
w, h := s.Size()
if h < game.NumLines || w < game.NumCols {
s.Fini()
return nil, fmt.Errorf("sorry, %w: %dx%d required",
ErrScreenTooSmall, game.NumCols, game.NumLines)
}
s.HideCursor()
return &Tcell{screen: s}, nil
}
// Fini restores the terminal.
func (t *Tcell) Fini() {
t.screen.Fini()
}
// Render blits a game window to the terminal (curses refresh).
func (t *Tcell) Render(w *game.Window) {
t.last = w
rows, cols := w.Size()
for y := range rows {
for x := range cols {
ch, standout := w.CellAt(y, x)
style := tcell.StyleDefault
if standout {
style = style.Reverse(true)
}
t.screen.SetContent(x, y, rune(ch), nil, style)
}
}
t.screen.Show()
}
// ReadChar blocks for the next key, translated to the byte codes the C
// game reads: arrows become hjkl, control keys their C0 codes. ok is
// false when Interrupt woke the read instead of a key arriving.
func (t *Tcell) ReadChar() (byte, bool) {
for {
ev := t.screen.PollEvent()
switch ev := ev.(type) {
case *tcell.EventResize:
if t.last != nil {
t.Render(t.last)
}
case *tcell.EventInterrupt:
// Interrupt posted this from the signal goroutine: hand
// control back so the game goroutine can service a pending
// autosave, then it reads again.
return 0, false
case *tcell.EventKey:
if b, ok := translateKey(ev); ok {
return b, true
}
}
}
}
// Interrupt wakes a ReadChar parked in PollEvent by posting an interrupt
// event onto tcell's own event queue — the mechanism tcell provides for
// exactly this, and the only Tcell method called from another goroutine
// (Screen.PostEvent is a channel send, safe to call concurrently).
//
// Best effort by design: PostEvent fails only when the event queue is
// full, which means the game goroutine is not parked waiting for a key,
// and a game goroutine that is running turns reaches the between-turns
// check on its own.
func (t *Tcell) Interrupt() {
_ = t.screen.PostEvent(tcell.NewEventInterrupt(nil))
}
// translateKey converts a key event to a game input byte; ok is false
// for keys the C game does not understand.
func translateKey(ev *tcell.EventKey) (byte, bool) {
if b, ok := namedKey(ev.Key()); ok {
return b, true
}
if ev.Key() >= tcell.KeyCtrlA && ev.Key() <= tcell.KeyCtrlZ {
return byte(ev.Key()), true //nolint:gosec // G115: 1..26 fits
}
if r := ev.Rune(); r > 0 && r < 0x80 {
return byte(r), true
}
return 0, false
}
// namedKey translates tcell's navigation and editing keys to the single
// bytes the C game reads (arrows become hjkl, etc.); ok is false for
// keys handled elsewhere.
func namedKey(k tcell.Key) (byte, bool) {
if b, ok := motionKey(k); ok {
return b, true
}
return editingKey(k)
}
// motionKey translates the arrow and paging keys to Rogue's movement
// letters (tcell.go ReadChar).
func motionKey(k tcell.Key) (byte, bool) {
//nolint:exhaustive // translation table: all other keys fall through
switch k {
case tcell.KeyUp:
return 'k', true
case tcell.KeyDown:
return 'j', true
case tcell.KeyLeft:
return 'h', true
case tcell.KeyRight:
return 'l', true
case tcell.KeyHome:
return 'y', true
case tcell.KeyPgUp:
return 'u', true
case tcell.KeyEnd:
return 'b', true
case tcell.KeyPgDn:
return 'n', true
}
return 0, false
}
// editingKey translates the editing and control keys to their C0 codes
// (tcell.go ReadChar).
func editingKey(k tcell.Key) (byte, bool) {
//nolint:exhaustive // translation table: all other keys fall through
switch k {
case tcell.KeyEnter:
return '\n', true
case tcell.KeyEscape:
return game.Escape, true
case tcell.KeyBackspace, tcell.KeyBackspace2:
return '\b', true
case tcell.KeyDelete:
return '\x7f', true
case tcell.KeyTab:
return '\t', true
case tcell.KeyCtrlC:
return '\x03', true
}
return 0, false
}
// ShellEscape suspends the screen and runs the user's shell (main.c
// shell + md_shellescape).
func (t *Tcell) ShellEscape() {
err := t.screen.Suspend()
if err != nil {
return
}
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
_, _ = fmt.Fprintln(os.Stdout,
"[Entering shell; exit to return to the game]")
// The shell session has no deadline by design; Background context.
//nolint:gosec // G204: the user's own $SHELL
cmd := exec.CommandContext(context.Background(), shell)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run() // best effort: the shell is the user's business
resumeErr := t.screen.Resume()
if resumeErr != nil {
panic(resumeErr) // terminal resume failure is unrecoverable
}
}