summaryrefslogtreecommitdiff
path: root/xlockkbd.c
blob: 3e986211a69f26d53fab2b0686c90cf8db189a4b (plain) (blame)
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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>

static void die(const char *s)
{
	fprintf(stderr, "xlockkbd: %s\n", s);
	exit(1);
}

static bool grab_kbd(Display *d, int screen)
{
	Window w = RootWindow(d, screen);
	int res;

	// attempt to grab keyboard for 500ms if already grabbed.
	// thanks to slock code for the pointer.
	for (int i = 0;;) {
		res = XGrabKeyboard(d, w, True, GrabModeAsync, GrabModeAsync,
			CurrentTime);
		if (res != AlreadyGrabbed || ++i > 5)
			break;

		usleep(100000);
	}

	return (res == GrabSuccess);
}

static void wait_for_key(Display *d)
{
	XEvent ev;
	while (!XNextEvent(d, &ev)) {
		if (ev.type == KeyPress &&
				XLookupKeysym(&ev.xkey, 0) == XK_Escape)
			break;
	}
}

int main()
{
	Display *d = XOpenDisplay(NULL);
	if (!d)
		die("cannot open display");

	for (int i = 0; i < ScreenCount(d); ++i) {
		if (!grab_kbd(d, i))
			die("failed to grab keyboard");
	}

	wait_for_key(d);
	return 0;
}