term_windows.go 1.07 KB
Newer Older
1
2
3
package readline

import (
4
	"golang.org/x/sys/windows"
5
6
7
8
9
10
11
)

type State struct {
	mode uint32
}

// IsTerminal checks if the given file descriptor is associated with a terminal
Michael Yang's avatar
Michael Yang committed
12
func IsTerminal(fd uintptr) bool {
13
	var st uint32
14
15
	err := windows.GetConsoleMode(windows.Handle(fd), &st)
	return err == nil
16
17
}

Michael Yang's avatar
Michael Yang committed
18
func SetRawMode(fd uintptr) (*State, error) {
19
	var st uint32
20
21
	if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
		return nil, err
22
	}
23
24
25
26
27
28
29
30

	// 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
31
32
33
34
	}
	return &State{st}, nil
}

Michael Yang's avatar
Michael Yang committed
35
func UnsetRawMode(fd uintptr, state any) error {
36
	s := state.(*State)
37
	return windows.SetConsoleMode(windows.Handle(fd), s.mode)
38
}