demo_scankey.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* demo_scankey.c - collate incoming ansi escape sequences.
  2. *
  3. * Copyright 2015 Rob Landley <rob@landley.net>
  4. *
  5. * TODO sigwinch
  6. USE_DEMO_SCANKEY(NEWTOY(demo_scankey, 0, TOYFLAG_BIN))
  7. config DEMO_SCANKEY
  8. bool "demo_scankey"
  9. default n
  10. help
  11. usage: demo_scankey
  12. Move a letter around the screen. Hit ESC to exit.
  13. */
  14. #define FOR_demo_scankey
  15. #include "toys.h"
  16. void demo_scankey_main(void)
  17. {
  18. time_t t[2];
  19. unsigned width, height, tick;
  20. char c = 'X', scratch[16];
  21. int key, x, y;
  22. t[0] = t[1] = x = tick = 0;
  23. memset(scratch, 0, 16);
  24. y = 1;
  25. sigatexit(tty_sigreset); // Make ctrl-c restore tty
  26. // hide cursor, reset color to default, clear screen
  27. xputsn("\e[?25l\e0m\e[2J");
  28. xset_terminal(1, 1, 0, 0); // Raw mode
  29. for (;;) {
  30. printf("\e[%u;%uH%c", y+1, x+1, c);
  31. t[1&++tick] = time(0);
  32. if (t[0] != t[1]) terminal_probesize(&width, &height);
  33. // Don't block first time through, to force header print
  34. key = scan_key_getsize(scratch, -1*!!t[0], &width, &height);
  35. printf("\e[HESC to exit: ");
  36. // Print unknown escape sequence
  37. if (*scratch) {
  38. printf("key=[ESC");
  39. // Fetch rest of sequence after deviation, time gap determines end
  40. while (0<(key = scan_key_getsize(scratch, 0, &width, &height)))
  41. printf("%c", key);
  42. printf("] ");
  43. } else printf("key=%d ", key);
  44. printf("x=%d y=%d width=%d height=%d\e[K", x, y, width, height);
  45. fflush(0);
  46. if (key == -2) continue;
  47. if (key <= ' ') break;
  48. if (key>=256) {
  49. printf("\e[%u;%uH ", y+1, x+1);
  50. key -= 256;
  51. if (key==KEY_UP) y--;
  52. else if (key==KEY_DOWN) y++;
  53. else if (key==KEY_RIGHT) x++;
  54. else if (key==KEY_LEFT) x--;
  55. else if (key==KEY_PGUP) y = 0;
  56. else if (key==KEY_PGDN) y = 999;
  57. else if (key==KEY_HOME) x = 0;
  58. else if (key==KEY_END) x = 999;
  59. if (y<1) y = 1;
  60. if (y>=height) y = height-1;
  61. if (x<0) x = 0;
  62. if (x>=width) x = width-1;
  63. } else c = key;
  64. }
  65. tty_reset();
  66. }