aboutsummaryrefslogtreecommitdiff
path: root/demo-async.c
blob: 0ac9f27027bf36ab5c2b1cd9329a902d2c364a0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <poll.h>
#include <stdio.h>

#include "termkey.h"

static void on_key(termkey_t *tk, termkey_key *key)
{
  char buffer[50];
  termkey_snprint_key(tk, buffer, sizeof buffer, key, TERMKEY_FORMAT_VIM);
  printf("%s\n", buffer);
}

int main(int argc, char *argv[]) {
  TERMKEY_CHECK_VERSION;

  termkey_t *tk = termkey_new(0, 0);

  if(!tk) {
    fprintf(stderr, "Cannot allocate termkey instance\n");
    exit(1);
  }

  struct pollfd fd;

  fd.fd = 0; /* the file descriptor we passed to termkey_new() */
  fd.events = POLLIN;

  termkey_result ret;
  termkey_key key;

  int running = 1;
  int nextwait = -1;

  while(running) {
    if(poll(&fd, 1, nextwait) == 0) {
      // Timed out
      if(termkey_getkey_force(tk, &key) == TERMKEY_RES_KEY)
        on_key(tk, &key);
    }

    if(fd.revents & (POLLIN|POLLHUP|POLLERR))
      termkey_advisereadable(tk);

    while((ret = termkey_getkey(tk, &key)) == TERMKEY_RES_KEY) {
      on_key(tk, &key);

      if(key.type == TERMKEY_TYPE_UNICODE &&
         key.modifiers & TERMKEY_KEYMOD_CTRL &&
         (key.code.codepoint == 'C' || key.code.codepoint == 'c'))
        running = 0;
    }

    if(ret == TERMKEY_RES_AGAIN)
      nextwait = termkey_get_waittime(tk);
    else
      nextwait = -1;
  }

  termkey_destroy(tk);
}