input.go 14 KB

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