aboutsummaryrefslogtreecommitdiff
path: root/daemons/spaced.c
blob: 0729266dd531a4f0adce423ec61cbcd79d072870 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// spaced — desktop space daemon for bar
//
// Monitors the active desktop space and posts a Darwin notification
// when the space changes. Uses a lightweight 0.5s poll of a CoreGraphics
// private API.
//
// Compile:
//   cc -o bar-spaced daemons/spaced.c -framework CoreFoundation

#include <CoreFoundation/CoreFoundation.h>
#include <dlfcn.h>
#include <notify.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static volatile int keep_running = 1;

// Private CoreGraphics API
typedef CFStringRef (*CGSCopyActiveMenuBarDisplayIdentifierFunc)(void);

static CGSCopyActiveMenuBarDisplayIdentifierFunc copyIdentifier = NULL;

static void handle_signal(int sig) {
	(void)sig;
	keep_running = 0;
}

int main(void) {
	signal(SIGINT, handle_signal);
	signal(SIGTERM, handle_signal);

	// Load the private CGS API at runtime
	void *handle = dlopen(
		"/System/Library/PrivateFrameworks/CoreGraphics.framework/CoreGraphics",
		RTLD_LAZY | RTLD_LOCAL);

	if (!handle) {
		fprintf(stderr, "bar-spaced: could not load CoreGraphics framework\n");
		return 1;
	}

	copyIdentifier = (CGSCopyActiveMenuBarDisplayIdentifierFunc)
		dlsym(handle, "CGSCopyActiveMenuBarDisplayIdentifier");

	if (!copyIdentifier) {
		fprintf(stderr, "bar-spaced: could not find CGS API\n");
		dlclose(handle);
		return 1;
	}

	CFStringRef last = NULL;
	unsigned int pollCount = 0;

	while (keep_running) {
		CFStringRef current = copyIdentifier();

		if (current) {
			if (!last || !CFEqual(current, last)) {
				notify_post("bar.touch.<block-name>");
				if (last) CFRelease(last);
				last = CFStringCreateCopy(NULL, current);
			}
			CFRelease(current);
		}

		usleep(500000); // 0.5 second intervals
		pollCount++;
	}

	if (last) CFRelease(last);
	dlclose(handle);
	return 0;
}