input.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. package door
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "log"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "unicode"
  12. )
  13. // See door.go for DEBUG_INPUT const
  14. var ErrInactivity error = fmt.Errorf("Inactivity")
  15. var ErrTimeout error = fmt.Errorf("Timeout")
  16. var ErrDisconnected error = fmt.Errorf("Disconnected")
  17. var DefaultTimeout time.Duration = time.Duration(60) * time.Second
  18. const READ_SIZE = 16 // Size of read buffer
  19. // put the common input routines here
  20. var readerBuffer []rune
  21. // https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_input_sequences
  22. // Translate these extended codes into these Extended values.
  23. var extendedKeys map[string]Extended = map[string]Extended{
  24. "[A": UP_ARROW,
  25. "[B": DOWN_ARROW,
  26. "[C": RIGHT_ARROW,
  27. "[D": LEFT_ARROW,
  28. "[H": HOME,
  29. "[F": END, // terminal
  30. "[1~": HOME, // putty (windows)
  31. "[4~": END, // putty (windows)
  32. "[K": END,
  33. "[V": PAGE_UP,
  34. "[U": PAGE_DOWN,
  35. "[@": INSERT,
  36. "[2~": INSERT, // terminal
  37. "[3~": DELETE, // terminal
  38. "[5~": PAGE_UP, // terminal
  39. "[6~": PAGE_DOWN, // terminal
  40. "[15~": F5, // terminal
  41. "[17~": F6, // terminal
  42. "[18~": F7, // terminal
  43. "[19~": F8, // terminal
  44. "[20~": F9, // terminal
  45. "[21~": F10, // terminal
  46. "[23~": F11,
  47. "[24~": F12, // terminal
  48. "OP": F1, // where did I find these O-codes? (from xterm)
  49. "OQ": F2,
  50. "OR": F3,
  51. "OS": F4, // syncterm "[1" = F1,F2,F3, and F4)
  52. "Ot": F5, // syncterm
  53. }
  54. func HasEnoughBytesForUnicode(runeread *bufio.Reader) bool {
  55. // Does the buffer have enough bytes for valid UTF-8?
  56. // https://en.wikipedia.org/wiki/UTF-8
  57. if runeread.Buffered() == 0 {
  58. return true
  59. }
  60. // must be at least 1, so:
  61. peek, err := runeread.Peek(1)
  62. if err != nil {
  63. return true
  64. }
  65. b := peek[0]
  66. if b&0x80 == 0 {
  67. // single byte unicode - OK!
  68. return true
  69. }
  70. if b&0b11100000 == 0b11000000 {
  71. // need 2 bytes
  72. if runeread.Buffered() >= 2 {
  73. return true
  74. }
  75. return false
  76. }
  77. if b&0b11110000 == 0b11100000 {
  78. if runeread.Buffered() >= 3 {
  79. return true
  80. }
  81. return false
  82. }
  83. if b&0b11111000 == 0b11110000 {
  84. if runeread.Buffered() >= 4 {
  85. return true
  86. }
  87. return false
  88. }
  89. // Invalid UTF-8 encoding.
  90. return true
  91. }
  92. func ReadRune(d *Door, runeread *bufio.Reader, timeout bool) {
  93. var input rune
  94. var err error
  95. // Is this unicode?
  96. err = nil
  97. for err == nil {
  98. //RuneRead:
  99. enough := HasEnoughBytesForUnicode(runeread)
  100. if (!enough) && (!timeout) {
  101. // We don't have enought, but there wasn't a timeout --
  102. // go try and read more.
  103. return
  104. }
  105. input, _, err = runeread.ReadRune()
  106. if err == io.EOF {
  107. break // continue
  108. }
  109. if err != nil {
  110. if DEBUG_INPUT {
  111. log.Printf("ReadRune: %#v\n", err)
  112. }
  113. // errors EOF
  114. break // continue // break for loop
  115. }
  116. if input == unicode.ReplacementChar {
  117. // possibly incomplete rune received.
  118. runeread.UnreadRune()
  119. b, _ := runeread.ReadByte()
  120. if DEBUG_INPUT {
  121. log.Printf("Reader (byte) >> %x\n", b)
  122. }
  123. readerBuffer = append(readerBuffer, rune(b))
  124. // d.readerChannel <- rune(b)
  125. } else {
  126. if DEBUG_INPUT {
  127. log.Printf("Reader >> %x\n", input)
  128. }
  129. readerBuffer = append(readerBuffer, input)
  130. // d.readerChannel <- input
  131. }
  132. // process(d, true)
  133. } // goto RuneRead
  134. process(d, !timeout)
  135. }
  136. func process(d *Door, newRune bool) {
  137. var rlen int
  138. var r, r2 rune
  139. var has2 bool
  140. var done bool = false
  141. for !done {
  142. rlen = len(readerBuffer)
  143. if rlen == 0 {
  144. // Nothing to do here
  145. return
  146. }
  147. if DEBUG_INPUT {
  148. log.Println("rlen:", rlen, "readerBuffer:", readerBuffer, "newRune:", newRune)
  149. }
  150. r = readerBuffer[0]
  151. if rlen >= 2 {
  152. r2 = readerBuffer[1]
  153. has2 = true
  154. } else {
  155. r2 = unicode.ReplacementChar
  156. has2 = false
  157. }
  158. // if !has2 and !newRune, then we're "done" (received everything,
  159. // and there's nothing else coming...)
  160. // fyneterm CR
  161. if r == '\x0a' {
  162. if !has2 && !newRune {
  163. ArrayPop(&readerBuffer, 1)
  164. d.readerChannel <- ReaderData{R: '\x0d', Ex: NOP, Err: nil}
  165. return
  166. }
  167. if has2 {
  168. ArrayPop(&readerBuffer, 1)
  169. if r2 == '\x00' || r2 == '\x0a' {
  170. ArrayPop(&readerBuffer, 1)
  171. }
  172. d.readerChannel <- ReaderData{R: '\x0d', Ex: NOP, Err: nil}
  173. } else {
  174. // We don't have a 2nd rune, and we haven't timed out.
  175. return
  176. }
  177. continue
  178. }
  179. // We get 0x0d, 0x00, or 0x0d 0x0a from syncterm
  180. if r == '\x0d' {
  181. if !has2 && !newRune {
  182. ArrayPop(&readerBuffer, 1)
  183. d.readerChannel <- ReaderData{R: r, Ex: NOP, Err: nil}
  184. return
  185. }
  186. if has2 {
  187. ArrayPop(&readerBuffer, 1)
  188. if r2 == '\x00' || r2 == '\x0a' {
  189. ArrayPop(&readerBuffer, 1)
  190. }
  191. d.readerChannel <- ReaderData{R: r, Ex: NOP, Err: nil}
  192. } else {
  193. return
  194. }
  195. continue
  196. }
  197. if r == '\x00' {
  198. // Possibly doorway mode - deprecated?
  199. // syncterm does support this.
  200. if !has2 && !newRune {
  201. // timeout
  202. ArrayPop(&readerBuffer, 1)
  203. d.readerChannel <- ReaderData{R: r, Ex: NOP, Err: nil}
  204. return
  205. }
  206. if has2 {
  207. doorwayMap := map[rune]Extended{'\x50': DOWN_ARROW,
  208. '\x48': UP_ARROW,
  209. '\x4b': LEFT_ARROW,
  210. '\x4d': RIGHT_ARROW,
  211. '\x47': HOME,
  212. '\x4f': END,
  213. '\x49': PAGE_UP,
  214. '\x51': PAGE_DOWN,
  215. '\x3b': F1,
  216. '\x3c': F2,
  217. '\x3d': F3,
  218. '\x3e': F4,
  219. '\x3f': F5,
  220. '\x40': F6,
  221. '\x41': F7,
  222. '\x42': F8,
  223. '\x43': F9,
  224. '\x44': F10,
  225. '\x45': F11,
  226. '\x46': F12,
  227. '\x52': INSERT,
  228. '\x53': DELETE,
  229. }
  230. ArrayPop(&readerBuffer, 2)
  231. ext, has := doorwayMap[r2]
  232. if has {
  233. d.readerChannel <- ReaderData{0, ext, nil}
  234. } else {
  235. log.Printf("ERROR Doorway mode: 0x00 %x\n", r2)
  236. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  237. }
  238. /*
  239. switch r2 {
  240. case '\x50':
  241. d.readerChannel <- ReaderData{0, DOWN_ARROW, nil}
  242. case '\x48':
  243. d.readerChannel <- ReaderData{0, UP_ARROW, nil}
  244. case '\x4b':
  245. d.readerChannel <- ReaderData{0, LEFT_ARROW, nil}
  246. case 0x4d:
  247. d.readerChannel <- ReaderData{0, RIGHT_ARROW, nil}
  248. case 0x47:
  249. d.readerChannel <- ReaderData{0, HOME, nil}
  250. case 0x4f:
  251. d.readerChannel <- ReaderData{0, END, nil}
  252. case 0x49:
  253. d.readerChannel <- ReaderData{0, PAGE_UP, nil}
  254. case 0x51:
  255. d.readerChannel <- ReaderData{0, PAGE_DOWN, nil}
  256. case 0x3b:
  257. d.readerChannel <- ReaderData{0, F1, nil}
  258. case 0x3c:
  259. d.readerChannel <- ReaderData{0, F2, nil}
  260. case 0x3d:
  261. d.readerChannel <- ReaderData{0, F3, nil}
  262. case 0x3e:
  263. d.readerChannel <- ReaderData{0, F4, nil}
  264. case 0x3f:
  265. d.readerChannel <- ReaderData{0, F5, nil}
  266. case 0x40:
  267. d.readerChannel <- ReaderData{0, F6, nil}
  268. case 0x41:
  269. d.readerChannel <- ReaderData{0, F7, nil}
  270. case 0x42:
  271. d.readerChannel <- ReaderData{0, F8, nil}
  272. case 0x43:
  273. d.readerChannel <- ReaderData{0, F9, nil}
  274. case 0x44:
  275. d.readerChannel <- ReaderData{0, F10, nil}
  276. case 0x45:
  277. d.readerChannel <- ReaderData{0, F11, nil}
  278. case 0x46:
  279. d.readerChannel <- ReaderData{0, F12, nil}
  280. case 0x52:
  281. d.readerChannel <- ReaderData{0, INSERT, nil}
  282. case 0x53:
  283. d.readerChannel <- ReaderData{0, DELETE, nil}
  284. default:
  285. log.Printf("ERROR Doorway mode: 0x00 %x\n", r2)
  286. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  287. }
  288. */
  289. } else {
  290. return
  291. }
  292. continue
  293. } // end doorway mode
  294. if r == '\x1b' {
  295. // Escape key, or ?
  296. // This is a little harder, since we don't know how many we need.
  297. if !has2 && !newRune {
  298. ArrayPop(&readerBuffer, 1)
  299. d.readerChannel <- ReaderData{r, NOP, nil}
  300. return
  301. }
  302. if has2 {
  303. // We at least have the 2nd one...
  304. if r2 == '\x1b' {
  305. ArrayPop(&readerBuffer, 1)
  306. d.readerChannel <- ReaderData{r, NOP, nil}
  307. continue
  308. }
  309. // Can't distinguish between \x1bO and \x1bOP (F1)
  310. /*
  311. if unicode.IsLetter(r2) {
  312. // ALT-KEY
  313. if unicode.IsLower(r2) {
  314. ArrayPop(&readerBuffer, 2)
  315. ex := Extended(int(ALT_a) + int(r2-'a'))
  316. d.readerChannel <- ReaderData{0, ex, nil}
  317. } else {
  318. // Must be upper
  319. ArrayPop(&readerBuffer, 2)
  320. ex := Extended(int(ALT_A) + int(r2-'A'))
  321. d.readerChannel <- ReaderData{0, ex, nil}
  322. }
  323. continue
  324. }
  325. */
  326. // \x1b[ codes end with @-~ 0x40-0x7e
  327. var extended []rune = make([]rune, 0, 10)
  328. extended = append(extended, r2)
  329. var extlen = 2 // Length of codes to remove on successful match.
  330. var pos = 2 // Where we get the next rune from
  331. var isMouse bool = false
  332. var found bool = false
  333. if DEBUG_INPUT {
  334. log.Println(pos, readerBuffer)
  335. }
  336. for pos < rlen {
  337. r2 = readerBuffer[pos]
  338. pos++
  339. extlen++
  340. extended = append(extended, r2)
  341. if DEBUG_INPUT {
  342. log.Println("0x1b LOOP pos:", pos, "extlen:", extlen, "extended:", string(extended))
  343. }
  344. ext, has := extendedKeys[string(extended)]
  345. if has {
  346. // Found it!
  347. if DEBUG_INPUT {
  348. log.Println("Found Extended Match:", ext.String())
  349. }
  350. ArrayPop(&readerBuffer, extlen)
  351. d.readerChannel <- ReaderData{0, ext, nil}
  352. found = true
  353. break
  354. }
  355. // Mouse codes can also contain letters.
  356. if !isMouse && unicode.IsLetter(r2) {
  357. // end of extended code, unless mouse!
  358. if DEBUG_INPUT {
  359. log.Println("not mouse, is letter...")
  360. }
  361. if string(extended) == "[M" {
  362. isMouse = true
  363. } else {
  364. break
  365. }
  366. }
  367. if isMouse && len(extended) == 5 {
  368. break
  369. }
  370. }
  371. if found {
  372. continue
  373. }
  374. if DEBUG_INPUT {
  375. log.Println("POS:", pos, "EXLEN:", extlen, "Extended:", extended, "readerBuffer:", readerBuffer)
  376. log.Printf("(possible) Extended Code: [%s]", extended_output(extended))
  377. }
  378. var exString string = string(extended)
  379. if strings.HasPrefix(exString, "[M") && len(extended) == 5 {
  380. // Yes, "valid"
  381. ArrayPop(&readerBuffer, extlen)
  382. // Mouse Extended - input zero based (I add +1 to X, Y, and button)
  383. var mouse Mouse = Mouse{Button: RuneToInt8(extended[2]) - ' ' + 1,
  384. X: RuneToInt8(extended[3]) - '!' + 1,
  385. Y: RuneToInt8(extended[4]) - '!' + 1}
  386. d.AddMouse(mouse)
  387. log.Println("Mouse:", mouse)
  388. d.readerChannel <- ReaderData{0, MOUSE, nil}
  389. continue
  390. }
  391. if strings.HasSuffix(exString, "R") {
  392. // yes, "valid"
  393. ArrayPop(&readerBuffer, extlen)
  394. // Cursor Position information (or Shift-F3)
  395. var cursor CursorPos
  396. // ^[[1;1R^[[2;3r^[[41;173R
  397. // Y;X
  398. exString = exString[1 : len(exString)-1] // Remove [ and R
  399. pos := SplitToInt(exString, ";")
  400. if len(pos) == 2 {
  401. cursor.X = pos[1]
  402. cursor.Y = pos[0]
  403. d.AddCursorPos(cursor)
  404. /*
  405. d.mcMutex.Lock()
  406. d.LastCursor = append(d.LastCursor, cursor)
  407. d.mcMutex.Unlock()
  408. */
  409. log.Println("Cursor Pos:", cursor)
  410. d.readerChannel <- ReaderData{0, CURSOR, nil}
  411. continue
  412. } else {
  413. log.Println("ERROR Cursor Pos:", extended)
  414. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  415. continue
  416. }
  417. }
  418. // Ok, this LOOKS like something invalid...
  419. if !newRune {
  420. // Yes, this is invalid.
  421. ArrayPop(&readerBuffer, extlen)
  422. // TODO: Save this somewhere.
  423. log.Println("ERROR Extended:", extended)
  424. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  425. } else {
  426. if DEBUG_INPUT {
  427. log.Println("(Possibly) invalid extended:", extended)
  428. }
  429. return
  430. }
  431. } else {
  432. return
  433. }
  434. continue
  435. }
  436. ArrayPop(&readerBuffer, 1)
  437. d.readerChannel <- ReaderData{r, NOP, nil}
  438. continue
  439. }
  440. }
  441. func (d *Door) WaitKey(timeout time.Duration) (rune, Extended, error) {
  442. if WantGetMouse {
  443. // Call GetMouse().
  444. d.GetMouse()
  445. }
  446. // Probably faster to just read from closed channel and get ok = false.
  447. select {
  448. case r, ok := <-d.readerChannel:
  449. if ok {
  450. if DEBUG_INPUT {
  451. log.Println("WaitKey:", r)
  452. }
  453. // return bio.GetKey()
  454. if r.Ex == MOUSE {
  455. // We want GetMouse() called.
  456. WantGetMouse = true
  457. }
  458. return r.R, r.Ex, r.Err
  459. } else {
  460. log.Println("WaitKey: Disconnected")
  461. // Reader has closed.
  462. // Disconnected = true
  463. return 0, NOP, ErrDisconnected
  464. }
  465. case <-time.After(timeout):
  466. return 0, NOP, ErrTimeout
  467. }
  468. }
  469. // Outputs spaces and backspaces
  470. // If you have set a background color, this shows the input area.
  471. func DisplayInput(max int) []byte {
  472. var output bytes.Buffer
  473. for x := 0; x < max; x++ {
  474. output.WriteByte(' ')
  475. }
  476. for x := 0; x < max; x++ {
  477. output.WriteByte('\x08')
  478. }
  479. return output.Bytes()
  480. // return strings.Repeat(" ", max) + strings.Repeat("\x08", max)
  481. }
  482. // Input a string of max length.
  483. // This displays the input area if a bg color was set.
  484. // This handles timeout, input, backspace, and enter.
  485. func (d *Door) Input(max int) string {
  486. var line []rune = make([]rune, 0, max)
  487. var length int
  488. var buffer bytes.Buffer
  489. var BSSPBS [3]byte = [3]byte{'\x08', ' ', '\x08'}
  490. // draw input area
  491. d.Write(DisplayInput(max))
  492. var r rune
  493. var ex Extended
  494. var err error
  495. for {
  496. r, ex, err = d.WaitKey(DefaultTimeout)
  497. if err != nil {
  498. // timeout/hangup
  499. return ""
  500. }
  501. if ex != NOP {
  502. continue
  503. }
  504. uw := UnicodeWidth(r)
  505. if strconv.IsPrint(r) {
  506. if length+uw <= max {
  507. buffer.Reset()
  508. buffer.WriteRune(r)
  509. d.Write(buffer.Bytes())
  510. // d.Write(string(r))
  511. line = append(line, r)
  512. length += uw
  513. } else {
  514. d.Write([]byte{'\x07'})
  515. }
  516. } else {
  517. // Non-print
  518. switch r {
  519. case 0x7f, 0x08:
  520. if len(line) > 0 {
  521. d.Write(BSSPBS[0:])
  522. rlen := len(line)
  523. if UnicodeWidth(line[rlen-1]) == 2 {
  524. d.Write(BSSPBS[0:])
  525. length -= 2
  526. } else {
  527. length--
  528. }
  529. line = line[0 : rlen-1]
  530. }
  531. case 0x0d:
  532. return string(line)
  533. }
  534. }
  535. }
  536. }
  537. func (d *Door) GetOneOf(possible string) rune {
  538. var r rune
  539. var err error
  540. for {
  541. r, _, err = d.WaitKey(DefaultTimeout)
  542. if err != nil {
  543. return rune(0)
  544. }
  545. r := unicode.ToUpper(r)
  546. if strings.ContainsRune(possible, r) {
  547. // return upper case rune
  548. return r
  549. }
  550. }
  551. }