term_windows.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package term
  5. import (
  6. "os"
  7. "golang.org/x/sys/windows"
  8. )
  9. type state struct {
  10. mode uint32
  11. }
  12. func isTerminal(fd int) bool {
  13. var st uint32
  14. err := windows.GetConsoleMode(windows.Handle(fd), &st)
  15. return err == nil
  16. }
  17. func makeRaw(fd int) (*State, error) {
  18. var st uint32
  19. if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
  20. return nil, err
  21. }
  22. raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
  23. if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
  24. return nil, err
  25. }
  26. return &State{state{st}}, nil
  27. }
  28. func getState(fd int) (*State, error) {
  29. var st uint32
  30. if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
  31. return nil, err
  32. }
  33. return &State{state{st}}, nil
  34. }
  35. func restore(fd int, state *State) error {
  36. return windows.SetConsoleMode(windows.Handle(fd), state.mode)
  37. }
  38. func getSize(fd int) (width, height int, err error) {
  39. var info windows.ConsoleScreenBufferInfo
  40. if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil {
  41. return 0, 0, err
  42. }
  43. return int(info.Window.Right - info.Window.Left + 1), int(info.Window.Bottom - info.Window.Top + 1), nil
  44. }
  45. func readPassword(fd int) ([]byte, error) {
  46. var st uint32
  47. if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
  48. return nil, err
  49. }
  50. old := st
  51. st &^= (windows.ENABLE_ECHO_INPUT | windows.ENABLE_LINE_INPUT)
  52. st |= (windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_PROCESSED_INPUT)
  53. if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil {
  54. return nil, err
  55. }
  56. defer windows.SetConsoleMode(windows.Handle(fd), old)
  57. var h windows.Handle
  58. p, _ := windows.GetCurrentProcess()
  59. if err := windows.DuplicateHandle(p, windows.Handle(fd), p, &h, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil {
  60. return nil, err
  61. }
  62. f := os.NewFile(uintptr(h), "stdin")
  63. defer f.Close()
  64. return readPasswordLine(f)
  65. }