summaryrefslogtreecommitdiffstats
path: root/xlock/main.c
blob: 74c4ee9edab6ac8491c9c191d33b97319ed26c8f (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 *   Copyright (C) 2010 Michael Buesch <m@bues.ch>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <X11/Xlib.h>


static Display *display;


static void signal_handler(int signal)
{
	XUngrabKeyboard(display, CurrentTime);
	XUngrabPointer(display, CurrentTime);
	XSync(display, True);
	printf("pwrtray-xlock: released\n");
	exit(0);
}

static int install_sighandler(int signal, void (*handler)(int))
{
	struct sigaction act;

	memset(&act, 0, sizeof(act));
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_handler = handler;

	return sigaction(signal, &act, NULL);
}

int main(int argc, char **argv)
{
	Window window;
	int res;
	sigset_t sigset;

	display = XOpenDisplay(NULL);
	if (!display) {
		/* Fallback to the first display. */
		display = XOpenDisplay(":0");
		if (!display) {
			fprintf(stderr, "Failed to open DISPLAY\n");
			return 1;
		}
	}
	window = DefaultRootWindow(display);

	sigemptyset(&sigset);
	res = sigprocmask(SIG_SETMASK, &sigset, NULL);
	res |= install_sighandler(SIGINT, signal_handler);
	res |= install_sighandler(SIGTERM, signal_handler);
	if (res) {
		fprintf(stderr, "Failed to setup signal handlers\n");
		return 1;
	}

	res = XGrabPointer(display, window,
			   False, 0, GrabModeAsync, GrabModeAsync,
			   None, None, CurrentTime);
	if (res != GrabSuccess) {
		fprintf(stderr, "Failed to grab pointer (res=%d)\n", res);
		return 1;
	}
	res = XGrabKeyboard(display, window,
			    False, GrabModeAsync, GrabModeAsync,
			    CurrentTime);
	if (res != GrabSuccess) {
		fprintf(stderr, "Failed to grab keyboard (res=%d)\n", res);
		XUngrabPointer(display, CurrentTime);
		return 1;
	}
	XFlush(display);

	printf("pwrtray-xlock: locked\n");
	while (1)
		sleep(0xFFFF);
}
bues.ch cgit interface