input.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. // This is like GetKey
  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. ArrayPop(&readerBuffer, 2)
  208. switch r2 {
  209. case '\x50':
  210. d.readerChannel <- ReaderData{0, DOWN_ARROW, nil}
  211. case '\x48':
  212. d.readerChannel <- ReaderData{0, UP_ARROW, nil}
  213. case '\x4b':
  214. d.readerChannel <- ReaderData{0, LEFT_ARROW, nil}
  215. case 0x4d:
  216. d.readerChannel <- ReaderData{0, RIGHT_ARROW, nil}
  217. case 0x47:
  218. d.readerChannel <- ReaderData{0, HOME, nil}
  219. case 0x4f:
  220. d.readerChannel <- ReaderData{0, END, nil}
  221. case 0x49:
  222. d.readerChannel <- ReaderData{0, PAGE_UP, nil}
  223. case 0x51:
  224. d.readerChannel <- ReaderData{0, PAGE_DOWN, nil}
  225. case 0x3b:
  226. d.readerChannel <- ReaderData{0, F1, nil}
  227. case 0x3c:
  228. d.readerChannel <- ReaderData{0, F2, nil}
  229. case 0x3d:
  230. d.readerChannel <- ReaderData{0, F3, nil}
  231. case 0x3e:
  232. d.readerChannel <- ReaderData{0, F4, nil}
  233. case 0x3f:
  234. d.readerChannel <- ReaderData{0, F5, nil}
  235. case 0x40:
  236. d.readerChannel <- ReaderData{0, F6, nil}
  237. case 0x41:
  238. d.readerChannel <- ReaderData{0, F7, nil}
  239. case 0x42:
  240. d.readerChannel <- ReaderData{0, F8, nil}
  241. case 0x43:
  242. d.readerChannel <- ReaderData{0, F9, nil}
  243. case 0x44:
  244. d.readerChannel <- ReaderData{0, F10, nil}
  245. case 0x45:
  246. d.readerChannel <- ReaderData{0, F11, nil}
  247. case 0x46:
  248. d.readerChannel <- ReaderData{0, F12, nil}
  249. case 0x52:
  250. d.readerChannel <- ReaderData{0, INSERT, nil}
  251. case 0x53:
  252. d.readerChannel <- ReaderData{0, DELETE, nil}
  253. default:
  254. log.Printf("ERROR Doorway mode: 0x00 %x\n", r2)
  255. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  256. }
  257. } else {
  258. return
  259. }
  260. continue
  261. } // end doorway mode
  262. if r == '\x1b' {
  263. // Escape key, or ?
  264. // This is a little harder, since we don't know how many we need.
  265. if !has2 && !newRune {
  266. ArrayPop(&readerBuffer, 1)
  267. d.readerChannel <- ReaderData{r, NOP, nil}
  268. return
  269. }
  270. if has2 {
  271. // We at least have the 2nd one...
  272. if r2 == '\x1b' {
  273. ArrayPop(&readerBuffer, 1)
  274. d.readerChannel <- ReaderData{r, NOP, nil}
  275. continue
  276. }
  277. // Can't distinguish between \x1bO and \x1bOP (F1)
  278. /*
  279. if unicode.IsLetter(r2) {
  280. // ALT-KEY
  281. if unicode.IsLower(r2) {
  282. ArrayPop(&readerBuffer, 2)
  283. ex := Extended(int(ALT_a) + int(r2-'a'))
  284. d.readerChannel <- ReaderData{0, ex, nil}
  285. } else {
  286. // Must be upper
  287. ArrayPop(&readerBuffer, 2)
  288. ex := Extended(int(ALT_A) + int(r2-'A'))
  289. d.readerChannel <- ReaderData{0, ex, nil}
  290. }
  291. continue
  292. }
  293. */
  294. // \x1b[ codes end with @-~ 0x40-0x7e
  295. var extended []rune = make([]rune, 0, 10)
  296. extended = append(extended, r2)
  297. var extlen = 2 // Length of codes to remove on successful match.
  298. var pos = 2 // Where we get the next rune from
  299. var isMouse bool = false
  300. var found bool = false
  301. if DEBUG_INPUT {
  302. log.Println(pos, readerBuffer)
  303. }
  304. for pos < rlen {
  305. r2 = readerBuffer[pos]
  306. pos++
  307. extlen++
  308. extended = append(extended, r2)
  309. if DEBUG_INPUT {
  310. log.Println("0x1b LOOP pos:", pos, "extlen:", extlen, "extended:", string(extended))
  311. }
  312. ext, has := extendedKeys[string(extended)]
  313. if has {
  314. // Found it!
  315. if DEBUG_INPUT {
  316. log.Println("Found Extended Match:", ext.String())
  317. }
  318. ArrayPop(&readerBuffer, extlen)
  319. d.readerChannel <- ReaderData{0, ext, nil}
  320. found = true
  321. break
  322. }
  323. // Mouse codes can also contain letters.
  324. if !isMouse && unicode.IsLetter(r2) {
  325. // end of extended code, unless mouse!
  326. if DEBUG_INPUT {
  327. log.Println("not mouse, is letter...")
  328. }
  329. if string(extended) == "[M" {
  330. isMouse = true
  331. } else {
  332. break
  333. }
  334. }
  335. if isMouse && len(extended) == 5 {
  336. break
  337. }
  338. }
  339. if found {
  340. continue
  341. }
  342. if DEBUG_INPUT {
  343. log.Println("POS:", pos, "EXLEN:", extlen, "Extended:", extended, "readerBuffer:", readerBuffer)
  344. log.Printf("(possible) Extended Code: [%s]", extended_output(extended))
  345. }
  346. var exString string = string(extended)
  347. if strings.HasPrefix(exString, "[M") && len(extended) == 5 {
  348. // Yes, "valid"
  349. ArrayPop(&readerBuffer, extlen)
  350. // Mouse Extended - input zero based (I add +1 to X, Y, and button)
  351. var mouse Mouse = Mouse{Button: RuneToInt8(extended[2]) - ' ' + 1,
  352. X: RuneToInt8(extended[3]) - '!' + 1,
  353. Y: RuneToInt8(extended[4]) - '!' + 1}
  354. d.AddMouse(mouse)
  355. log.Println("Mouse:", mouse)
  356. d.readerChannel <- ReaderData{0, MOUSE, nil}
  357. continue
  358. }
  359. if strings.HasSuffix(exString, "R") {
  360. // yes, "valid"
  361. ArrayPop(&readerBuffer, extlen)
  362. // Cursor Position information (or Shift-F3)
  363. var cursor CursorPos
  364. // ^[[1;1R^[[2;3r^[[41;173R
  365. // Y;X
  366. exString = exString[1 : len(exString)-1] // Remove [ and R
  367. pos := SplitToInt(exString, ";")
  368. if len(pos) == 2 {
  369. cursor.X = pos[1]
  370. cursor.Y = pos[0]
  371. d.AddCursorPos(cursor)
  372. /*
  373. d.mcMutex.Lock()
  374. d.LastCursor = append(d.LastCursor, cursor)
  375. d.mcMutex.Unlock()
  376. */
  377. log.Println("Cursor Pos:", cursor)
  378. d.readerChannel <- ReaderData{0, CURSOR, nil}
  379. continue
  380. } else {
  381. log.Println("ERROR Cursor Pos:", extended)
  382. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  383. continue
  384. }
  385. }
  386. // Ok, this LOOKS like something invalid...
  387. if !newRune {
  388. // Yes, this is invalid.
  389. ArrayPop(&readerBuffer, extlen)
  390. log.Println("ERROR Extended:", extended)
  391. d.readerChannel <- ReaderData{0, UNKNOWN, nil}
  392. } else {
  393. if DEBUG_INPUT {
  394. log.Println("(Possibly) invalid extended:", extended)
  395. }
  396. return
  397. }
  398. } else {
  399. return
  400. }
  401. continue
  402. }
  403. ArrayPop(&readerBuffer, 1)
  404. d.readerChannel <- ReaderData{r, NOP, nil}
  405. continue
  406. }
  407. }
  408. func (d *Door) WaitKey(timeout time.Duration) (rune, Extended, error) {
  409. /*
  410. d.readerMutex.Lock()
  411. if d.ReaderClosed {
  412. d.readerMutex.Unlock()
  413. return 0, NOP, ErrDisconnected
  414. }
  415. d.readerMutex.Unlock()
  416. */
  417. if WantGetMouse {
  418. d.GetMouse()
  419. }
  420. // Probably faster to just read from closed channel and get ok = false.
  421. select {
  422. case r, ok := <-d.readerChannel:
  423. if ok {
  424. if DEBUG_INPUT {
  425. log.Println("WaitKey:", r)
  426. }
  427. // return bio.GetKey()
  428. if r.Ex == MOUSE {
  429. WantGetMouse = true
  430. }
  431. return r.R, r.Ex, r.Err
  432. } else {
  433. log.Println("WaitKey: Disconnected")
  434. // Reader has closed.
  435. // Disconnected = true
  436. return 0, NOP, ErrDisconnected
  437. }
  438. case <-time.After(timeout):
  439. return 0, NOP, ErrTimeout
  440. }
  441. }
  442. // Outputs spaces and backspaces
  443. // If you have set a background color, this shows the input area.
  444. func DisplayInput(max int) string {
  445. return strings.Repeat(" ", max) + strings.Repeat("\x08", max)
  446. }
  447. // Input a string of max length.
  448. // This displays the input area if a bg color was set.
  449. // This handles timeout, input, backspace, and enter.
  450. func (d *Door) Input(max int) string {
  451. var line []rune = make([]rune, 0, max)
  452. var length int
  453. // draw input area
  454. d.Write(DisplayInput(max))
  455. var r rune
  456. var ex Extended
  457. var err error
  458. for {
  459. r, ex, err = d.WaitKey(DefaultTimeout)
  460. if err != nil {
  461. // timeout/hangup
  462. return ""
  463. }
  464. if ex != NOP {
  465. continue
  466. }
  467. uw := UnicodeWidth(r)
  468. if strconv.IsPrint(r) {
  469. if length+uw <= max {
  470. d.Write(string(r))
  471. line = append(line, r)
  472. length += uw
  473. } else {
  474. d.Write("\x07")
  475. }
  476. } else {
  477. // Non-print
  478. switch r {
  479. case 0x7f, 0x08:
  480. if len(line) > 0 {
  481. d.Write("\x08 \x08")
  482. rlen := len(line)
  483. if UnicodeWidth(line[rlen-1]) == 2 {
  484. d.Write("\x08 \x08")
  485. length -= 2
  486. } else {
  487. length--
  488. }
  489. line = line[0 : rlen-1]
  490. }
  491. case 0x0d:
  492. return string(line)
  493. }
  494. }
  495. }
  496. }
  497. func (d *Door) GetOneOf(possible string) rune {
  498. var r rune
  499. var err error
  500. for {
  501. r, _, err = d.WaitKey(DefaultTimeout)
  502. if err != nil {
  503. return rune(0)
  504. }
  505. r := unicode.ToUpper(r)
  506. if strings.ContainsRune(possible, r) {
  507. // return upper case rune
  508. return r
  509. }
  510. }
  511. }