Xinqi Bao's Git

Rewrite Makefile to accomodate file split
[slstatus.git] / slstatus.c
1 /* See LICENSE file for copyright and license details. */
2 #include <err.h>
3 #include <errno.h>
4 #include <locale.h>
5 #include <signal.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <time.h>
10 #include <X11/Xlib.h>
11
12 #include "arg.h"
13 #include "util.h"
14
15 struct arg {
16 const char *(*func)();
17 const char *fmt;
18 const char *args;
19 };
20
21 char *argv0;
22 static unsigned short int done;
23 static Display *dpy;
24
25 #include "slstatus.h"
26 #include "config.h"
27
28 static void
29 terminate(const int signo)
30 {
31 done = 1;
32 }
33
34 static void
35 difftimespec(struct timespec *res, struct timespec *a, struct timespec *b)
36 {
37 res->tv_sec = a->tv_sec - b->tv_sec - (a->tv_nsec < b->tv_nsec);
38 res->tv_nsec = a->tv_nsec - b->tv_nsec +
39 (a->tv_nsec < b->tv_nsec) * 1000000000;
40 }
41
42 static void
43 usage(void)
44 {
45 fprintf(stderr, "usage: %s [-s]\n", argv0);
46 exit(1);
47 }
48
49 int
50 main(int argc, char *argv[])
51 {
52 struct sigaction act;
53 struct timespec start, current, diff, intspec, wait;
54 size_t i, len;
55 int sflag = 0;
56 char status[MAXLEN];
57
58 ARGBEGIN {
59 case 's':
60 sflag = 1;
61 break;
62 default:
63 usage();
64 } ARGEND
65
66 if (argc) {
67 usage();
68 }
69
70 setlocale(LC_ALL, "");
71
72 memset(&act, 0, sizeof(act));
73 act.sa_handler = terminate;
74 sigaction(SIGINT, &act, NULL);
75 sigaction(SIGTERM, &act, NULL);
76
77 if (!sflag && !(dpy = XOpenDisplay(NULL))) {
78 fprintf(stderr, "slstatus: cannot open display");
79 return 1;
80 }
81
82 while (!done) {
83 clock_gettime(CLOCK_MONOTONIC, &start);
84
85 status[0] = '\0';
86 for (i = len = 0; i < LEN(args); i++) {
87 len += snprintf(status + len, sizeof(status) - len,
88 args[i].fmt, args[i].func(args[i].args));
89
90 if (len >= sizeof(status)) {
91 status[sizeof(status) - 1] = '\0';
92 }
93 }
94
95 if (sflag) {
96 printf("%s\n", status);
97 } else {
98 XStoreName(dpy, DefaultRootWindow(dpy), status);
99 XSync(dpy, False);
100 }
101
102 if (!done) {
103 clock_gettime(CLOCK_MONOTONIC, &current);
104 difftimespec(&diff, &current, &start);
105
106 intspec.tv_sec = interval / 1000;
107 intspec.tv_nsec = (interval % 1000) * 1000000;
108 difftimespec(&wait, &intspec, &diff);
109
110 if (wait.tv_sec >= 0) {
111 nanosleep(&wait, NULL);
112 }
113 }
114 }
115
116 if (!sflag) {
117 XStoreName(dpy, DefaultRootWindow(dpy), NULL);
118 XCloseDisplay(dpy);
119 }
120
121 return 0;
122 }