summaryrefslogtreecommitdiff
path: root/internal/tui/keys.go
blob: e88a3261b15a2e4489c0456ce93363bc63cfc496 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// SPDX-License-Identifier: GPL-3.0-or-later

package tui

import (
	"fmt"
	"os"

	"golang.org/x/term"
)

// ReadKey reads one keypress without Enter, restoring the terminal before
// it returns - on every path, including an error. It always reads a
// single byte; only a terminal is first put into raw mode, so a
// non-terminal (a pipe, in tests) needs no pty to exercise it.
func ReadKey(in *os.File) (rune, error) {
	fd := int(in.Fd())
	if !isTerminal(fd) {
		return readByte(in)
	}

	state, err := term.MakeRaw(fd)
	if err != nil {
		return 0, fmt.Errorf("tui: %w", err)
	}
	defer term.Restore(fd, state)

	return readByte(in)
}

func readByte(in *os.File) (rune, error) {
	var b [1]byte
	if _, err := in.Read(b[:]); err != nil {
		return 0, err
	}
	return rune(b[0]), nil
}