term_windows.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package readline
  2. import (
  3. "golang.org/x/sys/windows"
  4. )
  5. type State struct {
  6. mode uint32
  7. }
  8. // IsTerminal checks if the given file descriptor is associated with a terminal
  9. func IsTerminal(fd uintptr) bool {
  10. var st uint32
  11. err := windows.GetConsoleMode(windows.Handle(fd), &st)
  12. return err == nil
  13. }
  14. func SetRawMode(fd uintptr) (*State, error) {
  15. var st uint32
  16. if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
  17. return nil, err
  18. }
  19. // this enables raw mode by turning off various flags in the console mode: https://pkg.go.dev/golang.org/x/sys/windows#pkg-constants
  20. raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
  21. // turn on ENABLE_VIRTUAL_TERMINAL_INPUT to enable escape sequences
  22. raw |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT
  23. if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
  24. return nil, err
  25. }
  26. return &State{st}, nil
  27. }
  28. func UnsetRawMode(fd uintptr, state any) error {
  29. s := state.(*State)
  30. return windows.SetConsoleMode(windows.Handle(fd), s.mode)
  31. }