Xinqi Bao's Git

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