aboutsummaryrefslogtreecommitdiff
path: root/big-brother.c
blob: c5c9c1a54c1db114c37ee98704c5b2ef70d0d185 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
 * big-brother.c: activity tracker
 *
 * Copyright (c) 2016, Přemysl Janouch <p.janouch@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#define LIBERTY_WANT_POLLER

#include "config.h"
#undef PROGRAM_NAME
#define PROGRAM_NAME "big-brother"
#include "liberty/liberty.c"

#include <locale.h>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/extensions/sync.h>

// --- Utilities ---------------------------------------------------------------

static int64_t
clock_msec (clockid_t clock)
{
	struct timespec tp;
	hard_assert (clock_gettime (clock, &tp) != -1);
	return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_nsec / 1000000;
}

static char *
timestamp (int64_t ts)
{
	char buf[24];
	struct tm tm;
	time_t when = ts / 1000;
	strftime (buf, sizeof buf, "%F %T", gmtime_r (&when, &tm));
	return xstrdup_printf ("%s.%03d", buf, (int) (ts % 1000));
}

static void
log_message_custom (void *user_data, const char *quote, const char *fmt,
	va_list ap)
{
	(void) user_data;
	FILE *stream = stdout;

	char *ts = timestamp (clock_msec (CLOCK_REALTIME));
	fprintf (stream, "%s ", ts);
	free (ts);

	fputs (quote, stream);
	vfprintf (stream, fmt, ap);
	fputs ("\n", stream);
}

// --- Configuration -----------------------------------------------------------

static struct simple_config_item g_config_table[] =
{
	{ "idle_timeout",    "600",             "Timeout for user inactivity (s)" },
	{ NULL,              NULL,              NULL                              }
};

// --- Application -------------------------------------------------------------

struct app_context
{
	struct str_map config;              ///< Program configuration
	struct poller poller;               ///< Poller
	bool running;                       ///< Event loop is running

	Display *dpy;                       ///< X display handle
	struct poller_fd x_event;           ///< X11 event

	Atom net_active_window;             ///< _NET_ACTIVE_WINDOW
	Atom net_wm_name;                   ///< _NET_WM_NAME

	// Window title tracking

	char *current_title;                ///< Current window title or NULL
	Window current_window;              ///< Current window

	// XSync activity tracking

	int xsync_base_event_code;          ///< XSync base event code
	XSyncCounter idle_counter;          ///< XSync IDLETIME counter
	XSyncValue idle_timeout;            ///< Idle timeout

	XSyncAlarm idle_alarm_inactive;     ///< User is inactive
	XSyncAlarm idle_alarm_active;       ///< User is active
};

static void
app_context_init (struct app_context *self)
{
	memset (self, 0, sizeof *self);

	str_map_init (&self->config);
	self->config.free = free;
	simple_config_load_defaults (&self->config, g_config_table);

	if (!(self->dpy = XOpenDisplay (NULL)))
		exit_fatal ("cannot open display");

	poller_init (&self->poller);
	poller_fd_init (&self->x_event, &self->poller,
		ConnectionNumber (self->dpy));

	self->net_active_window =
		XInternAtom (self->dpy, "_NET_ACTIVE_WINDOW", true);
	self->net_wm_name =
		XInternAtom (self->dpy, "_NET_WM_NAME", true);

	// TODO: it is possible to employ a fallback mechanism via XScreenSaver
	//   by polling the XScreenSaverInfo::idle field, see
	//   https://www.x.org/releases/X11R7.5/doc/man/man3/Xss.3.html

	int n;
	if (!XSyncQueryExtension (self->dpy, &self->xsync_base_event_code, &n)
	 || !XSyncInitialize (self->dpy, &n, &n))
		exit_fatal ("cannot initialize XSync");

	// The idle counter is not guaranteed to exist, only SERVERTIME is
	XSyncSystemCounter *counters = XSyncListSystemCounters (self->dpy, &n);
	while (n--)
	{
		if (!strcmp (counters[n].name, "IDLETIME"))
			self->idle_counter = counters[n].counter;
	}
	if (!self->idle_counter)
		exit_fatal ("idle counter is missing");
	XSyncFreeSystemCounterList (counters);
}

