X-Git-Url: https://git.xinqibao.xyz/slstatus.git/blobdiff_plain/00ce7a746ab0630e7d3b84288307435c6d62610a..6f011743921db04e5513df45c5ac4b2c752d52de:/slstatus.c diff --git a/slstatus.c b/slstatus.c index 052af87..47bd4c9 100644 --- a/slstatus.c +++ b/slstatus.c @@ -28,6 +28,8 @@ #include "arg.h" +#define LEN(x) (sizeof (x) / sizeof *(x)) + struct arg { const char *(*func)(); const char *fmt; @@ -142,10 +144,19 @@ battery_power(const char *bat) static const char * battery_state(const char *bat) { - char path[PATH_MAX]; - char state[12]; FILE *fp; + struct { + char *state; + char *symbol; + } map[] = { + { "Charging", "+" }, + { "Discharging", "-" }, + { "Full", "=" }, + { "Unknown", "/" }, + }; + size_t i; int n; + char path[PATH_MAX], state[12]; snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/", bat, "/status"); fp = fopen(path, "r"); @@ -158,17 +169,13 @@ battery_state(const char *bat) if (n != 1) return UNKNOWN_STR; - if (strcmp(state, "Charging") == 0) { - return "+"; - } else if (strcmp(state, "Discharging") == 0) { - return "-"; - } else if (strcmp(state, "Full") == 0) { - return "="; - } else if (strcmp(state, "Unknown") == 0) { - return "/"; - } else { - return "?"; + for (i = 0; i < LEN(map); i++) { + if (!strcmp(map[i].state, state)) { + break; + } } + + return (i == LEN(map)) ? "?" : map[i].symbol; } static const char * @@ -373,10 +380,9 @@ kernel_release(void) static const char * keyboard_indicators(void) { - Display *dpy = XOpenDisplay(NULL); XKeyboardState state; + XGetKeyboardControl(dpy, &state); - XCloseDisplay(dpy); switch (state.led_mask) { case 1: @@ -740,7 +746,7 @@ vol_perc(const char *card) close(afd); return UNKNOWN_STR; } - for (i = 0; i < (sizeof(vnames) / sizeof((vnames[0]))); i++) { + for (i = 0; i < LEN(vnames); i++) { if (devmask & (1 << i) && !strcmp("vol", vnames[i])) { if (ioctl(afd, MIXER_READ(i), &v) == -1) { warn("vol_perc: ioctl"); @@ -872,6 +878,10 @@ main(int argc, char *argv[]) if (!sflag) { dpy = XOpenDisplay(NULL); + if (!dpy) { + fprintf(stderr, "slstatus: cannot open display"); + exit(1); + } } setlocale(LC_ALL, ""); @@ -879,8 +889,7 @@ main(int argc, char *argv[]) while (!done) { status_string[0] = '\0'; - for (element = status_string, i = len = 0; - i < sizeof(args) / sizeof(args[0]); + for (element = status_string, i = len = 0; i < LEN(args); ++i, element += len) { argument = args[i]; len = snprintf(element, sizeof(status_string)-1 - len,