aboutsummaryrefslogtreecommitdiffstats
path: root/dwmclock.c
blob: cc4b5b25d09d2dbbbad99b9fab82c070fe4fd947 (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
#define _GNU_SOURCE

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


int stop = 0;

#ifdef BATTERY
int getnum(char *fn)
{
	char buf[1024];
	FILE *f;
	int len;

	f = fopen(fn, "r");
	if (!f) {
		return -1;
	}
	len = fread(buf, 1, 1023, f);
	if (ferror(f)) {
		return -1;
	}
	fclose(f);
	if (len > 1022 || len < 1) {
		return -1;
	}
	buf[1023] = '\0';

	return atoi(buf);
}
#endif

void handler(int sig)
{
	stop = sig;
}

int main(void)
{
	struct tm *tm;
	time_t now;
#ifdef BATTERY
	long long curr, max, a=-1, b=-1, i;
	char name[8 + 9]; /* (p)pp.pp% hh:mm:ss\0 */
	char *perc = name;
	char *clock = name + 8;
#else
	char name[9]; /* hh:mm:ss\0 */
	char *clock = name;
#endif
	struct sigaction act;
	Display *disp;
	int screen;
	Window root;

	act.sa_handler = handler;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGHUP, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGQUIT, &act, NULL);
	sigaction(SIGTERM, &act, NULL);


	disp = XOpenDisplay(NULL);
#ifdef BATTERY
	for (i=0; !stop; ++i) {
#else
	while (!stop) {
#endif
		if (!disp) {
			puts("Cannot open display!");
			return 1;
		}
		screen = DefaultScreen(disp);
		root = RootWindow(disp, screen);
#ifdef BATTERY
		if (i % (BAT_REFRESH_SECONDS) == 0) {
			curr = getnum(ENERGY_NOW) * MUL;
			max = getnum(ENERGY_FULL);
			if (curr < 0 || max < 1) {
				a = b = -1;
			} else {
				a = curr * 10000 / max;
				b = a % 100;
				a /= 100;
			}
		}

		if (a < 0 || b < 0) {
			snprintf(perc, 8, "NO BAT ");
		} else if (a < 0 || a > 999999 || b < 0 || b > 99) {
			snprintf(perc, 8, "INVALID");
		} else if (a > 999) {
			snprintf(perc, 8, "%6lld%%", a);
		} else {
			snprintf(perc, 8, "%3lld.%02lld%%", a, b);
		}
		perc[7] = ' ';
#endif

		now = time(NULL);
		tm = localtime(&now);
		strftime(clock, 9, "%H:%M:%S", tm);

		XStoreName(disp, root, name);
		XFlush(disp);
		sleep(1);
	}
	XCloseDisplay(disp);


	return 0;
}