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