]> git.sur5r.net Git - i3/i3status/blob - i3status.c
Merge pull request #94 from rpls/master
[i3/i3status] / i3status.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3status – Generates a status line for dzen2 or xmobar
5  *
6  * Copyright © 2008 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 <limits.h>
15 #include <string.h>
16 #include <stdio.h>
17 #include <stdbool.h>
18 #include <unistd.h>
19 #include <stdlib.h>
20 #include <sys/socket.h>
21 #include <netinet/in.h>
22 #include <getopt.h>
23 #include <signal.h>
24 #include <confuse.h>
25 #include <glob.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <time.h>
29 #include <sys/time.h>
30 #include <locale.h>
31
32 #include <yajl/yajl_gen.h>
33 #include <yajl/yajl_version.h>
34
35 #include "i3status.h"
36
37 #define exit_if_null(pointer, ...) \
38     {                              \
39         if (pointer == NULL)       \
40             die(__VA_ARGS__);      \
41     }
42
43 #define CFG_CUSTOM_ALIGN_OPT \
44     CFG_STR_CB("align", NULL, CFGF_NONE, parse_align)
45
46 #define CFG_COLOR_OPTS(good, degraded, bad)             \
47     CFG_STR("color_good", good, CFGF_NONE),             \
48         CFG_STR("color_degraded", degraded, CFGF_NONE), \
49         CFG_STR("color_bad", bad, CFGF_NONE)
50
51 #define CFG_CUSTOM_COLOR_OPTS CFG_COLOR_OPTS(NULL, NULL, NULL)
52
53 #define CFG_CUSTOM_MIN_WIDTH_OPT \
54     CFG_PTR_CB("min_width", NULL, CFGF_NONE, parse_min_width, free)
55
56 /* socket file descriptor for general purposes */
57 int general_socket;
58
59 static bool exit_upon_signal = false;
60
61 cfg_t *cfg, *cfg_general, *cfg_section;
62
63 void **cur_instance;
64
65 pthread_cond_t i3status_sleep_cond = PTHREAD_COND_INITIALIZER;
66 pthread_mutex_t i3status_sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
67
68 /*
69  * Set the exit_upon_signal flag, because one cannot do anything in a safe
70  * manner in a signal handler (e.g. fprintf, which we really want to do for
71  * debugging purposes), see
72  * https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers
73  *
74  */
75 void fatalsig(int signum) {
76     exit_upon_signal = true;
77 }
78
79 /*
80  * Do nothing upon SIGUSR1. Running this signal handler will nevertheless
81  * interrupt nanosleep() so that i3status immediately generates new output.
82  *
83  */
84 void sigusr1(int signum) {
85     pthread_cond_broadcast(&i3status_sleep_cond);
86 }
87
88 /*
89  * Checks if the given path exists by calling stat().
90  *
91  */
92 static bool path_exists(const char *path) {
93     struct stat buf;
94     return (stat(path, &buf) == 0);
95 }
96
97 static void *scalloc(size_t size) {
98     void *result = calloc(size, 1);
99     exit_if_null(result, "Error: out of memory (calloc(%zd))\n", size);
100     return result;
101 }
102
103 static char *sstrdup(const char *str) {
104     char *result = strdup(str);
105     exit_if_null(result, "Error: out of memory (strdup())\n");
106     return result;
107 }
108
109 /*
110  * Parses the "align" module option (to validate input).
111  */
112 static int parse_align(cfg_t *context, cfg_opt_t *option, const char *value, void *result) {
113     if (strcasecmp(value, "left") != 0 && strcasecmp(value, "right") != 0 && strcasecmp(value, "center") != 0)
114         die("Invalid alignment attribute found in section %s, line %d: \"%s\"\n"
115             "Valid attributes are: left, center, right\n",
116             context->name, context->line, value);
117
118     const char **cresult = result;
119     *cresult = value;
120
121     return 0;
122 }
123
124 /*
125  * Parses the "min_width" module option whose value can either be a string or an integer.
126  */
127 static int parse_min_width(cfg_t *context, cfg_opt_t *option, const char *value, void *result) {
128     char *end;
129     long num = strtol(value, &end, 10);
130
131     if (num < 0)
132         die("Invalid min_width attribute found in section %s, line %d: %d\n"
133             "Expected positive integer or string\n",
134             context->name, context->line, num);
135     else if (num == LONG_MIN || num == LONG_MAX || (end && *end != '\0'))
136         num = 0;
137
138     if (strlen(value) == 0)
139         die("Empty min_width attribute found in section %s, line %d\n"
140             "Expected positive integer or non-empty string\n",
141             context->name, context->line);
142
143     if (strcmp(value, "0") == 0)
144         die("Invalid min_width attribute found in section %s, line %d: \"%s\"\n"
145             "Expected positive integer or string\n",
146             context->name, context->line, value);
147
148     struct min_width *parsed = scalloc(sizeof(struct min_width));
149     parsed->num = num;
150
151     /* num is preferred, but if it’s 0 (i.e. not valid), store and use
152      * the raw string value */
153     if (num == 0)
154         parsed->str = sstrdup(value);
155
156     struct min_width **cresult = result;
157     *cresult = parsed;
158
159     return 0;
160 }
161
162 /*
163  * Validates a color in "#RRGGBB" format
164  *
165  */
166 static int valid_color(const char *value) {
167     const int len = strlen(value);
168
169     if (output_format == O_LEMONBAR) {
170         /* lemonbar supports an optional alpha channel */
171         if (len != strlen("#rrggbb") && len != strlen("#aarrggbb")) {
172             return 0;
173         }
174     } else {
175         if (len != strlen("#rrggbb")) {
176             return 0;
177         }
178     }
179     if (value[0] != '#')
180         return 0;
181     for (int i = 1; i < len; ++i) {
182         if (value[i] >= '0' && value[i] <= '9')
183             continue;
184         if (value[i] >= 'a' && value[i] <= 'f')
185             continue;
186         if (value[i] >= 'A' && value[i] <= 'F')
187             continue;
188         return 0;
189     }
190     return 1;
191 }
192
193 /*
194  * This function resolves ~ in pathnames.
195  * It may resolve wildcards in the first part of the path, but if no match
196  * or multiple matches are found, it just returns a copy of path as given.
197  *
198  */
199 static char *resolve_tilde(const char *path) {
200     static glob_t globbuf;
201     char *head, *tail, *result = NULL;
202
203     tail = strchr(path, '/');
204     head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
205
206     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
207     free(head);
208     /* no match, or many wildcard matches are bad */
209     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
210         result = sstrdup(path);
211     else if (res != 0) {
212         die("glob() failed");
213     } else {
214         head = globbuf.gl_pathv[0];
215         result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
216         strncpy(result, head, strlen(head));
217         if (tail)
218             strncat(result, tail, strlen(tail));
219     }
220     globfree(&globbuf);
221
222     return result;
223 }
224
225 static char *get_config_path(void) {
226     char *xdg_config_home, *xdg_config_dirs, *config_path;
227
228     /* 1: check the traditional path under the home directory */
229     config_path = resolve_tilde("~/.i3status.conf");
230     if (path_exists(config_path))
231         return config_path;
232
233     /* 2: check for $XDG_CONFIG_HOME/i3status/config */
234     if ((xdg_config_home = getenv("XDG_CONFIG_HOME")) == NULL)
235         xdg_config_home = "~/.config";
236
237     xdg_config_home = resolve_tilde(xdg_config_home);
238     if (asprintf(&config_path, "%s/i3status/config", xdg_config_home) == -1)
239         die("asprintf() failed");
240     free(xdg_config_home);
241
242     if (path_exists(config_path))
243         return config_path;
244     free(config_path);
245
246     /* 3: check the traditional path under /etc */
247     config_path = SYSCONFDIR "/i3status.conf";
248     if (path_exists(config_path))
249         return sstrdup(config_path);
250
251     /* 4: check for $XDG_CONFIG_DIRS/i3status/config */
252     if ((xdg_config_dirs = getenv("XDG_CONFIG_DIRS")) == NULL)
253         xdg_config_dirs = "/etc/xdg";
254
255     char *buf = strdup(xdg_config_dirs);
256     char *tok = strtok(buf, ":");
257     while (tok != NULL) {
258         tok = resolve_tilde(tok);
259         if (asprintf(&config_path, "%s/i3status/config", tok) == -1)
260             die("asprintf() failed");
261         free(tok);
262         if (path_exists(config_path)) {
263             free(buf);
264             return config_path;
265         }
266         free(config_path);
267         tok = strtok(NULL, ":");
268     }
269     free(buf);
270
271     die("Unable to find the configuration file (looked at "
272         "~/.i3status.conf, $XDG_CONFIG_HOME/i3status/config, "
273         "/etc/i3status.conf and $XDG_CONFIG_DIRS/i3status/config)");
274     return NULL;
275 }
276
277 /*
278  * Returns the default separator to use if no custom separator has been specified.
279  */
280 static char *get_default_separator() {
281     if (output_format == O_DZEN2)
282         return "^p(5;-2)^ro(2)^p()^p(5)";
283     if (output_format == O_I3BAR)
284         // anything besides the empty string indicates that the default separator should be used
285         return "default";
286     return " | ";
287 }
288
289 int main(int argc, char *argv[]) {
290     unsigned int j;
291
292     cfg_opt_t general_opts[] = {
293         CFG_STR("output_format", "auto", CFGF_NONE),
294         CFG_BOOL("colors", 1, CFGF_NONE),
295         CFG_STR("separator", "default", CFGF_NONE),
296         CFG_STR("color_separator", "#333333", CFGF_NONE),
297         CFG_INT("interval", 1, CFGF_NONE),
298         CFG_COLOR_OPTS("#00FF00", "#FFFF00", "#FF0000"),
299         CFG_STR("markup", "none", CFGF_NONE),
300         CFG_END()};
301
302     cfg_opt_t run_watch_opts[] = {
303         CFG_STR("pidfile", NULL, CFGF_NONE),
304         CFG_STR("format", "%title: %status", CFGF_NONE),
305         CFG_STR("format_down", NULL, CFGF_NONE),
306         CFG_CUSTOM_ALIGN_OPT,
307         CFG_CUSTOM_COLOR_OPTS,
308         CFG_CUSTOM_MIN_WIDTH_OPT,
309         CFG_END()};
310
311     cfg_opt_t path_exists_opts[] = {
312         CFG_STR("path", NULL, CFGF_NONE),
313         CFG_STR("format", "%title: %status", CFGF_NONE),
314         CFG_STR("format_down", NULL, CFGF_NONE),
315         CFG_CUSTOM_ALIGN_OPT,
316         CFG_CUSTOM_COLOR_OPTS,
317         CFG_CUSTOM_MIN_WIDTH_OPT,
318         CFG_END()};
319
320     cfg_opt_t wireless_opts[] = {
321         CFG_STR("format_up", "W: (%quality at %essid, %bitrate) %ip", CFGF_NONE),
322         CFG_STR("format_down", "W: down", CFGF_NONE),
323         CFG_CUSTOM_ALIGN_OPT,
324         CFG_CUSTOM_COLOR_OPTS,
325         CFG_CUSTOM_MIN_WIDTH_OPT,
326         CFG_END()};
327
328     cfg_opt_t ethernet_opts[] = {
329         CFG_STR("format_up", "E: %ip (%speed)", CFGF_NONE),
330         CFG_STR("format_down", "E: down", CFGF_NONE),
331         CFG_CUSTOM_ALIGN_OPT,
332         CFG_CUSTOM_COLOR_OPTS,
333         CFG_CUSTOM_MIN_WIDTH_OPT,
334         CFG_END()};
335
336     cfg_opt_t ipv6_opts[] = {
337         CFG_STR("format_up", "%ip", CFGF_NONE),
338         CFG_STR("format_down", "no IPv6", CFGF_NONE),
339         CFG_CUSTOM_ALIGN_OPT,
340         CFG_CUSTOM_COLOR_OPTS,
341         CFG_CUSTOM_MIN_WIDTH_OPT,
342         CFG_END()};
343
344     cfg_opt_t battery_opts[] = {
345         CFG_STR("format", "%status %percentage %remaining", CFGF_NONE),
346         CFG_STR("format_down", "No battery", CFGF_NONE),
347         CFG_STR("status_chr", "CHR", CFGF_NONE),
348         CFG_STR("status_bat", "BAT", CFGF_NONE),
349         CFG_STR("status_full", "FULL", CFGF_NONE),
350         CFG_STR("path", "/sys/class/power_supply/BAT%d/uevent", CFGF_NONE),
351         CFG_INT("low_threshold", 30, CFGF_NONE),
352         CFG_STR("threshold_type", "time", CFGF_NONE),
353         CFG_BOOL("last_full_capacity", false, CFGF_NONE),
354         CFG_BOOL("integer_battery_capacity", false, CFGF_NONE),
355         CFG_BOOL("hide_seconds", false, CFGF_NONE),
356         CFG_CUSTOM_ALIGN_OPT,
357         CFG_CUSTOM_COLOR_OPTS,
358         CFG_CUSTOM_MIN_WIDTH_OPT,
359         CFG_END()};
360
361     cfg_opt_t time_opts[] = {
362         CFG_STR("format", "%Y-%m-%d %H:%M:%S", CFGF_NONE),
363         CFG_CUSTOM_ALIGN_OPT,
364         CFG_CUSTOM_MIN_WIDTH_OPT,
365         CFG_END()};
366
367     cfg_opt_t tztime_opts[] = {
368         CFG_STR("format", "%Y-%m-%d %H:%M:%S %Z", CFGF_NONE),
369         CFG_STR("timezone", "", CFGF_NONE),
370         CFG_STR("format_time", NULL, CFGF_NONE),
371         CFG_CUSTOM_ALIGN_OPT,
372         CFG_CUSTOM_MIN_WIDTH_OPT,
373         CFG_END()};
374
375     cfg_opt_t ddate_opts[] = {
376         CFG_STR("format", "%{%a, %b %d%}, %Y%N - %H", CFGF_NONE),
377         CFG_CUSTOM_ALIGN_OPT,
378         CFG_CUSTOM_MIN_WIDTH_OPT,
379         CFG_END()};
380
381     cfg_opt_t load_opts[] = {
382         CFG_STR("format", "%1min %5min %15min", CFGF_NONE),
383         CFG_FLOAT("max_threshold", 5, CFGF_NONE),
384         CFG_CUSTOM_ALIGN_OPT,
385         CFG_CUSTOM_COLOR_OPTS,
386         CFG_CUSTOM_MIN_WIDTH_OPT,
387         CFG_END()};
388
389     cfg_opt_t usage_opts[] = {
390         CFG_STR("format", "%usage", CFGF_NONE),
391         CFG_CUSTOM_ALIGN_OPT,
392         CFG_CUSTOM_MIN_WIDTH_OPT,
393         CFG_END()};
394
395     cfg_opt_t temp_opts[] = {
396         CFG_STR("format", "%degrees C", CFGF_NONE),
397         CFG_STR("path", NULL, CFGF_NONE),
398         CFG_INT("max_threshold", 75, CFGF_NONE),
399         CFG_CUSTOM_ALIGN_OPT,
400         CFG_CUSTOM_COLOR_OPTS,
401         CFG_CUSTOM_MIN_WIDTH_OPT,
402         CFG_END()};
403
404     cfg_opt_t disk_opts[] = {
405         CFG_STR("format", "%free", CFGF_NONE),
406         CFG_STR("format_not_mounted", NULL, CFGF_NONE),
407         CFG_STR("prefix_type", "binary", CFGF_NONE),
408         CFG_STR("threshold_type", "percentage_avail", CFGF_NONE),
409         CFG_FLOAT("low_threshold", 0, CFGF_NONE),
410         CFG_CUSTOM_ALIGN_OPT,
411         CFG_CUSTOM_COLOR_OPTS,
412         CFG_CUSTOM_MIN_WIDTH_OPT,
413         CFG_END()};
414
415     cfg_opt_t volume_opts[] = {
416         CFG_STR("format", "♪: %volume", CFGF_NONE),
417         CFG_STR("format_muted", "♪: 0%%", CFGF_NONE),
418         CFG_STR("device", "default", CFGF_NONE),
419         CFG_STR("mixer", "Master", CFGF_NONE),
420         CFG_INT("mixer_idx", 0, CFGF_NONE),
421         CFG_CUSTOM_ALIGN_OPT,
422         CFG_CUSTOM_COLOR_OPTS,
423         CFG_CUSTOM_MIN_WIDTH_OPT,
424         CFG_END()};
425
426     cfg_opt_t opts[] = {
427         CFG_STR_LIST("order", "{}", CFGF_NONE),
428         CFG_SEC("general", general_opts, CFGF_NONE),
429         CFG_SEC("run_watch", run_watch_opts, CFGF_TITLE | CFGF_MULTI),
430         CFG_SEC("path_exists", path_exists_opts, CFGF_TITLE | CFGF_MULTI),
431         CFG_SEC("wireless", wireless_opts, CFGF_TITLE | CFGF_MULTI),
432         CFG_SEC("ethernet", ethernet_opts, CFGF_TITLE | CFGF_MULTI),
433         CFG_SEC("battery", battery_opts, CFGF_TITLE | CFGF_MULTI),
434         CFG_SEC("cpu_temperature", temp_opts, CFGF_TITLE | CFGF_MULTI),
435         CFG_SEC("disk", disk_opts, CFGF_TITLE | CFGF_MULTI),
436         CFG_SEC("volume", volume_opts, CFGF_TITLE | CFGF_MULTI),
437         CFG_SEC("ipv6", ipv6_opts, CFGF_NONE),
438         CFG_SEC("time", time_opts, CFGF_NONE),
439         CFG_SEC("tztime", tztime_opts, CFGF_TITLE | CFGF_MULTI),
440         CFG_SEC("ddate", ddate_opts, CFGF_NONE),
441         CFG_SEC("load", load_opts, CFGF_NONE),
442         CFG_SEC("cpu_usage", usage_opts, CFGF_NONE),
443         CFG_END()};
444
445     char *configfile = NULL;
446     int o, option_index = 0;
447     struct option long_options[] = {
448         {"config", required_argument, 0, 'c'},
449         {"help", no_argument, 0, 'h'},
450         {"version", no_argument, 0, 'v'},
451         {0, 0, 0, 0}};
452
453     struct sigaction action;
454     memset(&action, 0, sizeof(struct sigaction));
455     action.sa_handler = fatalsig;
456
457     /* Exit upon SIGPIPE because when we have nowhere to write to, gathering system
458      * information is pointless. Also exit explicitly on SIGTERM and SIGINT because
459      * only this will trigger a reset of the cursor in the terminal output-format.
460      */
461     sigaction(SIGPIPE, &action, NULL);
462     sigaction(SIGTERM, &action, NULL);
463     sigaction(SIGINT, &action, NULL);
464
465     memset(&action, 0, sizeof(struct sigaction));
466     action.sa_handler = sigusr1;
467     sigaction(SIGUSR1, &action, NULL);
468
469     if (setlocale(LC_ALL, "") == NULL)
470         die("Could not set locale. Please make sure all your LC_* / LANG settings are correct.");
471
472     while ((o = getopt_long(argc, argv, "c:hv", long_options, &option_index)) != -1)
473         if ((char)o == 'c')
474             configfile = optarg;
475         else if ((char)o == 'h') {
476             printf("i3status " VERSION " © 2008 Michael Stapelberg and contributors\n"
477                    "Syntax: %s [-c <configfile>] [-h] [-v]\n",
478                    argv[0]);
479             return 0;
480         } else if ((char)o == 'v') {
481             printf("i3status " VERSION " © 2008 Michael Stapelberg and contributors\n");
482             return 0;
483         }
484
485     if (configfile == NULL)
486         configfile = get_config_path();
487
488     cfg = cfg_init(opts, CFGF_NOCASE);
489     if (cfg_parse(cfg, configfile) == CFG_PARSE_ERROR)
490         return EXIT_FAILURE;
491
492     if (cfg_size(cfg, "order") == 0)
493         die("Your 'order' array is empty. Please fix your config.\n");
494
495     cfg_general = cfg_getsec(cfg, "general");
496     if (cfg_general == NULL)
497         die("Could not get section \"general\"\n");
498
499     char *output_str = cfg_getstr(cfg_general, "output_format");
500     if (strcasecmp(output_str, "auto") == 0) {
501         fprintf(stderr, "i3status: trying to auto-detect output_format setting\n");
502         output_str = auto_detect_format();
503         if (!output_str) {
504             output_str = "none";
505             fprintf(stderr, "i3status: falling back to \"none\"\n");
506         } else {
507             fprintf(stderr, "i3status: auto-detected \"%s\"\n", output_str);
508         }
509     }
510
511     if (strcasecmp(output_str, "dzen2") == 0)
512         output_format = O_DZEN2;
513     else if (strcasecmp(output_str, "xmobar") == 0)
514         output_format = O_XMOBAR;
515     else if (strcasecmp(output_str, "i3bar") == 0)
516         output_format = O_I3BAR;
517     else if (strcasecmp(output_str, "lemonbar") == 0)
518         output_format = O_LEMONBAR;
519     else if (strcasecmp(output_str, "term") == 0)
520         output_format = O_TERM;
521     else if (strcasecmp(output_str, "none") == 0)
522         output_format = O_NONE;
523     else
524         die("Unknown output format: \"%s\"\n", output_str);
525
526     const char *separator = cfg_getstr(cfg_general, "separator");
527
528     /* lemonbar needs % to be escaped with another % */
529     pct_mark = (output_format == O_LEMONBAR) ? "%%" : "%";
530
531     // if no custom separator has been provided, use the default one
532     if (strcasecmp(separator, "default") == 0)
533         separator = get_default_separator();
534
535     if (!valid_color(cfg_getstr(cfg_general, "color_good")) || !valid_color(cfg_getstr(cfg_general, "color_degraded")) || !valid_color(cfg_getstr(cfg_general, "color_bad")) || !valid_color(cfg_getstr(cfg_general, "color_separator")))
536         die("Bad color format");
537
538     char *markup_str = cfg_getstr(cfg_general, "markup");
539     if (strcasecmp(markup_str, "pango") == 0)
540         markup_format = M_PANGO;
541     else if (strcasecmp(markup_str, "none") == 0)
542         markup_format = M_NONE;
543     else
544         die("Unknown markup format: \"%s\"\n", markup_str);
545
546 #if YAJL_MAJOR >= 2
547     yajl_gen json_gen = yajl_gen_alloc(NULL);
548 #else
549     yajl_gen json_gen = yajl_gen_alloc(NULL, NULL);
550 #endif
551
552     if (output_format == O_I3BAR) {
553         /* Initialize the i3bar protocol. See i3/docs/i3bar-protocol
554          * for details. */
555         printf("{\"version\":1}\n[\n");
556         fflush(stdout);
557         yajl_gen_array_open(json_gen);
558         yajl_gen_clear(json_gen);
559     }
560     if (output_format == O_TERM) {
561         /* Save the cursor-position and hide the cursor */
562         printf("\033[s\033[?25l");
563         /* Undo at exit */
564         atexit(&reset_cursor);
565     }
566
567     if ((general_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
568         die("Could not create socket\n");
569
570     int interval = cfg_getint(cfg_general, "interval");
571
572     /* One memory page which each plugin can use to buffer output.
573      * Even though it’s unclean, we just assume that the user will not
574      * specify a format string which expands to something longer than 4096
575      * bytes — given that the output of i3status is used to display
576      * information on screen, more than 1024 characters for the full line
577      * (!), not individual plugins, seem very unlikely. */
578     char buffer[4096];
579
580     void **per_instance = calloc(cfg_size(cfg, "order"), sizeof(*per_instance));
581     pthread_mutex_lock(&i3status_sleep_mutex);
582
583     while (1) {
584         if (exit_upon_signal) {
585             fprintf(stderr, "Exiting due to signal.\n");
586             exit(1);
587         }
588         struct timeval tv;
589         gettimeofday(&tv, NULL);
590         if (output_format == O_I3BAR)
591             yajl_gen_array_open(json_gen);
592         else if (output_format == O_TERM)
593             /* Restore the cursor-position, clear line */
594             printf("\033[u\033[K");
595         for (j = 0; j < cfg_size(cfg, "order"); j++) {
596             cur_instance = per_instance + j;
597             if (j > 0)
598                 print_separator(separator);
599
600             const char *current = cfg_getnstr(cfg, "order", j);
601
602             CASE_SEC("ipv6") {
603                 SEC_OPEN_MAP("ipv6");
604                 print_ipv6_info(json_gen, buffer, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
605                 SEC_CLOSE_MAP;
606             }
607
608             CASE_SEC_TITLE("wireless") {
609                 SEC_OPEN_MAP("wireless");
610                 const char *interface = NULL;
611                 if (strcasecmp(title, "_first_") == 0)
612                     interface = first_eth_interface(NET_TYPE_WIRELESS);
613                 if (interface == NULL)
614                     interface = title;
615                 print_wireless_info(json_gen, buffer, interface, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
616                 SEC_CLOSE_MAP;
617             }
618
619             CASE_SEC_TITLE("ethernet") {
620                 SEC_OPEN_MAP("ethernet");
621                 const char *interface = NULL;
622                 if (strcasecmp(title, "_first_") == 0)
623                     interface = first_eth_interface(NET_TYPE_ETHERNET);
624                 if (interface == NULL)
625                     interface = title;
626                 print_eth_info(json_gen, buffer, interface, cfg_getstr(sec, "format_up"), cfg_getstr(sec, "format_down"));
627                 SEC_CLOSE_MAP;
628             }
629
630             CASE_SEC_TITLE("battery") {
631                 SEC_OPEN_MAP("battery");
632                 print_battery_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"), cfg_getstr(sec, "status_chr"), cfg_getstr(sec, "status_bat"), cfg_getstr(sec, "status_full"), cfg_getint(sec, "low_threshold"), cfg_getstr(sec, "threshold_type"), cfg_getbool(sec, "last_full_capacity"), cfg_getbool(sec, "integer_battery_capacity"), cfg_getbool(sec, "hide_seconds"));
633                 SEC_CLOSE_MAP;
634             }
635
636             CASE_SEC_TITLE("run_watch") {
637                 SEC_OPEN_MAP("run_watch");
638                 print_run_watch(json_gen, buffer, title, cfg_getstr(sec, "pidfile"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"));
639                 SEC_CLOSE_MAP;
640             }
641
642             CASE_SEC_TITLE("path_exists") {
643                 SEC_OPEN_MAP("path_exists");
644                 print_path_exists(json_gen, buffer, title, cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getstr(sec, "format_down"));
645                 SEC_CLOSE_MAP;
646             }
647
648             CASE_SEC_TITLE("disk") {
649                 SEC_OPEN_MAP("disk_info");
650                 print_disk_info(json_gen, buffer, title, cfg_getstr(sec, "format"), cfg_getstr(sec, "format_not_mounted"), cfg_getstr(sec, "prefix_type"), cfg_getstr(sec, "threshold_type"), cfg_getfloat(sec, "low_threshold"));
651                 SEC_CLOSE_MAP;
652             }
653
654             CASE_SEC("load") {
655                 SEC_OPEN_MAP("load");
656                 print_load(json_gen, buffer, cfg_getstr(sec, "format"), cfg_getfloat(sec, "max_threshold"));
657                 SEC_CLOSE_MAP;
658             }
659
660             CASE_SEC("time") {
661                 SEC_OPEN_MAP("time");
662                 print_time(json_gen, buffer, NULL, cfg_getstr(sec, "format"), NULL, NULL, tv.tv_sec);
663                 SEC_CLOSE_MAP;
664             }
665
666             CASE_SEC_TITLE("tztime") {
667                 SEC_OPEN_MAP("tztime");
668                 print_time(json_gen, buffer, title, cfg_getstr(sec, "format"), cfg_getstr(sec, "timezone"), cfg_getstr(sec, "format_time"), tv.tv_sec);
669                 SEC_CLOSE_MAP;
670             }
671
672             CASE_SEC("ddate") {
673                 SEC_OPEN_MAP("ddate");
674                 print_ddate(json_gen, buffer, cfg_getstr(sec, "format"), tv.tv_sec);
675                 SEC_CLOSE_MAP;
676             }
677
678             CASE_SEC_TITLE("volume") {
679                 SEC_OPEN_MAP("volume");
680                 print_volume(json_gen, buffer, cfg_getstr(sec, "format"),
681                              cfg_getstr(sec, "format_muted"),
682                              cfg_getstr(sec, "device"),
683                              cfg_getstr(sec, "mixer"),
684                              cfg_getint(sec, "mixer_idx"));
685                 SEC_CLOSE_MAP;
686             }
687
688             CASE_SEC_TITLE("cpu_temperature") {
689                 SEC_OPEN_MAP("cpu_temperature");
690                 print_cpu_temperature_info(json_gen, buffer, atoi(title), cfg_getstr(sec, "path"), cfg_getstr(sec, "format"), cfg_getint(sec, "max_threshold"));
691                 SEC_CLOSE_MAP;
692             }
693
694             CASE_SEC("cpu_usage") {
695                 SEC_OPEN_MAP("cpu_usage");
696                 print_cpu_usage(json_gen, buffer, cfg_getstr(sec, "format"));
697                 SEC_CLOSE_MAP;
698             }
699         }
700         if (output_format == O_I3BAR) {
701             yajl_gen_array_close(json_gen);
702             const unsigned char *buf;
703 #if YAJL_MAJOR >= 2
704             size_t len;
705 #else
706             unsigned int len;
707 #endif
708             yajl_gen_get_buf(json_gen, &buf, &len);
709             write(STDOUT_FILENO, buf, len);
710             yajl_gen_clear(json_gen);
711         }
712
713         printf("\n");
714         fflush(stdout);
715
716         /* To provide updates on every full second (as good as possible)
717          * we don’t use sleep(interval) but we sleep until the next second.
718          * We also align to 60 seconds modulo interval such
719          * that we start with :00 on every new minute. */
720         struct timespec ts;
721 #if defined(__APPLE__)
722         gettimeofday(&tv, NULL);
723         ts.tv_sec = tv.tv_sec;
724 #else
725         clock_gettime(CLOCK_REALTIME, &ts);
726 #endif
727         ts.tv_sec += interval - (ts.tv_sec % interval);
728         ts.tv_nsec = 0;
729
730         /* Sleep to absolute time 'ts', unless the condition
731          * 'i3status_sleep_cond' is signaled from another thread */
732         pthread_cond_timedwait(&i3status_sleep_cond, &i3status_sleep_mutex, &ts);
733     }
734 }