terminal.go 15 KB

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