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  // hide cursor, reset color to default, clear screen
  34  xputsn("\e[?25l\e0m\e[2J");
  35  xset_terminal(1, 1, 0, 0); // Raw mode
  36
  37  for (;;) {
  38    printf("\e[%u;%uH%c", y+1, x+1, c);
  39    t[1&++tick] = time(0);
  40    if (t[0] != t[1]) terminal_probesize(&width, &height);
  41    // Don't block first time through, to force header print
  42    key = scan_key_getsize(scratch, -1*!!t[0], &width, &height);
  43    printf("\e[HESC to exit: ");
  44    // Print unknown escape sequence
  45    if (*scratch) {
  46      printf("key=[ESC");
  47      // Fetch rest of sequence after deviation, time gap determines end
  48      while (0<(key = scan_key_getsize(scratch, 0, &width, &height)))
  49        printf("%c", key);
  50      printf("] ");
  51    } else printf("key=%d ", key);
  52    printf("x=%d y=%d width=%d height=%d\e[K", x, y, width, height);
  53    fflush(0);
  54
  55    if (key == -2) continue;
  56    if (key <= ' ') break;
  57    if (key>=256) {
  58      printf("\e[%u;%uH ", y+1, x+1);
  59
  60      key -= 256;
  61      if (key==KEY_UP) y--;
  62      else if (key==KEY_DOWN) y++;
  63      else if (key==KEY_RIGHT) x++;
  64      else if (key==KEY_LEFT) x--;
  65      else if (key==KEY_PGUP) y = 0;
  66      else if (key==KEY_PGDN) y = 999;
  67      else if (key==KEY_HOME) x = 0;
  68      else if (key==KEY_END) x = 999;
  69      if (y<1) y = 1;
  70      if (y>=height) y = height-1;
  71      if (x<0) x = 0;
  72      if (x>=width) x = width-1;
  73    } else c = key;
  74  }
  75  tty_reset();
  76}
  77