Files
termo/demo-async.c
T

74 lines
1.3 KiB
C
Raw Normal View History

// <poll.h> might need this for sigset_t
#define _XOPEN_SOURCE 600
2008-11-06 19:33:07 +00:00
#include <poll.h>
#include <stdio.h>
2014-09-28 03:51:45 +02:00
#include <unistd.h>
#include <locale.h>
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
#include "termo.h"
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
static void
2014-10-14 00:08:15 +02:00
on_key (termo_t *tk, termo_key_t *key)
2008-11-06 19:33:07 +00:00
{
2014-09-23 01:38:08 +02:00
char buffer[50];
2014-10-14 00:08:15 +02:00
termo_strfkey (tk, buffer, sizeof buffer, key, TERMO_FORMAT_VIM);
2014-09-23 01:38:08 +02:00
printf ("%s\n", buffer);
2008-11-06 19:33:07 +00:00
}
2014-09-23 01:38:08 +02:00
int
main (int argc, char *argv[])
2008-12-08 22:54:14 +00:00
{
2014-09-23 02:33:06 +02:00
(void) argc;
(void) argv;
2014-10-14 00:08:15 +02:00
TERMO_CHECK_VERSION;
2014-09-28 03:51:45 +02:00
setlocale (LC_CTYPE, "");
2014-10-14 00:08:15 +02:00
termo_t *tk = termo_new (STDIN_FILENO, NULL, 0);
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
if (!tk)
{
2014-10-14 00:08:15 +02:00
fprintf (stderr, "Cannot allocate termo instance\n");
2014-09-23 01:38:08 +02:00
exit (1);
}
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
struct pollfd fd;
2014-10-14 21:19:11 +02:00
fd.fd = STDIN_FILENO; // the file descriptor we passed to termo_new()
2014-09-23 01:38:08 +02:00
fd.events = POLLIN;
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
termo_result_t ret;
termo_key_t key;
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
int running = 1;
int nextwait = -1;
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
while (running)
{
if (poll (&fd, 1, nextwait) == 0)
// Timed out
2014-10-14 00:08:15 +02:00
if (termo_getkey_force (tk, &key) == TERMO_RES_KEY)
2014-09-23 01:38:08 +02:00
on_key (tk, &key);
2008-11-06 19:33:07 +00:00
2014-09-23 01:38:08 +02:00
if (fd.revents & (POLLIN | POLLHUP | POLLERR))
2014-10-14 00:08:15 +02:00
termo_advisereadable (tk);
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
while ((ret = termo_getkey (tk, &key)) == TERMO_RES_KEY)
2014-09-23 01:38:08 +02:00
{
on_key (tk, &key);
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
if (key.type == TERMO_TYPE_KEY
&& (key.modifiers & TERMO_KEYMOD_CTRL)
2014-09-23 01:38:08 +02:00
&& (key.code.codepoint == 'C' || key.code.codepoint == 'c'))
running = 0;
}
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
if (ret == TERMO_RES_AGAIN)
nextwait = termo_get_waittime (tk);
2014-09-23 01:38:08 +02:00
else
nextwait = -1;
}
2008-11-06 19:33:07 +00:00
2014-10-14 00:08:15 +02:00
termo_destroy (tk);
2008-11-06 19:33:07 +00:00
}