Advertisement
Guest User

non-blocking keyboard input in swift

a guest
May 1st, 2019
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.24 KB | None | 0 0
  1. import Darwin
  2.  
  3. var orig_termios = termios()
  4.  
  5. func reset_terminal_mode() {
  6.   tcsetattr(0, TCSANOW, &orig_termios)
  7. }
  8.  
  9. func set_conio_terminal_mode() {
  10.   tcgetattr(0, &orig_termios)
  11.   var new_termios = orig_termios
  12.   atexit(reset_terminal_mode)
  13.   cfmakeraw(&new_termios)
  14.   tcsetattr(0, TCSANOW, &new_termios)
  15. }
  16.  
  17. func kbhit() -> Bool {
  18.   var fds = [ pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0) ]
  19.   let res = poll(&fds, 1, 0)
  20.   return res > 0
  21. }
  22.  
  23. func getChar() -> Int {
  24.   var c: UInt8 = 0
  25.  
  26.   let r = read(0, &c, 1)
  27.   if r < 0 {
  28.     return r
  29.   } else {
  30.     return Int(c)
  31.   }
  32. }
  33.  
  34. print("Type anything: ", terminator: "")
  35. fflush(stdout)
  36.  
  37. set_conio_terminal_mode()
  38.  
  39. var key: Int
  40.  
  41. while true {
  42.   if kbhit() {
  43.     key = getChar()
  44.  
  45.     if key == 13 {  // return key
  46.       break
  47.     } else {
  48.       print(String(UnicodeScalar(key)!)+", ", terminator:"")
  49.       fflush(stdout)
  50.     }
  51.   } else {
  52.     print(".", terminator: "")
  53.     fflush(stdout)
  54.     usleep(10)
  55.     print(".", terminator: "")
  56.     fflush(stdout)
  57.     usleep(10)
  58.     print(".", terminator: "")
  59.     fflush(stdout)
  60.     usleep(10)
  61.     print("\u{1B}[3D", terminator: "")
  62.     fflush(stdout)
  63.     usleep(10)
  64.   }
  65. }
  66.  
  67. print("\r")
  68. reset_terminal_mode()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement