From 9df6f621b984b9a5dd3ae95df3d3ef94b6280de3 Mon Sep 17 00:00:00 2001 From: Paul LeoNerd Evans Date: Thu, 6 Nov 2008 19:33:07 +0000 Subject: Added asynchronous demo which uses poll() --- Makefile | 5 ++++- demo-async.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 demo-async.c diff --git a/Makefile b/Makefile index 84f2e13..8fcceef 100644 --- a/Makefile +++ b/Makefile @@ -15,11 +15,14 @@ ifeq ($(DEBUG),1) CFLAGS_DEBUG=-ggdb -DDEBUG endif -all: demo +all: demo demo-async demo: libtermkey.so demo.c $(CC) $(CFLAGS) $(CFLAGS_DEBUG) -o $@ $^ +demo-async: libtermkey.so demo-async.c + $(CC) $(CFLAGS) $(CFLAGS_DEBUG) -o $@ $^ + libtermkey.so: termkey.o driver-csi.o driver-ti.o $(LD) -shared -soname=$(SONAME) -o $@ $^ -lncurses diff --git a/demo-async.c b/demo-async.c new file mode 100644 index 0000000..5f42cab --- /dev/null +++ b/demo-async.c @@ -0,0 +1,58 @@ +#include +#include + +#include "termkey.h" + +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_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_getwaittime(tk); + else + nextwait = -1; + } + + termkey_destroy(tk); +} -- cgit v1.2.3-70-g09d2