ansi_reader.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // +build windows
  2. package windowsconsole
  3. import (
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strings"
  10. "unsafe"
  11. ansiterm "github.com/Azure/go-ansiterm"
  12. "github.com/Azure/go-ansiterm/winterm"
  13. )
  14. const (
  15. escapeSequence = ansiterm.KEY_ESC_CSI
  16. )
  17. // ansiReader wraps a standard input file (e.g., os.Stdin) providing ANSI sequence translation.
  18. type ansiReader struct {
  19. file *os.File
  20. fd uintptr
  21. buffer []byte
  22. cbBuffer int
  23. command []byte
  24. }
  25. // NewAnsiReader returns an io.ReadCloser that provides VT100 terminal emulation on top of a
  26. // Windows console input handle.
  27. func NewAnsiReader(nFile int) io.ReadCloser {
  28. initLogger()
  29. file, fd := winterm.GetStdFile(nFile)
  30. return &ansiReader{
  31. file: file,
  32. fd: fd,
  33. command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH),
  34. buffer: make([]byte, 0),
  35. }
  36. }
  37. // Close closes the wrapped file.
  38. func (ar *ansiReader) Close() (err error) {
  39. return ar.file.Close()
  40. }
  41. // Fd returns the file descriptor of the wrapped file.
  42. func (ar *ansiReader) Fd() uintptr {
  43. return ar.fd
  44. }
  45. // Read reads up to len(p) bytes of translated input events into p.
  46. func (ar *ansiReader) Read(p []byte) (int, error) {
  47. if len(p) == 0 {
  48. return 0, nil
  49. }
  50. // Previously read bytes exist, read as much as we can and return
  51. if len(ar.buffer) > 0 {
  52. logger.Debugf("Reading previously cached bytes")
  53. originalLength := len(ar.buffer)
  54. copiedLength := copy(p, ar.buffer)
  55. if copiedLength == originalLength {
  56. ar.buffer = make([]byte, 0, len(p))
  57. } else {
  58. ar.buffer = ar.buffer[copiedLength:]
  59. }
  60. logger.Debugf("Read from cache p[%d]: % x", copiedLength, p)
  61. return copiedLength, nil
  62. }
  63. // Read and translate key events
  64. events, err := readInputEvents(ar.fd, len(p))
  65. if err != nil {
  66. return 0, err
  67. } else if len(events) == 0 {
  68. logger.Debug("No input events detected")
  69. return 0, nil
  70. }
  71. keyBytes := translateKeyEvents(events, []byte(escapeSequence))
  72. // Save excess bytes and right-size keyBytes
  73. if len(keyBytes) > len(p) {
  74. logger.Debugf("Received %d keyBytes, only room for %d bytes", len(keyBytes), len(p))
  75. ar.buffer = keyBytes[len(p):]
  76. keyBytes = keyBytes[:len(p)]
  77. } else if len(keyBytes) == 0 {
  78. logger.Debug("No key bytes returned from the translator")
  79. return 0, nil
  80. }
  81. copiedLength := copy(p, keyBytes)
  82. if copiedLength != len(keyBytes) {
  83. return 0, errors.New("unexpected copy length encountered")
  84. }
  85. logger.Debugf("Read p[%d]: % x", copiedLength, p)
  86. logger.Debugf("Read keyBytes[%d]: % x", copiedLength, keyBytes)
  87. return copiedLength, nil
  88. }
  89. // readInputEvents polls until at least one event is available.
  90. func readInputEvents(fd uintptr, maxBytes int) ([]winterm.INPUT_RECORD, error) {
  91. // Determine the maximum number of records to retrieve
  92. // -- Cast around the type system to obtain the size of a single INPUT_RECORD.
  93. // unsafe.Sizeof requires an expression vs. a type-reference; the casting
  94. // tricks the type system into believing it has such an expression.
  95. recordSize := int(unsafe.Sizeof(*((*winterm.INPUT_RECORD)(unsafe.Pointer(&maxBytes)))))
  96. countRecords := maxBytes / recordSize
  97. if countRecords > ansiterm.MAX_INPUT_EVENTS {
  98. countRecords = ansiterm.MAX_INPUT_EVENTS
  99. } else if countRecords == 0 {
  100. countRecords = 1
  101. }
  102. logger.Debugf("[windows] readInputEvents: Reading %v records (buffer size %v, record size %v)", countRecords, maxBytes, recordSize)
  103. // Wait for and read input events
  104. events := make([]winterm.INPUT_RECORD, countRecords)
  105. nEvents := uint32(0)
  106. eventsExist, err := winterm.WaitForSingleObject(fd, winterm.WAIT_INFINITE)
  107. if err != nil {
  108. return nil, err
  109. }
  110. if eventsExist {
  111. err = winterm.ReadConsoleInput(fd, events, &nEvents)
  112. if err != nil {
  113. return nil, err
  114. }
  115. }
  116. // Return a slice restricted to the number of returned records
  117. logger.Debugf("[windows] readInputEvents: Read %v events", nEvents)
  118. return events[:nEvents], nil
  119. }
  120. // KeyEvent Translation Helpers
  121. var arrowKeyMapPrefix = map[uint16]string{
  122. winterm.VK_UP: "%s%sA",
  123. winterm.VK_DOWN: "%s%sB",
  124. winterm.VK_RIGHT: "%s%sC",
  125. winterm.VK_LEFT: "%s%sD",
  126. }
  127. var keyMapPrefix = map[uint16]string{
  128. winterm.VK_UP: "\x1B[%sA",
  129. winterm.VK_DOWN: "\x1B[%sB",
  130. winterm.VK_RIGHT: "\x1B[%sC",
  131. winterm.VK_LEFT: "\x1B[%sD",
  132. winterm.VK_HOME: "\x1B[1%s~", // showkey shows ^[[1
  133. winterm.VK_END: "\x1B[4%s~", // showkey shows ^[[4
  134. winterm.VK_INSERT: "\x1B[2%s~",
  135. winterm.VK_DELETE: "\x1B[3%s~",
  136. winterm.VK_PRIOR: "\x1B[5%s~",
  137. winterm.VK_NEXT: "\x1B[6%s~",
  138. winterm.VK_F1: "",
  139. winterm.VK_F2: "",
  140. winterm.VK_F3: "\x1B[13%s~",
  141. winterm.VK_F4: "\x1B[14%s~",
  142. winterm.VK_F5: "\x1B[15%s~",
  143. winterm.VK_F6: "\x1B[17%s~",
  144. winterm.VK_F7: "\x1B[18%s~",
  145. winterm.VK_F8: "\x1B[19%s~",
  146. winterm.VK_F9: "\x1B[20%s~",
  147. winterm.VK_F10: "\x1B[21%s~",
  148. winterm.VK_F11: "\x1B[23%s~",
  149. winterm.VK_F12: "\x1B[24%s~",
  150. }
  151. // translateKeyEvents converts the input events into the appropriate ANSI string.
  152. func translateKeyEvents(events []winterm.INPUT_RECORD, escapeSequence []byte) []byte {
  153. var buffer bytes.Buffer
  154. for _, event := range events {
  155. if event.EventType == winterm.KEY_EVENT && event.KeyEvent.KeyDown != 0 {
  156. buffer.WriteString(keyToString(&event.KeyEvent, escapeSequence))
  157. }
  158. }
  159. return buffer.Bytes()
  160. }
  161. // keyToString maps the given input event record to the corresponding string.
  162. func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) string {
  163. if keyEvent.UnicodeChar == 0 {
  164. return formatVirtualKey(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence)
  165. }
  166. _, alt, control := getControlKeys(keyEvent.ControlKeyState)
  167. if control {
  168. // TODO(azlinux): Implement following control sequences
  169. // <Ctrl>-D Signals the end of input from the keyboard; also exits current shell.
  170. // <Ctrl>-H Deletes the first character to the left of the cursor. Also called the ERASE key.
  171. // <Ctrl>-Q Restarts printing after it has been stopped with <Ctrl>-s.
  172. // <Ctrl>-S Suspends printing on the screen (does not stop the program).
  173. // <Ctrl>-U Deletes all characters on the current line. Also called the KILL key.
  174. // <Ctrl>-E Quits current command and creates a core
  175. }
  176. // <Alt>+Key generates ESC N Key
  177. if !control && alt {
  178. return ansiterm.KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar))
  179. }
  180. return string(keyEvent.UnicodeChar)
  181. }
  182. // formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string.
  183. func formatVirtualKey(key uint16, controlState uint32, escapeSequence []byte) string {
  184. shift, alt, control := getControlKeys(controlState)
  185. modifier := getControlKeysModifier(shift, alt, control)
  186. if format, ok := arrowKeyMapPrefix[key]; ok {
  187. return fmt.Sprintf(format, escapeSequence, modifier)
  188. }
  189. if format, ok := keyMapPrefix[key]; ok {
  190. return fmt.Sprintf(format, modifier)
  191. }
  192. return ""
  193. }
  194. // getControlKeys extracts the shift, alt, and ctrl key states.
  195. func getControlKeys(controlState uint32) (shift, alt, control bool) {
  196. shift = 0 != (controlState & winterm.SHIFT_PRESSED)
  197. alt = 0 != (controlState & (winterm.LEFT_ALT_PRESSED | winterm.RIGHT_ALT_PRESSED))
  198. control = 0 != (controlState & (winterm.LEFT_CTRL_PRESSED | winterm.RIGHT_CTRL_PRESSED))
  199. return shift, alt, control
  200. }
  201. // getControlKeysModifier returns the ANSI modifier for the given combination of control keys.
  202. func getControlKeysModifier(shift, alt, control bool) string {
  203. if shift && alt && control {
  204. return ansiterm.KEY_CONTROL_PARAM_8
  205. }
  206. if alt && control {
  207. return ansiterm.KEY_CONTROL_PARAM_7
  208. }
  209. if shift && control {
  210. return ansiterm.KEY_CONTROL_PARAM_6
  211. }
  212. if control {
  213. return ansiterm.KEY_CONTROL_PARAM_5
  214. }
  215. if shift && alt {
  216. return ansiterm.KEY_CONTROL_PARAM_4
  217. }
  218. if alt {
  219. return ansiterm.KEY_CONTROL_PARAM_3
  220. }
  221. if shift {
  222. return ansiterm.KEY_CONTROL_PARAM_2
  223. }
  224. return ""
  225. }