1 // Copyright 2011 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.
7 // Package terminal provides support functions for dealing with terminals, as
8 // commonly found on UNIX systems.
10 // Putting a terminal into raw mode is the most common requirement:
12 // oldState, err := terminal.MakeRaw(0)
16 // defer terminal.Restore(0, oldState)
22 "golang.org/x/sys/windows"
29 // IsTerminal returns whether the given file descriptor is a terminal.
30 func IsTerminal(fd int) bool {
32 err := windows.GetConsoleMode(windows.Handle(fd), &st)
36 // MakeRaw put the terminal connected to the given file descriptor into raw
37 // mode and returns the previous state of the terminal so that it can be
39 func MakeRaw(fd int) (*State, error) {
41 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
44 raw := st &^ (windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
45 if err := windows.SetConsoleMode(windows.Handle(fd), raw); err != nil {
48 return &State{st}, nil
51 // GetState returns the current state of a terminal which may be useful to
52 // restore the terminal after a signal.
53 func GetState(fd int) (*State, error) {
55 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
58 return &State{st}, nil
61 // Restore restores the terminal connected to the given file descriptor to a
63 func Restore(fd int, state *State) error {
64 return windows.SetConsoleMode(windows.Handle(fd), state.mode)
67 // GetSize returns the visible dimensions of the given terminal.
69 // These dimensions don't include any scrollback buffer height.
70 func GetSize(fd int) (width, height int, err error) {
71 var info windows.ConsoleScreenBufferInfo
72 if err := windows.GetConsoleScreenBufferInfo(windows.Handle(fd), &info); err != nil {
75 return int(info.Window.Right - info.Window.Left + 1), int(info.Window.Bottom - info.Window.Top + 1), nil
78 // ReadPassword reads a line of input from a terminal without local echo. This
79 // is commonly used for inputting passwords and other sensitive data. The slice
80 // returned does not include the \n.
81 func ReadPassword(fd int) ([]byte, error) {
83 if err := windows.GetConsoleMode(windows.Handle(fd), &st); err != nil {
88 st &^= (windows.ENABLE_ECHO_INPUT)
89 st |= (windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT)
90 if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil {
94 defer windows.SetConsoleMode(windows.Handle(fd), old)
97 p, _ := windows.GetCurrentProcess()
98 if err := windows.DuplicateHandle(p, windows.Handle(fd), p, &h, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil {
102 f := os.NewFile(uintptr(h), "stdin")
104 return readPasswordLine(f)