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