static void
app_context_free (struct app_context *self)
{
	str_map_free (&self->config);
	free (self->current_title);
	poller_fd_reset (&self->x_event);
	XCloseDisplay (self->dpy);
	poller_free (&self->poller);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

static char *
x_text_property_to_utf8 (struct app_context *ctx, XTextProperty *prop)
{
#if ARE_WE_UTF8_YET
	Atom utf8_string = XInternAtom (ctx->dpy, "UTF8_STRING", true);
	if (prop->encoding == utf8_string)
		return xstrdup ((char *) prop->value);
#endif

	int n = 0;
	char **list = NULL;
	if (XmbTextPropertyToTextList (ctx->dpy, prop, &list, &n) >= Success
		&& n > 0 && *list)
	{
		// TODO: convert from locale encoding into UTF-8
		char *result = xstrdup (*list);
		XFreeStringList (list);
		return result;
	}
	return NULL;
}

static char *
x_text_property (struct app_context *ctx, Window window, Atom atom)
{
	XTextProperty name;
	XGetTextProperty (ctx->dpy, window, &name, atom);
	if (!name.value)
		return NULL;

	char *result = x_text_property_to_utf8 (ctx, &name);
	XFree (name.value);
	return result;
}

static char *
x_window_title (struct app_context *ctx, Window window)
{
	char *title;
	if (!(title = x_text_property (ctx, window, ctx->net_wm_name))
	 && !(title = x_text_property (ctx, window, XA_WM_NAME)))
		title = xstrdup ("broken");
	return title;
}

static bool
update_window_title (struct app_context *ctx, char *new_title)
{
	bool changed = !ctx->current_title != !new_title
		|| (new_title && strcmp (ctx->current_title, new_title));
	free (ctx->current_title);
	ctx->current_title = new_title;
	return changed;
}

static void
update_current_window (struct app_context *ctx)
{
	Window root = DefaultRootWindow (ctx->dpy);

	Atom dummy_type; int dummy_format;
	unsigned long nitems, dummy_bytes;
	unsigned char *p = NULL;
	if (XGetWindowProperty (ctx->dpy, root, ctx->net_active_window,
		0L, 1L, false, XA_WINDOW, &dummy_type, &dummy_format,
		&nitems, &dummy_bytes, &p) != Success)
		return;

	char *new_title = NULL;
	if (nitems)
	{
		Window active_window = *(Window *) p;
		XFree (p);

		if (ctx->current_window != active_window && ctx->current_window)
			XSelectInput (ctx->dpy, ctx->current_window, 0);

		XSelectInput (ctx->dpy, active_window, PropertyChangeMask);
		new_title = x_window_title (ctx, active_window);
		ctx->current_window = active_window;
	}
	if (update_window_title (ctx, new_title))
		print_status ("Window changed: %s",
			ctx->current_title ? ctx->current_title : "(none)");
}

static void
on_x_property_notify (struct app_context *ctx, XPropertyEvent *ev)
{
	// This is from the EWMH specification, set by the window manager
	if (ev->atom == ctx->net_active_window)
		update_current_window (ctx);
	else if (ev->window == ctx->current_window && ev->atom == ctx->net_wm_name)
	{
		if (update_window_title (ctx, x_window_title (ctx, ev->window)))
			print_status ("Title changed: %s", ctx->current_title);
	}
}

static void
set_idle_alarm (struct app_context *ctx,
	XSyncAlarm *alarm, XSyncTestType test, XSyncValue value)
{
	XSyncAlarmAttributes attr;
	attr.trigger.counter = ctx->idle_counter;
	attr.trigger.test_type = test;
	attr.trigger.wait_value = value;
	XSyncIntToValue (&attr.delta, 0);

	long flags = XSyncCACounter | XSyncCATestType | XSyncCAValue | XSyncCADelta;
	if (*alarm)
		XSyncChangeAlarm (ctx->dpy, *alarm, flags, &attr);
	else
		*alarm = XSyncCreateAlarm (ctx->dpy, flags, &attr);
}

static void
on_x_alarm_notify (struct app_context *ctx, XSyncAlarmNotifyEvent *ev)
{
	if (ev->alarm == ctx->idle_alarm_inactive)
	{
		print_status ("User is inactive");

		XSyncValue one, minus_one;
		XSyncIntToValue (&one, 1);

		Bool overflow;
		XSyncValueSubtract (&minus_one, ev->counter_value, one, &overflow);

		// Set an alarm for IDLETIME <= current_idletime - 1
		set_idle_alarm (ctx, &ctx->idle_alarm_active,
			XSyncNegativeComparison, minus_one);
	}
	else if (ev->alarm == ctx->idle_alarm_active)
	{
		print_status ("User is active");
		set_idle_alarm (ctx, &ctx->idle_alarm_inactive,
			XSyncPositiveComparison, ctx->idle_timeout);
	}
}

static void
on_x_ready (const struct pollfd *pfd, void *user_data)
{
	(void) pfd;
	struct app_context *ctx = user_data;

	XEvent ev;
	while (XPending (ctx->dpy))
	{
		if (XNextEvent (ctx->dpy, &ev))
			exit_fatal ("XNextEvent returned non-zero");
		else if (ev.type == PropertyNotify)
			on_x_property_notify (ctx, &ev.xproperty);
		else if (ev.type == ctx->xsync_base_event_code + XSyncAlarmNotify)
			on_x_alarm_notify (ctx, (XSyncAlarmNotifyEvent *) &ev);
	}
}

static XErrorHandler g_default_x_error_handler;

static int
on_x_error (Display *dpy, XErrorEvent *ee)
{
	// This just is going to happen since those windows aren't ours
	if (ee->error_code == BadWindow)
		return 0;

	return g_default_x_error_handler (dpy, ee);
}

static void
init_events (struct app_context *ctx)
{
	Window root = DefaultRootWindow (ctx->dpy);
	XSelectInput (ctx->dpy, root, PropertyChangeMask);
	XSync (ctx->dpy, False);

	g_default_x_error_handler = XSetErrorHandler (on_x_error);

	unsigned long n;
	const char *timeout = str_map_find (&ctx->config, "idle_timeout");
	if (!xstrtoul (&n, timeout, 10) || !n || n > INT_MAX / 1000)
		exit_fatal ("invalid value for the idle timeout");
	XSyncIntToValue (&ctx->idle_timeout, n * 1000);

	update_current_window (ctx);
	set_idle_alarm (ctx, &ctx->idle_alarm_inactive,
		XSyncPositiveComparison, ctx->idle_timeout);

	ctx->x_event.dispatcher = on_x_ready;
	ctx->x_event.user_data = ctx;
	poller_fd_set (&ctx->x_event, POLLIN);
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

int
main (int argc, char *argv[])
{
	g_log_message_real = log_message_custom;

	static const struct opt opts[] =
	{
		{ 'd', "debug", NULL, 0, "run in debug mode" },
		{ 'h', "help", NULL, 0, "display this help and exit" },
		{ 'V', "version", NULL, 0, "output version information and exit" },
		{ 'w', "write-default-cfg", "FILENAME",
		  OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
		  "write a default configuration file and exit" },
		{ 0, NULL, NULL, 0, NULL }
	};

	struct opt_handler oh;
	opt_handler_init (&oh, argc, argv, opts, NULL, "Activity tracker.");

	int c;
	while ((c = opt_handler_get (&oh)) != -1)
	switch (c)
	{
	case 'd':
		g_debug_mode = true;
		break;
	case 'h':
		opt_handler_usage (&oh, stdout);
		exit (EXIT_SUCCESS);
	case 'V':
		printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
		exit (EXIT_SUCCESS);
	case 'w':
		call_simple_config_write_default (optarg, g_config_table);
		exit (EXIT_SUCCESS);
	default:
		print_error ("wrong options");
		opt_handler_usage (&oh, stderr);
		exit (EXIT_FAILURE);
	}

	argc -= optind;
	argv += optind;

	opt_handler_free (&oh);

	if (!setlocale (LC_CTYPE, ""))
		exit_fatal ("cannot set locale");
	if (!XSupportsLocale ())
		exit_fatal ("locale not supported by Xlib");

	struct app_context ctx;
	app_context_init (&ctx);

	struct error *e = NULL;
	if (!simple_config_update_from_file (&ctx.config, &e))
		exit_fatal ("%s", e->message);

	init_events (&ctx);

	ctx.running = true;
	while (ctx.running)
		poller_run (&ctx.poller);

	app_context_free (&ctx);
	return 0;
}