terminal.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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.
  4. package terminal
  5. import (
  6. "io"
  7. "sync"
  8. )
  9. // EscapeCodes contains escape sequences that can be written to the terminal in
  10. // order to achieve different styles of text.
  11. type EscapeCodes struct {
  12. // Foreground colors
  13. Black, Red, Green, Yellow, Blue, Magenta, Cyan, White []byte
  14. // Reset all attributes
  15. Reset []byte
  16. }
  17. var vt100EscapeCodes = EscapeCodes{
  18. Black: []byte{keyEscape, '[', '3', '0', 'm'},
  19. Red: []byte{keyEscape, '[', '3', '1', 'm'},
  20. Green: []byte{keyEscape, '[', '3', '2', 'm'},
  21. Yellow: []byte{keyEscape, '[', '3', '3', 'm'},
  22. Blue: []byte{keyEscape, '[', '3', '4', 'm'},
  23. Magenta: []byte{keyEscape, '[', '3', '5', 'm'},
  24. Cyan: []byte{keyEscape, '[', '3', '6', 'm'},
  25. White: []byte{keyEscape, '[', '3', '7', 'm'},
  26. Reset: []byte{keyEscape, '[', '0', 'm'},
  27. }
  28. // Terminal contains the state for running a VT100 terminal that is capable of
  29. // reading lines of input.
  30. type Terminal struct {
  31. // AutoCompleteCallback, if non-null, is called for each keypress
  32. // with the full input line and the current position of the cursor.
  33. // If it returns a nil newLine, the key press is processed normally.
  34. // Otherwise it returns a replacement line and the new cursor position.
  35. AutoCompleteCallback func(line []byte, pos, key int) (newLine []byte, newPos int)
  36. // Escape contains a pointer to the escape codes for this terminal.
  37. // It's always a valid pointer, although the escape codes themselves
  38. // may be empty if the terminal doesn't support them.
  39. Escape *EscapeCodes
  40. // lock protects the terminal and the state in this object from
  41. // concurrent processing of a key press and a Write() call.
  42. lock sync.Mutex
  43. c io.ReadWriter
  44. prompt string
  45. // line is the current line being entered.
  46. line []byte
  47. // pos is the logical position of the cursor in line
  48. pos int
  49. // echo is true if local echo is enabled
  50. echo bool
  51. // cursorX contains the current X value of the cursor where the left
  52. // edge is 0. cursorY contains the row number where the first row of
  53. // the current line is 0.
  54. cursorX, cursorY int
  55. // maxLine is the greatest value of cursorY so far.
  56. maxLine int
  57. termWidth, termHeight int
  58. // outBuf contains the terminal data to be sent.
  59. outBuf []byte
  60. // remainder contains the remainder of any partial key sequences after
  61. // a read. It aliases into inBuf.
  62. remainder []byte
  63. inBuf [256]byte
  64. // history contains previously entered commands so that they can be
  65. // accessed with the up and down keys.
  66. history stRingBuffer
  67. // historyIndex stores the currently accessed history entry, where zero
  68. // means the immediately previous entry.
  69. historyIndex int
  70. // When navigating up and down the history it's possible to return to
  71. // the incomplete, initial line. That value is stored in
  72. // historyPending.
  73. historyPending string
  74. }
  75. // NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
  76. // a local terminal, that terminal must first have been put into raw mode.
  77. // prompt is a string that is written at the start of each input line (i.e.
  78. // "> ").
  79. func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
  80. return &Terminal{
  81. Escape: &vt100EscapeCodes,
  82. c: c,
  83. prompt: prompt,
  84. termWidth: 80,
  85. termHeight: 24,
  86. echo: true,
  87. historyIndex: -1,
  88. }
  89. }
  90. const (
  91. keyCtrlD = 4
  92. keyEnter = '\r'
  93. keyEscape = 27
  94. keyBackspace = 127
  95. keyUnknown = 256 + iota
  96. keyUp
  97. keyDown
  98. keyLeft
  99. keyRight
  100. keyAltLeft
  101. keyAltRight
  102. keyHome
  103. keyEnd
  104. )
  105. // bytesToKey tries to parse a key sequence from b. If successful, it returns
  106. // the key and the remainder of the input. Otherwise it returns -1.
  107. func bytesToKey(b []byte) (int, []byte) {
  108. if len(b) == 0 {
  109. return -1, nil
  110. }
  111. if b[0] != keyEscape {
  112. return int(b[0]), b[1:]
  113. }
  114. if len(b) >= 3 && b[0] == keyEscape && b[1] == '[' {
  115. switch b[2] {
  116. case 'A':
  117. return keyUp, b[3:]
  118. case 'B':
  119. return keyDown, b[3:]
  120. case 'C':
  121. return keyRight, b[3:]
  122. case 'D':
  123. return keyLeft, b[3:]
  124. }
  125. }
  126. if len(b) >= 3 && b[0] == keyEscape && b[1] == 'O' {
  127. switch b[2] {
  128. case 'H':
  129. return keyHome, b[3:]
  130. case 'F':
  131. return keyEnd, b[3:]
  132. }
  133. }
  134. if len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' {
  135. switch b[5] {
  136. case 'C':
  137. return keyAltRight, b[6:]
  138. case 'D':
  139. return keyAltLeft, b[6:]
  140. }
  141. }
  142. // If we get here then we have a key that we don't recognise, or a
  143. // partial sequence. It's not clear how one should find the end of a
  144. // sequence without knowing them all, but it seems that [a-zA-Z] only
  145. // appears at the end of a sequence.
  146. for i, c := range b[0:] {
  147. if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
  148. return keyUnknown, b[i+1:]
  149. }
  150. }
  151. return -1, b
  152. }
  153. // queue appends data to the end of t.outBuf
  154. func (t *Terminal) queue(data []byte) {
  155. t.outBuf = append(t.outBuf, data...)
  156. }
  157. var eraseUnderCursor = []byte{' ', keyEscape, '[', 'D'}
  158. var space = []byte{' '}
  159. func isPrintable(key int) bool {
  160. return key >= 32 && key < 127
  161. }
  162. // moveCursorToPos appends data to t.outBuf which will move the cursor to the
  163. // given, logical position in the text.
  164. func (t *Terminal) moveCursorToPos(pos int) {
  165. if !t.echo {
  166. return
  167. }
  168. x := len(t.prompt) + pos
  169. y := x / t.termWidth
  170. x = x % t.termWidth
  171. up := 0
  172. if y < t.cursorY {
  173. up = t.cursorY - y
  174. }
  175. down := 0
  176. if y > t.cursorY {
  177. down = y - t.cursorY
  178. }
  179. left := 0
  180. if x < t.cursorX {
  181. left = t.cursorX - x
  182. }
  183. right := 0
  184. if x > t.cursorX {
  185. right = x - t.cursorX
  186. }
  187. t.cursorX = x
  188. t.cursorY = y
  189. t.move(up, down, left, right)
  190. }
  191. func (t *Terminal) move(up, down, left, right int) {
  192. movement := make([]byte, 3*(up+down+left+right))
  193. m := movement
  194. for i := 0; i < up; i++ {
  195. m[0] = keyEscape
  196. m[1] = '['
  197. m[2] = 'A'
  198. m = m[3:]
  199. }
  200. for i := 0; i < down; i++ {
  201. m[0] = keyEscape
  202. m[1] = '['
  203. m[2] = 'B'
  204. m = m[3:]
  205. }
  206. for i := 0; i < left; i++ {
  207. m[0] = keyEscape
  208. m[1] = '['
  209. m[2] = 'D'
  210. m = m[3:]
  211. }
  212. for i := 0; i < right; i++ {
  213. m[0] = keyEscape
  214. m[1] = '['
  215. m[2] = 'C'
  216. m = m[3:]
  217. }
  218. t.queue(movement)
  219. }
  220. func (t *Terminal) clearLineToRight() {
  221. op := []byte{keyEscape, '[', 'K'}
  222. t.queue(op)
  223. }
  224. const maxLineLength = 4096
  225. func (t *Terminal) setLine(newLine []byte, newPos int) {
  226. if t.echo {
  227. t.moveCursorToPos(0)
  228. t.writeLine(newLine)
  229. for i := len(newLine); i < len(t.line); i++ {
  230. t.writeLine(space)
  231. }
  232. t.moveCursorToPos(newPos)
  233. }
  234. t.line = newLine
  235. t.pos = newPos
  236. }
  237. // handleKey processes the given key and, optionally, returns a line of text
  238. // that the user has entered.
  239. func (t *Terminal) handleKey(key int) (line string, ok bool) {
  240. switch key {
  241. case keyBackspace:
  242. if t.pos == 0 {
  243. return
  244. }
  245. t.pos--
  246. t.moveCursorToPos(t.pos)
  247. copy(t.line[t.pos:], t.line[1+t.pos:])
  248. t.line = t.line[:len(t.line)-1]
  249. if t.echo {
  250. t.writeLine(t.line[t.pos:])
  251. }
  252. t.queue(eraseUnderCursor)
  253. t.moveCursorToPos(t.pos)
  254. case keyAltLeft:
  255. // move left by a word.
  256. if t.pos == 0 {
  257. return
  258. }
  259. t.pos--
  260. for t.pos > 0 {
  261. if t.line[t.pos] != ' ' {
  262. break
  263. }
  264. t.pos--
  265. }
  266. for t.pos > 0 {
  267. if t.line[t.pos] == ' ' {
  268. t.pos++
  269. break
  270. }
  271. t.pos--
  272. }
  273. t.moveCursorToPos(t.pos)
  274. case keyAltRight:
  275. // move right by a word.
  276. for t.pos < len(t.line) {
  277. if t.line[t.pos] == ' ' {
  278. break
  279. }
  280. t.pos++
  281. }
  282. for t.pos < len(t.line) {
  283. if t.line[t.pos] != ' ' {
  284. break
  285. }
  286. t.pos++
  287. }
  288. t.moveCursorToPos(t.pos)
  289. case keyLeft:
  290. if t.pos == 0 {
  291. return
  292. }
  293. t.pos--
  294. t.moveCursorToPos(t.pos)
  295. case keyRight:
  296. if t.pos == len(t.line) {
  297. return
  298. }
  299. t.pos++
  300. t.moveCursorToPos(t.pos)
  301. case keyHome:
  302. if t.pos == 0 {
  303. return
  304. }
  305. t.pos = 0
  306. t.moveCursorToPos(t.pos)
  307. case keyEnd:
  308. if t.pos == len(t.line) {
  309. return
  310. }
  311. t.pos = len(t.line)
  312. t.moveCursorToPos(t.pos)
  313. case keyUp:
  314. entry, ok := t.history.NthPreviousEntry(t.historyIndex + 1)
  315. if !ok {
  316. return "", false
  317. }
  318. if t.historyIndex == -1 {
  319. t.historyPending = string(t.line)
  320. }
  321. t.historyIndex++
  322. t.setLine([]byte(entry), len(entry))
  323. case keyDown:
  324. switch t.historyIndex {
  325. case -1:
  326. return
  327. case 0:
  328. t.setLine([]byte(t.historyPending), len(t.historyPending))
  329. t.historyIndex--
  330. default:
  331. entry, ok := t.history.NthPreviousEntry(t.historyIndex - 1)
  332. if ok {
  333. t.historyIndex--
  334. t.setLine([]byte(entry), len(entry))
  335. }
  336. }
  337. case keyEnter:
  338. t.moveCursorToPos(len(t.line))
  339. t.queue([]byte("\r\n"))
  340. line = string(t.line)
  341. ok = true
  342. t.line = t.line[:0]
  343. t.pos = 0
  344. t.cursorX = 0
  345. t.cursorY = 0
  346. t.maxLine = 0
  347. default:
  348. if t.AutoCompleteCallback != nil {
  349. t.lock.Unlock()
  350. newLine, newPos := t.AutoCompleteCallback(t.line, t.pos, key)
  351. t.lock.Lock()
  352. if newLine != nil {
  353. t.setLine(newLine, newPos)
  354. return
  355. }
  356. }
  357. if !isPrintable(key) {
  358. return
  359. }
  360. if len(t.line) == maxLineLength {
  361. return
  362. }
  363. if len(t.line) == cap(t.line) {
  364. newLine := make([]byte, len(t.line), 2*(1+len(t.line)))
  365. copy(newLine, t.line)
  366. t.line = newLine
  367. }
  368. t.line = t.line[:len(t.line)+1]
  369. copy(t.line[t.pos+1:], t.line[t.pos:])
  370. t.line[t.pos] = byte(key)
  371. if t.echo {
  372. t.writeLine(t.line[t.pos:])
  373. }
  374. t.pos++
  375. t.moveCursorToPos(t.pos)
  376. }
  377. return
  378. }
  379. func (t *Terminal) writeLine(line []byte) {
  380. for len(line) != 0 {
  381. remainingOnLine := t.termWidth - t.cursorX
  382. todo := len(line)
  383. if todo > remainingOnLine {
  384. todo = remainingOnLine
  385. }
  386. t.queue(line[:todo])
  387. t.cursorX += todo
  388. line = line[todo:]
  389. if t.cursorX == t.termWidth {
  390. t.cursorX = 0
  391. t.cursorY++
  392. if t.cursorY > t.maxLine {
  393. t.maxLine = t.cursorY
  394. }
  395. }
  396. }
  397. }
  398. func (t *Terminal) Write(buf []byte) (n int, err error) {
  399. t.lock.Lock()
  400. defer t.lock.Unlock()
  401. if t.cursorX == 0 && t.cursorY == 0 {
  402. // This is the easy case: there's nothing on the screen that we
  403. // have to move out of the way.
  404. return t.c.Write(buf)
  405. }
  406. // We have a prompt and possibly user input on the screen. We
  407. // have to clear it first.
  408. t.move(0 /* up */, 0 /* down */, t.cursorX /* left */, 0 /* right */)
  409. t.cursorX = 0
  410. t.clearLineToRight()
  411. for t.cursorY > 0 {
  412. t.move(1 /* up */, 0, 0, 0)
  413. t.cursorY--
  414. t.clearLineToRight()
  415. }
  416. if _, err = t.c.Write(t.outBuf); err != nil {
  417. return
  418. }
  419. t.outBuf = t.outBuf[:0]
  420. if n, err = t.c.Write(buf); err != nil {
  421. return
  422. }
  423. t.queue([]byte(t.prompt))
  424. chars := len(t.prompt)
  425. if t.echo {
  426. t.queue(t.line)
  427. chars += len(t.line)
  428. }
  429. t.cursorX = chars % t.termWidth
  430. t.cursorY = chars / t.termWidth
  431. t.moveCursorToPos(t.pos)
  432. if _, err = t.c.Write(t.outBuf); err != nil {
  433. return
  434. }
  435. t.outBuf = t.outBuf[:0]
  436. return
  437. }
  438. // ReadPassword temporarily changes the prompt and reads a password, without
  439. // echo, from the terminal.
  440. func (t *Terminal) ReadPassword(prompt string) (line string, err error) {
  441. t.lock.Lock()
  442. defer t.lock.Unlock()
  443. oldPrompt := t.prompt
  444. t.prompt = prompt
  445. t.echo = false
  446. line, err = t.readLine()
  447. t.prompt = oldPrompt
  448. t.echo = true
  449. return
  450. }
  451. // ReadLine returns a line of input from the terminal.
  452. func (t *Terminal) ReadLine() (line string, err error) {
  453. t.lock.Lock()
  454. defer t.lock.Unlock()
  455. return t.readLine()
  456. }
  457. func (t *Terminal) readLine() (line string, err error) {
  458. // t.lock must be held at this point
  459. if t.cursorX == 0 && t.cursorY == 0 {
  460. t.writeLine([]byte(t.prompt))
  461. t.c.Write(t.outBuf)
  462. t.outBuf = t.outBuf[:0]
  463. }
  464. for {
  465. rest := t.remainder
  466. lineOk := false
  467. for !lineOk {
  468. var key int
  469. key, rest = bytesToKey(rest)
  470. if key < 0 {
  471. break
  472. }
  473. if key == keyCtrlD {
  474. return "", io.EOF
  475. }
  476. line, lineOk = t.handleKey(key)
  477. }
  478. if len(rest) > 0 {
  479. n := copy(t.inBuf[:], rest)
  480. t.remainder = t.inBuf[:n]
  481. } else {
  482. t.remainder = nil
  483. }
  484. t.c.Write(t.outBuf)
  485. t.outBuf = t.outBuf[:0]
  486. if lineOk {
  487. if t.echo {
  488. t.historyIndex = -1
  489. t.history.Add(line)
  490. }
  491. return
  492. }
  493. // t.remainder is a slice at the beginning of t.inBuf
  494. // containing a partial key sequence
  495. readBuf := t.inBuf[len(t.remainder):]
  496. var n int
  497. t.lock.Unlock()
  498. n, err = t.c.Read(readBuf)
  499. t.lock.Lock()
  500. if err != nil {
  501. return
  502. }
  503. t.remainder = t.inBuf[:n+len(t.remainder)]
  504. }
  505. panic("unreachable") // for Go 1.0.
  506. }
  507. // SetPrompt sets the prompt to be used when reading subsequent lines.
  508. func (t *Terminal) SetPrompt(prompt string) {
  509. t.lock.Lock()
  510. defer t.lock.Unlock()
  511. t.prompt = prompt
  512. }
  513. func (t *Terminal) SetSize(width, height int) {
  514. t.lock.Lock()
  515. defer t.lock.Unlock()
  516. t.termWidth, t.termHeight = width, height
  517. }
  518. // stRingBuffer is a ring buffer of strings.
  519. type stRingBuffer struct {
  520. // entries contains max elements.
  521. entries []string
  522. max int
  523. // head contains the index of the element most recently added to the ring.
  524. head int
  525. // size contains the number of elements in the ring.
  526. size int
  527. }
  528. func (s *stRingBuffer) Add(a string) {
  529. if s.entries == nil {
  530. const defaultNumEntries = 100
  531. s.entries = make([]string, defaultNumEntries)
  532. s.max = defaultNumEntries
  533. }
  534. s.head = (s.head + 1) % s.max
  535. s.entries[s.head] = a
  536. if s.size < s.max {
  537. s.size++
  538. }
  539. }
  540. // NthPreviousEntry returns the value passed to the nth previous call to Add.
  541. // If n is zero then the immediately prior value is returned, if one, then the
  542. // next most recent, and so on. If such an element doesn't exist then ok is
  543. // false.
  544. func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) {
  545. if n >= s.size {
  546. return "", false
  547. }
  548. index := s.head - n
  549. if index < 0 {
  550. index += s.max
  551. }
  552. return s.entries[index], true
  553. }