]> git.sur5r.net Git - i3/i3status/blob - i3status.c
Add colorized output for load avg
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or xmobar
5  *
6  * Copyright © 2008-2012 Michael Stapelberg and contributors
7  * Copyright © 2009 Thorsten Toepper <atsutane at freethoughts dot de>
8  * Copyright © 2010 Axel Wagner <mail at merovius dot de>
9  * Copyright © 2010 Fernando Tarlá Cardoso Lemos <fernandotcl at gmail dot com>
10  *
11  * See file LICENSE for license information.
12  *
13  */
14 #include <string.h>
15 #include <stdio.h>
16 #include <stdbool.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <getopt.h>
22 #include <signal.h>
23 #include <confuse.h>
24 #include <glob.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <time.h>
28 #include <sys/time.h>
29 #include <locale.h>
30
31 #include <yajl/yajl_gen.h>
32 #include <yajl/yajl_version.h>
33
34 #include "i3status.h"
35
36 #define exit_if_null(pointer, ...) { if (pointer == NULL) die(__VA_ARGS__); }
37
38 #define CFG_COLOR_OPTS(good, degraded, bad) \
39     CFG_STR("color_good", good, CFGF_NONE), \
40     CFG_STR("color_degraded", degraded, CFGF_NONE), \
41     CFG_STR("color_bad", bad, CFGF_NONE)
42
43 #define CFG_CUSTOM_COLOR_OPTS CFG_COLOR_OPTS(NULL, NULL, NULL)
44
45 /* socket file descriptor for general purposes */
46 int general_socket;
47
48 cfg_t *cfg, *cfg_general, *cfg_section;
49
50 /*
51  * Exit upon SIGPIPE because when we have nowhere to write to, gathering
52  * system information is pointless.
53  *
54  */
55 void sigpipe(int signum) {
56         fprintf(stderr, "Received SIGPIPE, exiting\n");
57         exit(1);
58 }
59
60 /*
61  * Do nothing upon SIGUSR1. Running this signal handler will nevertheless
62  * interrupt nanosleep() so that i3status immediately generates new output.
63  *
64  */
65 void sigusr1(int signum) {
66 }
67
68 /*
69  * Checks if the given path exists by calling stat().
70  *
71  */
72 static bool path_exists(const char *path) {
73         struct stat buf;
74         return (stat(path, &buf) == 0);
75 }
76
77 static void *scalloc(size_t size) {
78         void *result = calloc(size, 1);
79         exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
80         return result;
81 }
82
83 static char *sstrdup(const char *str) {
84         char *result = strdup(str);
85         exit_if_null(result, "Error: out of memory (strdup())\n");
86         return result;
87 }
88
89
90 /*
91  * Validates a color in "#RRGGBB" format
92  *
93  */
94 static int valid_color(const char *value)
95 {
96         if (strlen(value) != 7) return 0;
97         if (value[0] != '#') return 0;
98         for (int i = 1; i < 7; ++i) {
99                 if (value[i] >= '0' && value[i] <= '9') continue;
100                 if (value[i] >= 'a' && value[i] <= 'f') continue;
101                 if (value[i] >= 'A' && value[i] <= 'F') continue;
102                 return 0;
103         }
104         return 1;
105 }
106
107 /*
108  * This function resolves ~ in pathnames.
109  * It may resolve wildcards in the first part of the path, but if no match
110  * or multiple matches are found, it just returns a copy of path as given.
111  *
112  */
113 static char *resolve_tilde(const char *path) {
114         static glob_t globbuf;
115         char *head, *tail, *result = NULL;
116
117         tail = strchr(path, '/');
118         head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
119
120         int res = glob(head, GLOB_TILDE, NULL, &globbuf);
121         free(head);
122         /* no match, or many wildcard matches are bad */
123         if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
124                 result = sstrdup(path);
125         else if (res != 0) {
126                 die("glob() failed");
127         } else {
128                 head = globbuf.gl_pathv[0];
129                 result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
130                 strncpy(result, head, strlen(head));
131                 if (tail)
132                         strncat(result, tail, strlen(tail));
133         }
134         globfree(&globbuf);
135
136         return result;
137 }
138
139 static char *get_config_path(void) {
140         char *xdg_config_home, *xdg_config_dirs, *config_path;
141
142         /* 1: check the traditional path under the home directory */
143         config_path = resolve_tilde("~/.i3status.conf");
144         if (path_exists(config_path))
145                 return config_path;
146
147         /* 2: check for $XDG_CONFIG_HOME/i3status/config */
148         if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL)
149                 xdg_config_home = "~/.config";
150
151         xdg_config_home = resolve_tilde(xdg_config_home);
152         if (asprintf(&config_path, "%s/i3status/config", xdg_config_home) == -1)
153                 die("asprintf() failed");
154         free(xdg_config_home);
155
156         if (path_exists(config_path))
157                 return config_path;
158         free(config_path);
159
160         /* 3: check the traditional path under /etc */
161         config_path = SYSCONFDIR "/i3status.conf";
162         if (path_exists(config_path))
163             return sstrdup(config_path);
164
165         /* 4: check for $XDG_CONFIG_DIRS/i3status/config */
166         if ((xdg_config_dirs = getenv("XDG_CONFIG_DIRS")) == NULL)
167                 xdg_config_dirs = "/etc/xdg";
168
169         char *buf = strdup(xdg_config_dirs);
170         char *tok = strtok(buf, ":");
171         while (tok != NULL) {
172                 tok = resolve_tilde(tok);
173                 if (asprintf(&config_path, "%s/i3status/config", tok) == -1)
174                         die("asprintf() failed");
175                 free(tok);
176                 if (path_exists(config_path)) {
177                         free(buf);
178                         return config_path;
179                 }
180                 free(config_path);
181                 tok = strtok(NULL, ":");
182         }
183         free(buf);
184
185         die("Unable to find the configuration file (looked at "
186                 "~/.i3status.conf, $XDG_CONFIG_HOME/i3status/config, "
187                 "/etc/i3status.conf and $XDG_CONFIG_DIRS/i3status/config)");
188         return NULL;
189 }
190
191 int main(int argc, char *argv[]) {
192         unsigned int j;
193
194         cfg_opt_t general_opts[] = {
195                 CFG_STR("output_format", "auto", CFGF_NONE),
196                 CFG_BOOL("colors", 1, CFGF_NONE),
197                 CFG_STR("color_separator", "#333333", CFGF_NONE),
198                 CFG_INT("interval", 1, CFGF_NONE),
199                 CFG_COLOR_OPTS("#00FF00", "#FFFF00", "#FF0000"),
200                 CFG_END()
201         };
202
203         cfg_opt_t run_watch_opts[] = {
204                 CFG_STR("pidfile", NULL, CFGF_NONE),
205                 CFG_STR("format", "%title: %status", CFGF_NONE),
206                 CFG_CUSTOM_COLOR_OPTS,
207                 CFG_END()
208         };
209
210         cfg_opt_t wireless_opts[] = {
211                 CFG_STR("format_up", "W: (%quality at %essid, %bitrate) %ip", CFGF_NONE),
212                 CFG_STR("format_down", "W: down", CFGF_NONE),
213                 CFG_CUSTOM_COLOR_OPTS,
214                 CFG_END()
215         };
216
217         cfg_opt_t ethernet_opts[] = {
218                 CFG_STR("format_up", "E: %ip (%speed)", CFGF_NONE),
219                 CFG_STR("format_down", "E: down", CFGF_NONE),
220                 CFG_CUSTOM_COLOR_OPTS,
221                 CFG_END()
222         };
223
224         cfg_opt_t ipv6_opts[] = {
225                 CFG_STR("format_up", "%ip", CFGF_NONE),
226                 CFG_STR("format_down", "no IPv6", CFGF_NONE),
227                 CFG_CUSTOM_COLOR_OPTS,
228                 CFG_END()
229         };
230
231         cfg_opt_t battery_opts[] = {
232                 CFG_STR("format", "%status %percentage %remaining", CFGF_NONE),
233                 CFG_STR("path", "/sys/class/power_supply/BAT%d/uevent", CFGF_NONE),
234                 CFG_INT("low_threshold", 30, CFGF_NONE),
235                 CFG_STR("threshold_type", "time", CFGF_NONE),
236                 CFG_BOOL("last_full_capacity", false, CFGF_NONE),
237                 CFG_BOOL("integer_battery_capacity", false, CFGF_NONE),
238                 CFG_CUSTOM_COLOR_OPTS,
239                 CFG_END()
240         };
241
242         cfg_opt_t time_opts[] = {
243                 CFG_STR("format", "%Y-%m-%d %H:%M:%S", CFGF_NONE),
244                 CFG_END()
245         };
246
247         cfg_opt_t tztime_opts[] = {
248                 CFG_STR("format", "%Y-%m-%d %H:%M:%S %Z", CFGF_NONE),
249                 CFG_STR("timezone", "", CFGF_NONE),
250                 CFG_END()
251         };
252
253         cfg_opt_t ddate_opts[] = {
254                 CFG_STR("format", "%{%a, %b %d%}, %Y%N - %H", CFGF_NONE),
255                 CFG_END()
256         };
257
258         cfg_opt_t load_opts[] = {
259                 CFG_STR("format", "%1min %5min %15min", CFGF_NONE),
260                 CFG_INT("max_threshold", 5, CFGF_NONE),
261                 CFG_CUSTOM_COLOR_OPTS,
262                 CFG_END()
263         };
264
265         cfg_opt_t usage_opts[] = {
266                 CFG_STR("format", "%usage", CFGF_NONE),
267                 CFG_END()
268         };
269
270         cfg_opt_t temp_opts[] = {
271                 CFG_STR("format", "%degrees C", CFGF_NONE),
272                 CFG_STR("path", NULL, CFGF_NONE),
273                 CFG_INT("max_threshold", 75, CFGF_NONE),
274                 CFG_CUSTOM_COLOR_OPTS,
275                 CFG_END()
276         };
277
278         cfg_opt_t disk_opts[] = {
279                 CFG_STR("format", "%free", CFGF_NONE),
280                 CFG_END()
281         };
282
283         cfg_opt_t volume_opts[] = {
284                 CFG_STR("format", "♪: %volume", CFGF_NONE),
285                 CFG_STR("device", "default", CFGF_NONE),
286                 CFG_STR("mixer", "Master", CFGF_NONE),
287                 CFG_INT("mixer_idx", 0, CFGF_NONE),
288                 CFG_CUSTOM_COLOR_OPTS,
289                 CFG_END()
290         };
291
292         cfg_opt_t opts[] = {
293                 CFG_STR_LIST("order", "{}", CFGF_NONE),
294                 CFG_SEC("general", general_opts, CFGF_NONE),
295                 CFG_SEC("run_watch", run_watch_opts, CFGF_TITLE | CFGF_MULTI),
296                 CFG_SEC("wireless", wireless_opts, CFGF_TITLE | CFGF_MULTI),
297                 CFG_SEC("ethernet", ethernet_opts, CFGF_TITLE | CFGF_MULTI),
298                 CFG_SEC("battery", battery_opts, CFGF_TITLE | CFGF_MULTI),
299                 CFG_SEC("cpu_temperature", temp_opts, CFGF_TITLE | CFGF_MULTI),
300                 CFG_SEC("disk", disk_opts, CFGF_TITLE | CFGF_MULTI),
301                 CFG_SEC("volume", volume_opts, CFGF_TITLE | CFGF_MULTI),
302                 CFG_SEC("ipv6", ipv6_opts, CFGF_NONE),
303                 CFG_SEC("time", time_opts, CFGF_NONE),
304                 CFG_SEC("tztime", tztime_opts, CFGF_TITLE | CFGF_MULTI),
305                 CFG_SEC("ddate", ddate_opts, CFGF_NONE),
306                 CFG_SEC("load", load_opts, CFGF_NONE),
307                 CFG_SEC("cpu_usage", usage_opts, CFGF_NONE),
308                 CFG_CUSTOM_COLOR_OPTS,
309                 CFG_END()
310         };
311
312         char *configfile = NULL;
313         int o, option_index = 0;
314         struct option long_options[] = {
315                 {"config", required_argument, 0, 'c'},
316                 {"help", no_argument, 0, 'h'},
317                 {"version", no_argument, 0, 'v'},
318                 {0, 0, 0, 0}
319         };
320
321         struct sigaction action;
322         memset(&action, 0, sizeof(struct sigaction));
323         action.sa_handler = sigpipe;
324         sigaction(SIGPIPE, &action, NULL);
325
326         memset(&action, 0, sizeof(struct sigaction));
327         action.sa_handler = sigusr1;
328         sigaction(SIGUSR1, &action, NULL);
329
330         if (setlocale(LC_ALL, "") == NULL)
331                 die("Could not set locale. Please make sure all your LC_* / LANG settings are correct.");
332
333         while ((o = getopt_long(argc, argv, "c:hv", long_options, &option_index)) != -1)
334                 if ((char)o == 'c')
335                         configfile = optarg;
336                 else if ((char)o == 'h') {
337                         printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n"
338                                 "Syntax: %s [-c <configfile>] [-h] [-v]\n", argv[0]);
339                         return 0;
340                 } else if ((char)o == 'v') {
341                         printf("i3status " VERSION " © 2008-2012 Michael Stapelberg and contributors\n");
342                         return 0;
343                 }
344
345
346         if (configfile == NULL)
347                 configfile = get_config_path();
348
349         cfg = cfg_init(opts, CFGF_NOCASE);
350         if (cfg_parse(cfg, configfile) == CFG_PARSE_ERROR)
351                 return EXIT_FAILURE;
352
353         if (cfg_size(cfg, "order") == 0)
354                 die("Your 'order' array is empty. Please fix your config.\n");
355
356         cfg_general = cfg_getsec(cfg, "general");
357         if (cfg_general == NULL)
358                 die("Could not get section \"general\"\n");
359
360         char *output_str = cfg_getstr(cfg_general, "output_format");
361         if (strcasecmp(output_str, "auto") == 0) {
362                 fprintf(stderr, "i3status: trying to auto-detect output_format setting\n");
363                 output_str = auto_detect_format();
364                 if (!output_str) {
365                         output_str = "none";
366                         fprintf(stderr, "i3status: falling back to \"none\"\n");
367                 } else {
368                         fprintf(stderr, "i3status: auto-detected \"%s\"\n", output_str);
369                 }
370         }
371
372         if (strcasecmp(output_str, "dzen2") == 0)
373                 output_format = O_DZEN2;
374         else if (strcasecmp(output_str, "xmobar") == 0)
375                 output_format = O_XMOBAR;
376         else if (strcasecmp(output_str, "i3bar") == 0)
377                 output_format = O_I3BAR;
378         else if (strcasecmp(output_str, "none") == 0)
379                 output_format = O_NONE;
380         else die("Unknown output format: \"%s\"\n", output_str);
381
382         if (!valid_color(cfg_getstr(cfg_general, "color_good"))
383                         || !valid_color(cfg_getstr(cfg_general, "color_degraded"))
384                         || !valid_color(cfg_getstr(cfg_general, "color_bad"))
385                         || !valid_color(cfg_getstr(cfg_general, "color_separator")))
386                die("Bad color format");
387
388 #if YAJL_MAJOR >= 2
389         yajl_gen json_gen = yajl_gen_alloc(NULL);
390 #else
391         yajl_gen json_gen = yajl_gen_alloc(NULL, NULL);
392 #endif
393
394         if (output_format == O_I3BAR) {
395                 /* Initialize the i3bar protocol. See i3/docs/i3bar-protocol
396                  * for details. */
397                 printf("{\"version\":1}\n[\n");
398                 fflush(stdout);
399                 yajl_gen_array_open(json_gen);
400                 yajl_gen_clear(json_gen);
401         }
402
403         if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
404                 die("Could not create socket\n");
405
406         int interval = cfg_getint(cfg_general, "interval");
407
408         /* One memory page which each plugin can use to buffer output.
409          * Even though it’s unclean, we just assume that the user will not
410          * specify a format string which expands to something longer than 4096
411          * bytes — given that the output of i3status is used to display
412          * information on screen, more than 1024 characters for the full line
413          * (!), not individual plugins, seem very unlikely. */
414         char buffer[4096];
415
416         while (1) {
417                 struct timeval tv;
418                 gettimeofday(&tv, NULL);
419                 if (output_format == O_I3BAR)
420                         yajl_gen_array_open(json_gen);
421                 for (j = 0; j < cfg_size(cfg, "order"); j++) {
422                         if (j > 0)
423                                 print_seperator();
424
425                         const char *current = cfg_getnstr(cfg, "order", j);
426
427                         CASE_SEC("ipv6") {
428                                 SEC_OPEN_MAP("ipv6");
429                                 print_ipv6_info(json_gen, buffer, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
430                                 SEC_CLOSE_MAP;
431                         }
432
433                         CASE_SEC_TITLE("wireless") {
434                                 SEC_OPEN_MAP("wireless");
435                                 print_wireless_info(json_gen, buffer, title, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
436                                 SEC_CLOSE_MAP;
437                         }
438
439                         CASE_SEC_TITLE("ethernet") {
440                                 SEC_OPEN_MAP("ethernet");
441                                 print_eth_info(json_gen, buffer, title, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
442                                 SEC_CLOSE_MAP;
443                         }
444
445                         CASE_SEC_TITLE("battery") {
446                                 SEC_OPEN_MAP("battery");
447                                 print_battery_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "low_threshold"), cfg_getstr(sec, "threshold_type"), cfg_getbool(sec, "last_full_capacity"), cfg_getbool(sec, "integer_battery_capacity"));
448                                 SEC_CLOSE_MAP;
449                         }
450
451                         CASE_SEC_TITLE("run_watch") {
452                                 SEC_OPEN_MAP("run_watch");
453                                 print_run_watch(json_gen, buffer, title, cfg_getstr(sec, "pidfile"), cfg_getstr(sec, "format"));
454                                 SEC_CLOSE_MAP;
455                         }
456
457                         CASE_SEC_TITLE("disk") {
458                                 SEC_OPEN_MAP("disk_info");
459                                 print_disk_info(json_gen, buffer, title, cfg_getstr(sec, "format"));
460                                 SEC_CLOSE_MAP;
461                         }
462
463                         CASE_SEC("load") {
464                                 SEC_OPEN_MAP("load");
465                                 print_load(json_gen, buffer, cfg_getstr(sec, "format"), cfg_getint(sec, "max_threshold"));
466                                 SEC_CLOSE_MAP;
467                         }
468
469                         CASE_SEC("time") {
470                                 SEC_OPEN_MAP("time");
471                                 print_time(json_gen, buffer, cfg_getstr(sec, "format"), NULL, tv.tv_sec);
472                                 SEC_CLOSE_MAP;
473                         }
474
475                         CASE_SEC_TITLE("tztime") {
476                                 SEC_OPEN_MAP("tztime");
477                                 print_time(json_gen, buffer, cfg_getstr(sec, "format"), cfg_getstr(sec, "timezone"), tv.tv_sec);
478                                 SEC_CLOSE_MAP;
479                         }
480
481                         CASE_SEC("ddate") {
482                                 SEC_OPEN_MAP("ddate");
483                                 print_ddate(json_gen, buffer, cfg_getstr(sec, "format"), tv.tv_sec);
484                                 SEC_CLOSE_MAP;
485                         }
486
487                         CASE_SEC_TITLE("volume") {
488                                 SEC_OPEN_MAP("volume");
489                                 print_volume(json_gen, buffer, cfg_getstr(sec, "format"),
490                                              cfg_getstr(sec, "device"),
491                                              cfg_getstr(sec, "mixer"),
492                                              cfg_getint(sec, "mixer_idx"));
493                                 SEC_CLOSE_MAP;
494                         }
495
496                         CASE_SEC_TITLE("cpu_temperature") {
497                                 SEC_OPEN_MAP("cpu_temperature");
498                                 print_cpu_temperature_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "max_threshold"));
499                                 SEC_CLOSE_MAP;
500                         }
501
502                         CASE_SEC("cpu_usage") {
503                                 SEC_OPEN_MAP("cpu_usage");
504                                 print_cpu_usage(json_gen, buffer, cfg_getstr(sec, "format"));
505                                 SEC_CLOSE_MAP;
506                         }
507                 }
508                 if (output_format == O_I3BAR) {
509                         yajl_gen_array_close(json_gen);
510                         const unsigned char *buf;
511 #if YAJL_MAJOR >= 2
512                         size_t len;
513 #else
514                         unsigned int len;
515 #endif
516                         yajl_gen_get_buf(json_gen, &buf, &len);
517                         write(STDOUT_FILENO, buf, len);
518                         yajl_gen_clear(json_gen);
519                 }
520
521                 printf("\n");
522                 fflush(stdout);
523
524                 /* To provide updates on every full second (as good as possible)
525                  * we don’t use sleep(interval) but we sleep until the next
526                  * second (with microsecond precision) plus (interval-1)
527                  * seconds. We also align to 60 seconds modulo interval such
528                  * that we start with :00 on every new minute. */
529                 struct timeval current_timeval;
530                 gettimeofday(&current_timeval, NULL);
531                 struct timespec ts = {interval - 1 - (current_timeval.tv_sec % interval), (10e5 - current_timeval.tv_usec) * 1000};
532                 nanosleep(&ts, NULL);
533         }
534 }