2023-10-30 20:18:12 +00:00
|
|
|
package readline
|
|
|
|
|
|
|
|
import (
|
2024-03-26 22:21:56 +00:00
|
|
|
"golang.org/x/sys/windows"
|
2023-10-30 20:18:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type State struct {
|
|
|
|
mode uint32
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsTerminal checks if the given file descriptor is associated with a terminal
|
2024-05-22 16:00:38 +00:00
|
|
|
func IsTerminal(fd uintptr) bool {
|
2023-10-30 20:18:12 +00:00
|
|
|
var st uint32
|
2024-03-26 22:21:56 +00:00
|
|
|
err := windows.GetConsoleMode(windows.Handle(fd), &st)
|
|
|
|
return err == nil
|
2023-10-30 20:18:12 +00:00
|
|
|
}
|
|
|
|
|
2024-05-22 16:00:38 +00:00
|
|
|
func SetRawMode(fd uintptr) (*State, error) {
|
2023-10-30 20:18:12 +00:00
|
|
|
var st uint32
|
2024-03-26 22:21:56 +00:00
|
|
|
if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
|
|
|
|
return nil, err
|
2023-10-30 20:18:12 +00:00
|
|
|
}
|
2024-03-26 22:21:56 +00:00
|
|
|
|
|
|
|
// this enables raw mode by turning off various flags in the console mode: https://pkg.go.dev/golang.org/x/sys/windows#pkg-constants
|
|
|
|
raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
|
|
|
|
|
|
|
|
// turn on ENABLE_VIRTUAL_TERMINAL_INPUT to enable escape sequences
|
|
|
|
raw |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT
|
|
|
|
if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
|
|
|
|
return nil, err
|
2023-10-30 20:18:12 +00:00
|
|
|
}
|
|
|
|
return &State{st}, nil
|
|
|
|
}
|
|
|
|
|
2024-05-22 16:00:38 +00:00
|
|
|
func UnsetRawMode(fd uintptr, state any) error {
|
2024-02-15 05:28:35 +00:00
|
|
|
s := state.(*State)
|
2024-03-26 22:21:56 +00:00
|
|
|
return windows.SetConsoleMode(windows.Handle(fd), s.mode)
|
2023-10-30 20:18:12 +00:00
|
|
|
}
|