input.go 13 KB

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