diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/first_network_device.c | 53 | ||||
| -rw-r--r-- | src/general.c | 50 | ||||
| -rw-r--r-- | src/output.c | 79 | ||||
| -rw-r--r-- | src/print_battery_info.c | 1064 | ||||
| -rw-r--r-- | src/print_cpu_temperature.c | 325 | ||||
| -rw-r--r-- | src/print_cpu_usage.c | 110 | ||||
| -rw-r--r-- | src/print_ddate.c | 363 | ||||
| -rw-r--r-- | src/print_disk_info.c | 270 | ||||
| -rw-r--r-- | src/print_eth_info.c | 175 | ||||
| -rw-r--r-- | src/print_ip_addr.c | 73 | ||||
| -rw-r--r-- | src/print_ipv6_addr.c | 218 | ||||
| -rw-r--r-- | src/print_load.c | 82 | ||||
| -rw-r--r-- | src/print_path_exists.c | 41 | ||||
| -rw-r--r-- | src/print_run_watch.c | 39 | ||||
| -rw-r--r-- | src/print_time.c | 52 | ||||
| -rw-r--r-- | src/print_volume.c | 287 | ||||
| -rw-r--r-- | src/print_wireless_info.c | 659 | ||||
| -rw-r--r-- | src/process_runs.c | 46 | 
18 files changed, 1982 insertions, 2004 deletions
diff --git a/src/first_network_device.c b/src/first_network_device.c index c160027..35cd4ff 100644 --- a/src/first_network_device.c +++ b/src/first_network_device.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <sys/stat.h>  #include <stdlib.h>  #include <ifaddrs.h> @@ -6,34 +6,33 @@  #include "i3status.h"  const char *first_eth_interface(const net_type_t type) { -        static char *interface = NULL; -        struct ifaddrs *ifaddr, *addrp; -        struct stat stbuf; -        static char path[1024]; +    static char *interface = NULL; +    struct ifaddrs *ifaddr, *addrp; +    struct stat stbuf; +    static char path[1024]; -        getifaddrs(&ifaddr); +    getifaddrs(&ifaddr); -        if (ifaddr == NULL) -                return NULL; +    if (ifaddr == NULL) +        return NULL; -        free(interface); -        interface = NULL; -        for (addrp = ifaddr; -             addrp != NULL; -             addrp = addrp->ifa_next) { -                if (strncasecmp("lo", addrp->ifa_name, strlen("lo")) == 0) -                        continue; -                // Skip this interface if it is a wireless interface. -                snprintf(path, sizeof(path), "/sys/class/net/%s/wireless", addrp->ifa_name); -                const bool is_wireless = (stat(path, &stbuf) == 0); -                if (( is_wireless && type == NET_TYPE_ETHERNET) || -                    (!is_wireless && type == NET_TYPE_WIRELESS)) -                        continue; -                interface = strdup(addrp->ifa_name); -                break; -        } +    free(interface); +    interface = NULL; +    for (addrp = ifaddr; +         addrp != NULL; +         addrp = addrp->ifa_next) { +        if (strncasecmp("lo", addrp->ifa_name, strlen("lo")) == 0) +            continue; +        // Skip this interface if it is a wireless interface. +        snprintf(path, sizeof(path), "/sys/class/net/%s/wireless", addrp->ifa_name); +        const bool is_wireless = (stat(path, &stbuf) == 0); +        if ((is_wireless && type == NET_TYPE_ETHERNET) || +            (!is_wireless && type == NET_TYPE_WIRELESS)) +            continue; +        interface = strdup(addrp->ifa_name); +        break; +    } -        freeifaddrs(ifaddr); -        return interface; +    freeifaddrs(ifaddr); +    return interface;  } - diff --git a/src/general.c b/src/general.c index c5b33b4..f299a2b 100644 --- a/src/general.c +++ b/src/general.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <sys/types.h>  #include <string.h>  #include <stdarg.h> @@ -15,18 +15,18 @@   *   */  bool slurp(const char *filename, char *destination, int size) { -        int fd; +    int fd; -        if ((fd = open(filename, O_RDONLY)) == -1) -                return false; +    if ((fd = open(filename, O_RDONLY)) == -1) +        return false; -        /* We need one byte for the trailing 0 byte */ -        int n = read(fd, destination, size-1); -        if (n != -1) -                destination[n] = '\0'; -        (void)close(fd); +    /* We need one byte for the trailing 0 byte */ +    int n = read(fd, destination, size - 1); +    if (n != -1) +        destination[n] = '\0'; +    (void)close(fd); -        return true; +    return true;  }  /* @@ -35,15 +35,15 @@ bool slurp(const char *filename, char *destination, int size) {   *   */  char *skip_character(char *input, char character, int amount) { -        char *walk; -        size_t len = strlen(input); -        int blanks = 0; +    char *walk; +    size_t len = strlen(input); +    int blanks = 0; -        for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++) -                if (*walk == character) -                        blanks++; +    for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++) +        if (*walk == character) +            blanks++; -        return (walk == input ? walk : walk-1); +    return (walk == input ? walk : walk - 1);  }  /* @@ -51,12 +51,12 @@ char *skip_character(char *input, char character, int amount) {   *   */  void die(const char *fmt, ...) { -        char buffer[512]; -        va_list ap; -        va_start(ap, fmt); -        (void)vsnprintf(buffer, sizeof(buffer), fmt, ap); -        va_end(ap); - -        fprintf(stderr, "%s", buffer); -        exit(EXIT_FAILURE); +    char buffer[512]; +    va_list ap; +    va_start(ap, fmt); +    (void)vsnprintf(buffer, sizeof(buffer), fmt, ap); +    va_end(ap); + +    fprintf(stderr, "%s", buffer); +    exit(EXIT_FAILURE);  } diff --git a/src/output.c b/src/output.c index 3a43d58..b2fb1dd 100644 --- a/src/output.c +++ b/src/output.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdbool.h>  #include <string.h>  #include <stdio.h> @@ -15,29 +15,29 @@   *   */  char *color(const char *colorstr) { -        static char colorbuf[32]; -        if (!cfg_getbool(cfg_general, "colors")) { -                colorbuf[0] = '\0'; -                return colorbuf; -        } -        if (output_format == O_DZEN2) -                (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", cfg_getstr(cfg_general, colorstr)); -        else if (output_format == O_XMOBAR) -                (void)snprintf(colorbuf, sizeof(colorbuf), "<fc=%s>", cfg_getstr(cfg_general, colorstr)); -        else if (output_format == O_TERM) { -                /* The escape-sequence for color is <CSI><col>;1m (bright/bold -                 * output), where col is a 3-bit rgb-value with b in the -                 * least-significant bit. We round the given color to the -                 * nearist 3-bit-depth color and output the escape-sequence */ -                char *str = cfg_getstr(cfg_general, colorstr); -                int col = strtol(str + 1, NULL, 16); -                int r = (col & (0xFF << 0)) / 0x80; -                int g = (col & (0xFF << 8)) / 0x8000; -                int b = (col & (0xFF << 16)) / 0x800000; -                col = (r << 2) | (g << 1) | b; -                (void)snprintf(colorbuf, sizeof(colorbuf), "\033[3%d;1m", col); -        } +    static char colorbuf[32]; +    if (!cfg_getbool(cfg_general, "colors")) { +        colorbuf[0] = '\0';          return colorbuf; +    } +    if (output_format == O_DZEN2) +        (void)snprintf(colorbuf, sizeof(colorbuf), "^fg(%s)", cfg_getstr(cfg_general, colorstr)); +    else if (output_format == O_XMOBAR) +        (void)snprintf(colorbuf, sizeof(colorbuf), "<fc=%s>", cfg_getstr(cfg_general, colorstr)); +    else if (output_format == O_TERM) { +        /* The escape-sequence for color is <CSI><col>;1m (bright/bold +         * output), where col is a 3-bit rgb-value with b in the +         * least-significant bit. We round the given color to the +         * nearist 3-bit-depth color and output the escape-sequence */ +        char *str = cfg_getstr(cfg_general, colorstr); +        int col = strtol(str + 1, NULL, 16); +        int r = (col & (0xFF << 0)) / 0x80; +        int g = (col & (0xFF << 8)) / 0x8000; +        int b = (col & (0xFF << 16)) / 0x800000; +        col = (r << 2) | (g << 1) | b; +        (void)snprintf(colorbuf, sizeof(colorbuf), "\033[3%d;1m", col); +    } +    return colorbuf;  }  /* @@ -45,30 +45,31 @@ char *color(const char *colorstr) {   *   */  char *endcolor(void) { -        if (output_format == O_XMOBAR) -                return "</fc>"; -        else if (output_format == O_TERM) -                return "\033[0m"; -        else return ""; +    if (output_format == O_XMOBAR) +        return "</fc>"; +    else if (output_format == O_TERM) +        return "\033[0m"; +    else +        return "";  }  void print_separator(const char *separator) { -        if (output_format == O_I3BAR || strlen(separator) == 0) -                return; +    if (output_format == O_I3BAR || strlen(separator) == 0) +        return; -        if (output_format == O_DZEN2) -                printf("^fg(%s)%s^fg()", cfg_getstr(cfg_general, "color_separator"), separator); -        else if (output_format == O_XMOBAR) -                printf("<fc=%s>%s</fc>", cfg_getstr(cfg_general, "color_separator"), separator); -        else if (output_format == O_TERM) -                printf("%s%s%s", color("color_separator"), separator, endcolor()); -        else if (output_format == O_NONE) -                printf("%s", separator); +    if (output_format == O_DZEN2) +        printf("^fg(%s)%s^fg()", cfg_getstr(cfg_general, "color_separator"), separator); +    else if (output_format == O_XMOBAR) +        printf("<fc=%s>%s</fc>", cfg_getstr(cfg_general, "color_separator"), separator); +    else if (output_format == O_TERM) +        printf("%s%s%s", color("color_separator"), separator, endcolor()); +    else if (output_format == O_NONE) +        printf("%s", separator);  }  /*   * The term-output hides the cursor. We call this on exit to reset that.   */  void reset_cursor(void) { -        printf("\033[?25h"); +    printf("\033[?25h");  } diff --git a/src/print_battery_info.c b/src/print_battery_info.c index 0df9b72..1126f57 100644 --- a/src/print_battery_info.c +++ b/src/print_battery_info.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <ctype.h>  #include <time.h>  #include <string.h> @@ -34,599 +34,583 @@   *   */  void print_battery_info(yajl_gen json_gen, char *buffer, int number, const char *path, const char *format, const char *format_down, const char *status_chr, const char *status_bat, const char *status_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) { -        time_t empty_time; -        struct tm *empty_tm; -        char buf[1024]; -        char statusbuf[16]; -        char percentagebuf[16]; -        char remainingbuf[256]; -        char emptytimebuf[256]; -        char consumptionbuf[256]; -        const char *walk, *last; -        char *outwalk = buffer; -        bool watt_as_unit = false; -        bool colorful_output = false; -        int full_design = -1, -            remaining = -1, -            present_rate = -1, -            voltage = -1; -        charging_status_t status = CS_DISCHARGING; - -        memset(statusbuf, '\0', sizeof(statusbuf)); -        memset(percentagebuf, '\0', sizeof(percentagebuf)); -        memset(remainingbuf, '\0', sizeof(remainingbuf)); -        memset(emptytimebuf, '\0', sizeof(emptytimebuf)); -        memset(consumptionbuf, '\0', sizeof(consumptionbuf)); - -        static char batpath[512]; -        sprintf(batpath, path, number); -        INSTANCE(batpath); +    time_t empty_time; +    struct tm *empty_tm; +    char buf[1024]; +    char statusbuf[16]; +    char percentagebuf[16]; +    char remainingbuf[256]; +    char emptytimebuf[256]; +    char consumptionbuf[256]; +    const char *walk, *last; +    char *outwalk = buffer; +    bool watt_as_unit = false; +    bool colorful_output = false; +    int full_design = -1, +        remaining = -1, +        present_rate = -1, +        voltage = -1; +    charging_status_t status = CS_DISCHARGING; + +    memset(statusbuf, '\0', sizeof(statusbuf)); +    memset(percentagebuf, '\0', sizeof(percentagebuf)); +    memset(remainingbuf, '\0', sizeof(remainingbuf)); +    memset(emptytimebuf, '\0', sizeof(emptytimebuf)); +    memset(consumptionbuf, '\0', sizeof(consumptionbuf)); + +    static char batpath[512]; +    sprintf(batpath, path, number); +    INSTANCE(batpath);  #define BATT_STATUS_NAME(status) \ -    (status == CS_CHARGING ? status_chr : \ -        (status == CS_DISCHARGING ? status_bat : status_full)) +    (status == CS_CHARGING ? status_chr : (status == CS_DISCHARGING ? status_bat : status_full))  #if defined(LINUX) -        if (!slurp(batpath, buf, sizeof(buf))) { -                OUTPUT_FULL_TEXT(format_down); -                return; +    if (!slurp(batpath, buf, sizeof(buf))) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    for (walk = buf, last = buf; (walk - buf) < 1024; walk++) { +        if (*walk == '\n') { +            last = walk + 1; +            continue;          } -        for (walk = buf, last = buf; (walk-buf) < 1024; walk++) { -                if (*walk == '\n') { -                        last = walk+1; -                        continue; -                } - -                if (*walk != '=') -                        continue; - -                if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW")) { -                        watt_as_unit = true; -                        remaining = atoi(walk+1); -                } -                else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW")) { -                        watt_as_unit = false; -                        remaining = atoi(walk+1); -                } -                else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW")) -                        present_rate = abs(atoi(walk+1)); -                else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW")) -                        voltage = abs(atoi(walk+1)); -                /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually -                 * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as -                 * unit instead of μAh. We will calculate it as we need it -                 * later. */ -                else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW")) -                        present_rate = abs(atoi(walk+1)); -                else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging")) -                        status = CS_CHARGING; -                else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full")) -                        status = CS_FULL; -                else { -                        /* The only thing left is the full capacity */ -                        if (last_full_capacity) { -                                if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") && -                                    !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL")) -                                        continue; -                        } else { -                                if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") && -                                    !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN")) -                                        continue; -                        } - -                        full_design = atoi(walk+1); -                } -        } - -        /* the difference between POWER_SUPPLY_ENERGY_NOW and -         * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is -         * given in mWh, the charge in mAh. So calculate every value given in -         * ampere to watt */ -        if (!watt_as_unit) { -            present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0)); - -            if (voltage != -1) { -                remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0)); -                full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0)); +        if (*walk != '=') +            continue; + +        if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW")) { +            watt_as_unit = true; +            remaining = atoi(walk + 1); +        } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW")) { +            watt_as_unit = false; +            remaining = atoi(walk + 1); +        } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW")) +            present_rate = abs(atoi(walk + 1)); +        else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW")) +            voltage = abs(atoi(walk + 1)); +        /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually +         * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as +         * unit instead of μAh. We will calculate it as we need it +         * later. */ +        else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW")) +            present_rate = abs(atoi(walk + 1)); +        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging")) +            status = CS_CHARGING; +        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full")) +            status = CS_FULL; +        else { +            /* The only thing left is the full capacity */ +            if (last_full_capacity) { +                if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") && +                    !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL")) +                    continue; +            } else { +                if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") && +                    !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN")) +                    continue;              } -        } -        if ((full_design == -1) || (remaining == -1)) { -                OUTPUT_FULL_TEXT(format_down); -                return; +            full_design = atoi(walk + 1);          } - -        (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); - -        float percentage_remaining = (((float)remaining / (float)full_design) * 100); -        if (integer_battery_capacity) { -                (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00f%%", percentage_remaining); -        } else { -                (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.02f%%", percentage_remaining); +    } + +    /* the difference between POWER_SUPPLY_ENERGY_NOW and +     * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is +     * given in mWh, the charge in mAh. So calculate every value given in +     * ampere to watt */ +    if (!watt_as_unit) { +        present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0)); + +        if (voltage != -1) { +            remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0)); +            full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));          } +    } -        if (present_rate > 0) { -                float remaining_time; -                int seconds, hours, minutes, seconds_remaining; -                if (status == CS_CHARGING) -                        remaining_time = ((float)full_design - (float)remaining) / (float)present_rate; -                else if (status == CS_DISCHARGING) -                        remaining_time = ((float)remaining / (float)present_rate); -                else remaining_time = 0; - -                seconds_remaining = (int)(remaining_time * 3600.0); - -                hours = seconds_remaining / 3600; -                seconds = seconds_remaining - (hours * 3600); -                minutes = seconds / 60; -                seconds -= (minutes * 60); - -                if (status == CS_DISCHARGING && low_threshold > 0) { -                        if (strcasecmp(threshold_type, "percentage") == 0 -                                && percentage_remaining < low_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } else if (strcasecmp(threshold_type, "time") == 0 -                                && seconds_remaining < 60 * low_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } else { -                            colorful_output = false; -                        } -                } - -                if (hide_seconds) -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", -                                max(hours, 0), max(minutes, 0)); -                else -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d", -                                max(hours, 0), max(minutes, 0), max(seconds, 0)); +    if ((full_design == -1) || (remaining == -1)) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } -                empty_time = time(NULL); -                empty_time += seconds_remaining; -                empty_tm = localtime(&empty_time); +    (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); -                if (hide_seconds) -                        (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d", -                                max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0)); -                else -                        (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d", -                                max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0)); - -                (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW", -                        ((float)present_rate / 1000.0 / 1000.0)); -        } else { -                /* On some systems, present_rate may not exist. Still, make sure -                 * we colorize the output if threshold_type is set to percentage -                 * (since we don't have any information on remaining time). */ -                if (status == CS_DISCHARGING && low_threshold > 0) { -                        if (strcasecmp(threshold_type, "percentage") == 0 -                                && percentage_remaining < low_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } -                } -        } -#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) -        int state; -        int sysctl_rslt; -        size_t sysctl_size = sizeof(sysctl_rslt); +    float percentage_remaining = (((float)remaining / (float)full_design) * 100); +    if (integer_battery_capacity) { +        (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00f%%", percentage_remaining); +    } else { +        (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.02f%%", percentage_remaining); +    } -        if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) { -                OUTPUT_FULL_TEXT(format_down); -                return; -        } +    if (present_rate > 0) { +        float remaining_time; +        int seconds, hours, minutes, seconds_remaining; +        if (status == CS_CHARGING) +            remaining_time = ((float)full_design - (float)remaining) / (float)present_rate; +        else if (status == CS_DISCHARGING) +            remaining_time = ((float)remaining / (float)present_rate); +        else +            remaining_time = 0; -        present_rate = sysctl_rslt; -        if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) { -                OUTPUT_FULL_TEXT(format_down); -                return; -        } +        seconds_remaining = (int)(remaining_time * 3600.0); -        remaining = sysctl_rslt; -        if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL,0) != 0) { -                OUTPUT_FULL_TEXT(format_down); -                return; +        hours = seconds_remaining / 3600; +        seconds = seconds_remaining - (hours * 3600); +        minutes = seconds / 60; +        seconds -= (minutes * 60); + +        if (status == CS_DISCHARGING && low_threshold > 0) { +            if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            } else { +                colorful_output = false; +            }          } -        state = sysctl_rslt; -        if (state == 0 && present_rate == 100) -                status = CS_FULL; -        else if (state == 0 && present_rate < 100) -                status = CS_CHARGING; +        if (hide_seconds) +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", +                           max(hours, 0), max(minutes, 0));          else -                status = CS_DISCHARGING; +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d", +                           max(hours, 0), max(minutes, 0), max(seconds, 0)); -        full_design = sysctl_rslt; +        empty_time = time(NULL); +        empty_time += seconds_remaining; +        empty_tm = localtime(&empty_time); -        (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); +        if (hide_seconds) +            (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d", +                           max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0)); +        else +            (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d", +                           max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0)); -        (void)snprintf(percentagebuf, sizeof(percentagebuf), "%02d%%", -                       present_rate); - -        if (state == 1) { -                int hours, minutes; -                minutes = remaining; -                hours = minutes / 60; -                minutes -= (hours * 60); -                (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02dh%02d", -                               max(hours, 0), max(minutes, 0)); -		if (strcasecmp(threshold_type, "percentage") == 0 -		    && present_rate < low_threshold) { -			START_COLOR("color_bad"); -			colorful_output = true; -		} else if (strcasecmp(threshold_type, "time") == 0 -			   && remaining < (u_int) low_threshold) { -			START_COLOR("color_bad"); -			colorful_output = true; -		} +        (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW", +                       ((float)present_rate / 1000.0 / 1000.0)); +    } else { +        /* On some systems, present_rate may not exist. Still, make sure +         * we colorize the output if threshold_type is set to percentage +         * (since we don't have any information on remaining time). */ +        if (status == CS_DISCHARGING && low_threshold > 0) { +            if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            } +        } +    } +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +    int state; +    int sysctl_rslt; +    size_t sysctl_size = sizeof(sysctl_rslt); + +    if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    present_rate = sysctl_rslt; +    if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    remaining = sysctl_rslt; +    if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    state = sysctl_rslt; +    if (state == 0 && present_rate == 100) +        status = CS_FULL; +    else if (state == 0 && present_rate < 100) +        status = CS_CHARGING; +    else +        status = CS_DISCHARGING; + +    full_design = sysctl_rslt; + +    (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); + +    (void)snprintf(percentagebuf, sizeof(percentagebuf), "%02d%%", +                   present_rate); + +    if (state == 1) { +        int hours, minutes; +        minutes = remaining; +        hours = minutes / 60; +        minutes -= (hours * 60); +        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02dh%02d", +                       max(hours, 0), max(minutes, 0)); +        if (strcasecmp(threshold_type, "percentage") == 0 && present_rate < low_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true; +        } else if (strcasecmp(threshold_type, "time") == 0 && remaining < (u_int)low_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true;          } +    }  #elif defined(__OpenBSD__) -	/* +    /*  	 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and  	 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and  	 * probing acpi(4) devices.  	 */ -	struct apm_power_info apm_info; -	int apm_fd; - -	apm_fd = open("/dev/apm", O_RDONLY); -	if (apm_fd < 0) { -		OUTPUT_FULL_TEXT("can't open /dev/apm"); -		return; -	} -	if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0) -		OUTPUT_FULL_TEXT("can't read power info"); - -	close(apm_fd); - -	/* Don't bother to go further if there's no battery present. */ -	if ((apm_info.battery_state == APM_BATTERY_ABSENT) || -	    (apm_info.battery_state == APM_BATT_UNKNOWN)) { -		OUTPUT_FULL_TEXT(format_down); -		return; -	} - -	switch(apm_info.ac_state) { -	case APM_AC_OFF: -		status = CS_DISCHARGING; -		break; -	case APM_AC_ON: -		status = CS_CHARGING; -		break; -	default: -		/* If we don't know what's going on, just assume we're discharging. */ -		status = CS_DISCHARGING; -		break; -	} - -	(void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); -	/* integer_battery_capacity is implied as battery_life is already in whole numbers. */ -	(void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00d%%", apm_info.battery_life); - -	if (status == CS_DISCHARGING && low_threshold > 0) { -		if (strcasecmp(threshold_type, "percentage") == 0 -		    && apm_info.battery_life < low_threshold) { -			START_COLOR("color_bad"); -			colorful_output = true; -		} else if (strcasecmp(threshold_type, "time") == 0 -			   && apm_info.minutes_left < (u_int) low_threshold) { -			START_COLOR("color_bad"); -			colorful_output = true; -		} -	} - -	/* Can't give a meaningful value for remaining minutes if we're charging. */ -	if (status != CS_CHARGING) { -		(void)snprintf(remainingbuf, sizeof(remainingbuf), "%d", apm_info.minutes_left); -	} else { -		(void)snprintf(remainingbuf, sizeof(remainingbuf), "%s", "(CHR)"); -	} - -	if (colorful_output) -		END_COLOR; -#elif defined(__NetBSD__) -        /* -         * Using envsys(4) via sysmon(4). -         */ -        int fd, rval, last_full_cap; -        bool is_found = false; -        char *sensor_desc; -        bool is_full = false; - -        prop_dictionary_t dict; -        prop_array_t array; -        prop_object_iterator_t iter; -        prop_object_iterator_t iter2; -        prop_object_t obj, obj2, obj3, obj4, obj5; - -        asprintf(&sensor_desc, "acpibat%d", number); - -        fd = open("/dev/sysmon", O_RDONLY); -        if (fd < 0) { -                OUTPUT_FULL_TEXT("can't open /dev/sysmon"); -                return; -        } - -        rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict); -        if (rval == -1) { -                close(fd); -                return; +    struct apm_power_info apm_info; +    int apm_fd; + +    apm_fd = open("/dev/apm", O_RDONLY); +    if (apm_fd < 0) { +        OUTPUT_FULL_TEXT("can't open /dev/apm"); +        return; +    } +    if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0) +        OUTPUT_FULL_TEXT("can't read power info"); + +    close(apm_fd); + +    /* Don't bother to go further if there's no battery present. */ +    if ((apm_info.battery_state == APM_BATTERY_ABSENT) || +        (apm_info.battery_state == APM_BATT_UNKNOWN)) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    switch (apm_info.ac_state) { +        case APM_AC_OFF: +            status = CS_DISCHARGING; +            break; +        case APM_AC_ON: +            status = CS_CHARGING; +            break; +        default: +            /* If we don't know what's going on, just assume we're discharging. */ +            status = CS_DISCHARGING; +            break; +    } + +    (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); +    /* integer_battery_capacity is implied as battery_life is already in whole numbers. */ +    (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00d%%", apm_info.battery_life); + +    if (status == CS_DISCHARGING && low_threshold > 0) { +        if (strcasecmp(threshold_type, "percentage") == 0 && apm_info.battery_life < low_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true; +        } else if (strcasecmp(threshold_type, "time") == 0 && apm_info.minutes_left < (u_int)low_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true;          } +    } -        if (prop_dictionary_count(dict) == 0) { -                prop_object_release(dict); -                close(fd); -                return; -        } +    /* Can't give a meaningful value for remaining minutes if we're charging. */ +    if (status != CS_CHARGING) { +        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%d", apm_info.minutes_left); +    } else { +        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%s", "(CHR)"); +    } -        iter = prop_dictionary_iterator(dict); -        if (iter == NULL) { -                prop_object_release(dict); -                close(fd); -        } - -        /* iterate over the dictionary returned by the kernel */ -        while ((obj = prop_object_iterator_next(iter)) != NULL) { -                /* skip this dict if it's not what we're looking for */ -                if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) && -                    (strncmp(sensor_desc, -                            prop_dictionary_keysym_cstring_nocopy(obj), -                            strlen(sensor_desc)) != 0)) -                        continue; - -                is_found = true; - -                array = prop_dictionary_get_keysym(dict, obj); -                if (prop_object_type(array) != PROP_TYPE_ARRAY) { -                        prop_object_iterator_release(iter); -                        prop_object_release(dict); -                        close(fd); -                        return; -                } - -                iter2 = prop_array_iterator(array); -                if (!iter2) { -                        prop_object_iterator_release(iter); -                        prop_object_release(dict); -                        close(fd); -                        return; -                } - -                /* iterate over array of dicts specific to target battery */ -                while ((obj2 = prop_object_iterator_next(iter2)) != NULL) { -                        obj3 = prop_dictionary_get(obj2, "description"); - -                        if (obj3 && -                            strlen(prop_string_cstring_nocopy(obj3)) == 8 && -                            strncmp("charging", -                                    prop_string_cstring_nocopy(obj3), -                                    8) == 0) -                        { -                                obj3 = prop_dictionary_get(obj2, "cur-value"); - -                                if (prop_number_integer_value(obj3)) -                                        status = CS_CHARGING; -                                else -                                        status = CS_DISCHARGING; - -                                continue; -                        } - -                        if (obj3 && -                            strlen(prop_string_cstring_nocopy(obj3)) == 6 && -                            strncmp("charge", -                                    prop_string_cstring_nocopy(obj3), -                                    6) == 0) -                        { -                                obj3 = prop_dictionary_get(obj2, "cur-value"); -                                obj4 = prop_dictionary_get(obj2, "max-value"); -                                obj5 = prop_dictionary_get(obj2, "type"); - -                                remaining = prop_number_integer_value(obj3); -                                full_design = prop_number_integer_value(obj4); - -                                if (remaining == full_design) -                                        is_full = true; - -                                if (strncmp("Ampere hour", -                                            prop_string_cstring_nocopy(obj5), -                                            11) == 0) -                                        watt_as_unit = false; -                                else -                                        watt_as_unit = true; - -                                continue; -                        } - -                        if (obj3 && -                            strlen(prop_string_cstring_nocopy(obj3)) == 14 && -                            strncmp("discharge rate", -                                    prop_string_cstring_nocopy(obj3), -                                    14) == 0) -                        { -                                obj3 = prop_dictionary_get(obj2, "cur-value"); -                                present_rate = prop_number_integer_value(obj3); -                                continue; -                        } - -                        if (obj3 && -                            strlen(prop_string_cstring_nocopy(obj3)) == 13 && -                            strncmp("last full cap", -                                    prop_string_cstring_nocopy(obj3), -                                    13) == 0) -                        { -                                obj3 = prop_dictionary_get(obj2, "cur-value"); -                                last_full_cap = prop_number_integer_value(obj3); -                                continue; -                        } - -                        if (obj3 && -                            strlen(prop_string_cstring_nocopy(obj3)) == 7 && -                            strncmp("voltage", -                                    prop_string_cstring_nocopy(obj3), -                                    7) == 0) -                        { -                                obj3 = prop_dictionary_get(obj2, "cur-value"); -                                voltage = prop_number_integer_value(obj3); -                                continue; -                        } -                } -                prop_object_iterator_release(iter2); -        } +    if (colorful_output) +        END_COLOR; +#elif defined(__NetBSD__) +    /* +     * Using envsys(4) via sysmon(4). +     */ +    int fd, rval, last_full_cap; +    bool is_found = false; +    char *sensor_desc; +    bool is_full = false; + +    prop_dictionary_t dict; +    prop_array_t array; +    prop_object_iterator_t iter; +    prop_object_iterator_t iter2; +    prop_object_t obj, obj2, obj3, obj4, obj5; + +    asprintf(&sensor_desc, "acpibat%d", number); + +    fd = open("/dev/sysmon", O_RDONLY); +    if (fd < 0) { +        OUTPUT_FULL_TEXT("can't open /dev/sysmon"); +        return; +    } + +    rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict); +    if (rval == -1) { +        close(fd); +        return; +    } -        prop_object_iterator_release(iter); +    if (prop_dictionary_count(dict) == 0) {          prop_object_release(dict);          close(fd); +        return; +    } -        if (! is_found) { -                OUTPUT_FULL_TEXT(format_down); -                return; +    iter = prop_dictionary_iterator(dict); +    if (iter == NULL) { +        prop_object_release(dict); +        close(fd); +    } + +    /* iterate over the dictionary returned by the kernel */ +    while ((obj = prop_object_iterator_next(iter)) != NULL) { +        /* skip this dict if it's not what we're looking for */ +        if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) && +            (strncmp(sensor_desc, +                     prop_dictionary_keysym_cstring_nocopy(obj), +                     strlen(sensor_desc)) != 0)) +            continue; + +        is_found = true; + +        array = prop_dictionary_get_keysym(dict, obj); +        if (prop_object_type(array) != PROP_TYPE_ARRAY) { +            prop_object_iterator_release(iter); +            prop_object_release(dict); +            close(fd); +            return;          } -        if (last_full_capacity) -                full_design = last_full_cap; - -        if (! watt_as_unit) { -                present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0)); -                remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0)); -                full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0)); +        iter2 = prop_array_iterator(array); +        if (!iter2) { +            prop_object_iterator_release(iter); +            prop_object_release(dict); +            close(fd); +            return;          } -        float percentage_remaining = -                (((float)remaining / (float)full_design) * 100); +        /* iterate over array of dicts specific to target battery */ +        while ((obj2 = prop_object_iterator_next(iter2)) != NULL) { +            obj3 = prop_dictionary_get(obj2, "description"); -        if (integer_battery_capacity) -                (void)snprintf(percentagebuf, -                           sizeof(percentagebuf), -                           "%d%%", -                           (int) percentage_remaining); -        else -                (void)snprintf(percentagebuf, -                           sizeof(percentagebuf), -                           "%.02f%%", -                           percentage_remaining); - -        /* -         * Handle percentage low_threshold here, and time low_threshold when -         * we have it. -         */ -        if (status == CS_DISCHARGING && low_threshold > 0) { -                if (strcasecmp(threshold_type, "percentage") == 0 -                    && (((float)remaining / (float)full_design) * 100) < low_threshold) { -                        START_COLOR("color_bad"); -                        colorful_output = true; -                } -        } +            if (obj3 && +                strlen(prop_string_cstring_nocopy(obj3)) == 8 && +                strncmp("charging", +                        prop_string_cstring_nocopy(obj3), +                        8) == 0) { +                obj3 = prop_dictionary_get(obj2, "cur-value"); -        if (is_full) -                (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(CS_FULL)); -        else -                (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); +                if (prop_number_integer_value(obj3)) +                    status = CS_CHARGING; +                else +                    status = CS_DISCHARGING; -        /* -         * The envsys(4) ACPI routines do not appear to provide a 'time -         * remaining' figure, so we must deduce it. -         */ -        float remaining_time; -        int seconds, hours, minutes, seconds_remaining; +                continue; +            } -        if (status == CS_CHARGING) -                remaining_time = ((float)full_design - (float)remaining) -                        / (float)present_rate; -        else if (status == CS_DISCHARGING) -                remaining_time = ((float)remaining / (float)present_rate); -        else remaining_time = 0; +            if (obj3 && +                strlen(prop_string_cstring_nocopy(obj3)) == 6 && +                strncmp("charge", +                        prop_string_cstring_nocopy(obj3), +                        6) == 0) { +                obj3 = prop_dictionary_get(obj2, "cur-value"); +                obj4 = prop_dictionary_get(obj2, "max-value"); +                obj5 = prop_dictionary_get(obj2, "type"); + +                remaining = prop_number_integer_value(obj3); +                full_design = prop_number_integer_value(obj4); + +                if (remaining == full_design) +                    is_full = true; + +                if (strncmp("Ampere hour", +                            prop_string_cstring_nocopy(obj5), +                            11) == 0) +                    watt_as_unit = false; +                else +                    watt_as_unit = true; -        seconds_remaining = (int)(remaining_time * 3600.0); +                continue; +            } -        hours = seconds_remaining / 3600; -        seconds = seconds_remaining - (hours * 3600); -        minutes = seconds / 60; -        seconds -= (minutes * 60); +            if (obj3 && +                strlen(prop_string_cstring_nocopy(obj3)) == 14 && +                strncmp("discharge rate", +                        prop_string_cstring_nocopy(obj3), +                        14) == 0) { +                obj3 = prop_dictionary_get(obj2, "cur-value"); +                present_rate = prop_number_integer_value(obj3); +                continue; +            } -        if (status != CS_CHARGING) { -                if (hide_seconds) -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", -                                max(hours, 0), max(minutes, 0)); -                else -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d", -                                max(hours, 0), max(minutes, 0), max(seconds, 0)); - -                if (low_threshold > 0) { -                        if (strcasecmp(threshold_type, "time") == 0 -                            && ((float) seconds_remaining / 60.0) < (u_int) low_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } -                } -        } else { -                if (hide_seconds) -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d until full)", -                                max(hours, 0), max(minutes, 0)); -                else -                        (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d:%02d until full)", -                                max(hours, 0), max(minutes, 0), max(seconds, 0)); +            if (obj3 && +                strlen(prop_string_cstring_nocopy(obj3)) == 13 && +                strncmp("last full cap", +                        prop_string_cstring_nocopy(obj3), +                        13) == 0) { +                obj3 = prop_dictionary_get(obj2, "cur-value"); +                last_full_cap = prop_number_integer_value(obj3); +                continue; +            } + +            if (obj3 && +                strlen(prop_string_cstring_nocopy(obj3)) == 7 && +                strncmp("voltage", +                        prop_string_cstring_nocopy(obj3), +                        7) == 0) { +                obj3 = prop_dictionary_get(obj2, "cur-value"); +                voltage = prop_number_integer_value(obj3); +                continue; +            } +        } +        prop_object_iterator_release(iter2); +    } + +    prop_object_iterator_release(iter); +    prop_object_release(dict); +    close(fd); + +    if (!is_found) { +        OUTPUT_FULL_TEXT(format_down); +        return; +    } + +    if (last_full_capacity) +        full_design = last_full_cap; + +    if (!watt_as_unit) { +        present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0)); +        remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0)); +        full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0)); +    } + +    float percentage_remaining = +        (((float)remaining / (float)full_design) * 100); + +    if (integer_battery_capacity) +        (void)snprintf(percentagebuf, +                       sizeof(percentagebuf), +                       "%d%%", +                       (int)percentage_remaining); +    else +        (void)snprintf(percentagebuf, +                       sizeof(percentagebuf), +                       "%.02f%%", +                       percentage_remaining); + +    /* +     * Handle percentage low_threshold here, and time low_threshold when +     * we have it. +     */ +    if (status == CS_DISCHARGING && low_threshold > 0) { +        if (strcasecmp(threshold_type, "percentage") == 0 && (((float)remaining / (float)full_design) * 100) < low_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true;          } +    } -        empty_time = time(NULL); -        empty_time += seconds_remaining; -        empty_tm = localtime(&empty_time); +    if (is_full) +        (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(CS_FULL)); +    else +        (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status)); -        /* No need to show empty time if battery is charging */ -        if (status != CS_CHARGING) { -                if (hide_seconds) -                        (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d", -                                max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0)); -                else -                        (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d", -                                max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0)); +    /* +     * The envsys(4) ACPI routines do not appear to provide a 'time +     * remaining' figure, so we must deduce it. +     */ +    float remaining_time; +    int seconds, hours, minutes, seconds_remaining; + +    if (status == CS_CHARGING) +        remaining_time = ((float)full_design - (float)remaining) / (float)present_rate; +    else if (status == CS_DISCHARGING) +        remaining_time = ((float)remaining / (float)present_rate); +    else +        remaining_time = 0; + +    seconds_remaining = (int)(remaining_time * 3600.0); + +    hours = seconds_remaining / 3600; +    seconds = seconds_remaining - (hours * 3600); +    minutes = seconds / 60; +    seconds -= (minutes * 60); + +    if (status != CS_CHARGING) { +        if (hide_seconds) +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", +                           max(hours, 0), max(minutes, 0)); +        else +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d", +                           max(hours, 0), max(minutes, 0), max(seconds, 0)); + +        if (low_threshold > 0) { +            if (strcasecmp(threshold_type, "time") == 0 && ((float)seconds_remaining / 60.0) < (u_int)low_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            }          } +    } else { +        if (hide_seconds) +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d until full)", +                           max(hours, 0), max(minutes, 0)); +        else +            (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d:%02d until full)", +                           max(hours, 0), max(minutes, 0), max(seconds, 0)); +    } + +    empty_time = time(NULL); +    empty_time += seconds_remaining; +    empty_tm = localtime(&empty_time); + +    /* No need to show empty time if battery is charging */ +    if (status != CS_CHARGING) { +        if (hide_seconds) +            (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d", +                           max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0)); +        else +            (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d", +                           max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0)); +    } -        (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW", -                ((float)present_rate / 1000.0 / 1000.0)); +    (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW", +                   ((float)present_rate / 1000.0 / 1000.0));  #endif -#define EAT_SPACE_FROM_OUTPUT_IF_EMPTY(_buf) \ -        do { \ -                if (strlen(_buf) == 0) { \ -                        if (outwalk > buffer && isspace(outwalk[-1])) \ -                                outwalk--; \ -                        else if (isspace(*(walk+1))) \ -                                walk++; \ -                } \ -        } while (0) - -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } - -                if (BEGINS_WITH(walk+1, "status")) { -                        outwalk += sprintf(outwalk, "%s", statusbuf); -                        walk += strlen("status"); -                } else if (BEGINS_WITH(walk+1, "percentage")) { -                        outwalk += sprintf(outwalk, "%s", percentagebuf); -                        walk += strlen("percentage"); -                } else if (BEGINS_WITH(walk+1, "remaining")) { -                        outwalk += sprintf(outwalk, "%s", remainingbuf); -                        walk += strlen("remaining"); -                        EAT_SPACE_FROM_OUTPUT_IF_EMPTY(remainingbuf); -                } else if (BEGINS_WITH(walk+1, "emptytime")) { -                        outwalk += sprintf(outwalk, "%s", emptytimebuf); -                        walk += strlen("emptytime"); -                        EAT_SPACE_FROM_OUTPUT_IF_EMPTY(emptytimebuf); -                } else if (BEGINS_WITH(walk+1, "consumption")) { -                        outwalk += sprintf(outwalk, "%s", consumptionbuf); -                        walk += strlen("consumption"); -                        EAT_SPACE_FROM_OUTPUT_IF_EMPTY(consumptionbuf); -                } +#define EAT_SPACE_FROM_OUTPUT_IF_EMPTY(_buf)              \ +    do {                                                  \ +        if (strlen(_buf) == 0) {                          \ +            if (outwalk > buffer && isspace(outwalk[-1])) \ +                outwalk--;                                \ +            else if (isspace(*(walk + 1)))                \ +                walk++;                                   \ +        }                                                 \ +    } while (0) + +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } + +        if (BEGINS_WITH(walk + 1, "status")) { +            outwalk += sprintf(outwalk, "%s", statusbuf); +            walk += strlen("status"); +        } else if (BEGINS_WITH(walk + 1, "percentage")) { +            outwalk += sprintf(outwalk, "%s", percentagebuf); +            walk += strlen("percentage"); +        } else if (BEGINS_WITH(walk + 1, "remaining")) { +            outwalk += sprintf(outwalk, "%s", remainingbuf); +            walk += strlen("remaining"); +            EAT_SPACE_FROM_OUTPUT_IF_EMPTY(remainingbuf); +        } else if (BEGINS_WITH(walk + 1, "emptytime")) { +            outwalk += sprintf(outwalk, "%s", emptytimebuf); +            walk += strlen("emptytime"); +            EAT_SPACE_FROM_OUTPUT_IF_EMPTY(emptytimebuf); +        } else if (BEGINS_WITH(walk + 1, "consumption")) { +            outwalk += sprintf(outwalk, "%s", consumptionbuf); +            walk += strlen("consumption"); +            EAT_SPACE_FROM_OUTPUT_IF_EMPTY(consumptionbuf);          } +    } -        if (colorful_output) -                END_COLOR; +    if (colorful_output) +        END_COLOR; -        OUTPUT_FULL_TEXT(buffer); +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_cpu_temperature.c b/src/print_cpu_temperature.c index c687474..f60a5f6 100644 --- a/src/print_cpu_temperature.c +++ b/src/print_cpu_temperature.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdlib.h>  #include <limits.h>  #include <stdio.h> @@ -13,8 +13,8 @@  #include <sys/types.h>  #include <sys/sysctl.h>  #define TZ_ZEROC 2732 -#define TZ_KELVTOC(x) (((x) - TZ_ZEROC) / 10), abs(((x) - TZ_ZEROC) % 10) -#define TZ_AVG(x) ((x) - TZ_ZEROC) / 10 +#define TZ_KELVTOC(x) (((x)-TZ_ZEROC) / 10), abs(((x)-TZ_ZEROC) % 10) +#define TZ_AVG(x) ((x)-TZ_ZEROC) / 10  #endif  #if defined(__DragonFly__) @@ -43,171 +43,170 @@  #define MUKTOC(v) ((v - 273150000) / 1000000.0)  #endif -  /*   * Reads the CPU temperature from /sys/class/thermal/thermal_zone%d/temp (or   * the user provided path) and returns the temperature in degree celcius.   *   */  void print_cpu_temperature_info(yajl_gen json_gen, char *buffer, int zone, const char *path, const char *format, int max_threshold) { -        char *outwalk = buffer; +    char *outwalk = buffer;  #ifdef THERMAL_ZONE -        const char *walk; -        bool colorful_output = false; -        char *thermal_zone; +    const char *walk; +    bool colorful_output = false; +    char *thermal_zone; -        if (path == NULL) -                asprintf(&thermal_zone, THERMAL_ZONE, zone); -        else -                asprintf(&thermal_zone, path, zone); +    if (path == NULL) +        asprintf(&thermal_zone, THERMAL_ZONE, zone); +    else +        asprintf(&thermal_zone, path, zone); -        INSTANCE(thermal_zone); +    INSTANCE(thermal_zone); -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } -                if (BEGINS_WITH(walk+1, "degrees")) { +        if (BEGINS_WITH(walk + 1, "degrees")) {  #if defined(LINUX) -                        static char buf[16]; -                        long int temp; -                        if (!slurp(thermal_zone, buf, sizeof(buf))) -                                goto error; -                        temp = strtol(buf, NULL, 10); -                        if (temp == LONG_MIN || temp == LONG_MAX || temp <= 0) -                                *(outwalk++) = '?'; -                        else { -                                if ((temp/1000) >= max_threshold) { -                                        START_COLOR("color_bad"); -                                        colorful_output = true; -                                } -                                outwalk += sprintf(outwalk, "%ld", (temp/1000)); -                                if (colorful_output) { -                                        END_COLOR; -                                        colorful_output = false; -                                } -                        } +            static char buf[16]; +            long int temp; +            if (!slurp(thermal_zone, buf, sizeof(buf))) +                goto error; +            temp = strtol(buf, NULL, 10); +            if (temp == LONG_MIN || temp == LONG_MAX || temp <= 0) +                *(outwalk++) = '?'; +            else { +                if ((temp / 1000) >= max_threshold) { +                    START_COLOR("color_bad"); +                    colorful_output = true; +                } +                outwalk += sprintf(outwalk, "%ld", (temp / 1000)); +                if (colorful_output) { +                    END_COLOR; +                    colorful_output = false; +                } +            }  #elif defined(__DragonFly__) -			struct sensor th_sensor; -			size_t th_sensorlen; - -			th_sensorlen = sizeof(th_sensor); - -			if (sysctlbyname(thermal_zone, &th_sensor, &th_sensorlen, NULL, 0) == -1) { -				perror("sysctlbyname"); -				goto error; -			} -			if (MUKTOC(th_sensor.value) >= max_threshold) { -				START_COLOR("color_bad"); -				colorful_output = true; -			} -			outwalk += sprintf(outwalk, "%.2f", MUKTOC(th_sensor.value)); -			if (colorful_output) { -				END_COLOR; -				colorful_output = false; -			} +            struct sensor th_sensor; +            size_t th_sensorlen; + +            th_sensorlen = sizeof(th_sensor); + +            if (sysctlbyname(thermal_zone, &th_sensor, &th_sensorlen, NULL, 0) == -1) { +                perror("sysctlbyname"); +                goto error; +            } +            if (MUKTOC(th_sensor.value) >= max_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            } +            outwalk += sprintf(outwalk, "%.2f", MUKTOC(th_sensor.value)); +            if (colorful_output) { +                END_COLOR; +                colorful_output = false; +            }  #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) -                        int sysctl_rslt; -                        size_t sysctl_size = sizeof(sysctl_rslt); -                        if (sysctlbyname(thermal_zone, &sysctl_rslt, &sysctl_size, NULL, 0)) -                                goto error; - -                        if (TZ_AVG(sysctl_rslt) >= max_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } -                        outwalk += sprintf(outwalk, "%d.%d", TZ_KELVTOC(sysctl_rslt)); -                        if (colorful_output) { -                                END_COLOR; -                                colorful_output = false; -                        } +            int sysctl_rslt; +            size_t sysctl_size = sizeof(sysctl_rslt); +            if (sysctlbyname(thermal_zone, &sysctl_rslt, &sysctl_size, NULL, 0)) +                goto error; + +            if (TZ_AVG(sysctl_rslt) >= max_threshold) { +                START_COLOR("color_bad"); +                colorful_output = true; +            } +            outwalk += sprintf(outwalk, "%d.%d", TZ_KELVTOC(sysctl_rslt)); +            if (colorful_output) { +                END_COLOR; +                colorful_output = false; +            }  #elif defined(__OpenBSD__) -        struct sensordev sensordev; -        struct sensor sensor; -        size_t sdlen, slen; -        int dev, numt, mib[5] = { CTL_HW, HW_SENSORS, 0, 0, 0 }; +            struct sensordev sensordev; +            struct sensor sensor; +            size_t sdlen, slen; +            int dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0}; -        sdlen = sizeof(sensordev); -        slen = sizeof(sensor); +            sdlen = sizeof(sensordev); +            slen = sizeof(sensor); -        for (dev = 0; ; dev++) { +            for (dev = 0;; dev++) {                  mib[2] = dev;                  if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) == -1) { -                        if (errno == ENXIO) -                                continue; -                        if (errno == ENOENT) -                                break; -                        goto error; +                    if (errno == ENXIO) +                        continue; +                    if (errno == ENOENT) +                        break; +                    goto error;                  }                  /* 'path' is the node within the full path (defaults to acpitz0). */                  if (BEGINS_WITH(sensordev.xname, thermal_zone)) { -                        mib[3] = SENSOR_TEMP; -                        /* Limit to temo0, but should retrieve from a full path... */ -                        for (numt = 0; numt < 1 /*sensordev.maxnumt[SENSOR_TEMP]*/; numt++) { -                                mib[4] = numt; -                                if (sysctl(mib, 5, &sensor, &slen, NULL, 0) == -1) { -                                        if (errno != ENOENT) { -                                                warn("sysctl"); -                                                continue; -                                        } -                                } -                                if ((int)MUKTOC(sensor.value) >= max_threshold) { -                                        START_COLOR("color_bad"); -                                        colorful_output = true; -                                } - -                                outwalk += sprintf(outwalk, "%.2f", MUKTOC(sensor.value)); - -                                if (colorful_output) { -                                        END_COLOR; -                                        colorful_output = false; -                                } +                    mib[3] = SENSOR_TEMP; +                    /* Limit to temo0, but should retrieve from a full path... */ +                    for (numt = 0; numt < 1 /*sensordev.maxnumt[SENSOR_TEMP]*/; numt++) { +                        mib[4] = numt; +                        if (sysctl(mib, 5, &sensor, &slen, NULL, 0) == -1) { +                            if (errno != ENOENT) { +                                warn("sysctl"); +                                continue; +                            } +                        } +                        if ((int)MUKTOC(sensor.value) >= max_threshold) { +                            START_COLOR("color_bad"); +                            colorful_output = true;                          } + +                        outwalk += sprintf(outwalk, "%.2f", MUKTOC(sensor.value)); + +                        if (colorful_output) { +                            END_COLOR; +                            colorful_output = false; +                        } +                    }                  } -        } +            }  #elif defined(__NetBSD__) -        int fd, rval; -        bool err = false; -        prop_dictionary_t dict; -        prop_array_t array; -        prop_object_iterator_t iter; -        prop_object_iterator_t iter2; -        prop_object_t obj, obj2, obj3; - -        fd = open("/dev/sysmon", O_RDONLY); -        if (fd == -1) +            int fd, rval; +            bool err = false; +            prop_dictionary_t dict; +            prop_array_t array; +            prop_object_iterator_t iter; +            prop_object_iterator_t iter2; +            prop_object_t obj, obj2, obj3; + +            fd = open("/dev/sysmon", O_RDONLY); +            if (fd == -1)                  goto error; -        rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict); -        if (rval == -1) { -            err = true; -            goto error_netbsd1; -        } - -        /* No drivers registered? */ -        if (prop_dictionary_count(dict) == 0) { -            err = true; -            goto error_netbsd2; -        } - -        iter = prop_dictionary_iterator(dict); -        if (iter == NULL) { -            err = true; -            goto error_netbsd2; -        } - -        /* iterate over the dictionary returned by the kernel */ -        while ((obj = prop_object_iterator_next(iter)) != NULL) { +            rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict); +            if (rval == -1) { +                err = true; +                goto error_netbsd1; +            } + +            /* No drivers registered? */ +            if (prop_dictionary_count(dict) == 0) { +                err = true; +                goto error_netbsd2; +            } + +            iter = prop_dictionary_iterator(dict); +            if (iter == NULL) { +                err = true; +                goto error_netbsd2; +            } + +            /* iterate over the dictionary returned by the kernel */ +            while ((obj = prop_object_iterator_next(iter)) != NULL) {                  /* skip this dict if it's not what we're looking for */                  if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) != strlen(thermal_zone)) ||                      (strncmp(thermal_zone,                               prop_dictionary_keysym_cstring_nocopy(obj),                               strlen(thermal_zone)) != 0)) -                        continue; +                    continue;                  array = prop_dictionary_get_keysym(dict, obj);                  if (prop_object_type(array) != PROP_TYPE_ARRAY) { @@ -223,48 +222,48 @@ void print_cpu_temperature_info(yajl_gen json_gen, char *buffer, int zone, const                  /* iterate over array of dicts specific to target sensor */                  while ((obj2 = prop_object_iterator_next(iter2)) != NULL) { -                        obj3 = prop_dictionary_get(obj2, "cur-value"); +                    obj3 = prop_dictionary_get(obj2, "cur-value"); -                        float temp = MUKTOC(prop_number_integer_value(obj3)); -                        if ((int)temp >= max_threshold) { -                                START_COLOR("color_bad"); -                                colorful_output = true; -                        } +                    float temp = MUKTOC(prop_number_integer_value(obj3)); +                    if ((int)temp >= max_threshold) { +                        START_COLOR("color_bad"); +                        colorful_output = true; +                    } -                        outwalk += sprintf(outwalk, "%.2f", temp); +                    outwalk += sprintf(outwalk, "%.2f", temp); -                        if (colorful_output) { -                                END_COLOR; -                                colorful_output = false; -                        } +                    if (colorful_output) { +                        END_COLOR; +                        colorful_output = false; +                    } -                        break; +                    break;                  }                  prop_object_iterator_release(iter2); -        } -error_netbsd3: -        prop_object_iterator_release(iter); -error_netbsd2: -	prop_object_release(dict); -error_netbsd1: -        close(fd); -        if (err) goto error; +            } +        error_netbsd3: +            prop_object_iterator_release(iter); +        error_netbsd2: +            prop_object_release(dict); +        error_netbsd1: +            close(fd); +            if (err) +                goto error;  #endif - -                        walk += strlen("degrees"); -                } +            walk += strlen("degrees");          } +    } -        free(thermal_zone); +    free(thermal_zone); -        OUTPUT_FULL_TEXT(buffer); -        return; +    OUTPUT_FULL_TEXT(buffer); +    return;  error:  #endif -        free(thermal_zone); +    free(thermal_zone); -        OUTPUT_FULL_TEXT("cant read temp"); -        (void)fputs("i3status: Cannot read temperature. Verify that you have a thermal zone in /sys/class/thermal or disable the cpu_temperature module in your i3status config.\n", stderr); +    OUTPUT_FULL_TEXT("cant read temp"); +    (void)fputs("i3status: Cannot read temperature. Verify that you have a thermal zone in /sys/class/thermal or disable the cpu_temperature module in your i3status config.\n", stderr);  } diff --git a/src/print_cpu_usage.c b/src/print_cpu_usage.c index 26a9d4f..68437b3 100644 --- a/src/print_cpu_usage.c +++ b/src/print_cpu_usage.c @@ -1,4 +1,4 @@ -// vim:sw=8:sts=8:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdlib.h>  #include <limits.h>  #include <stdio.h> @@ -30,7 +30,7 @@  #include "i3status.h"  static int prev_total = 0; -static int prev_idle  = 0; +static int prev_idle = 0;  /*   * Reads the CPU utilization from /proc/stat and returns the usage as a @@ -38,74 +38,74 @@ static int prev_idle  = 0;   *   */  void print_cpu_usage(yajl_gen json_gen, char *buffer, const char *format) { -        const char *walk; -        char *outwalk = buffer; -        char buf[1024]; -        int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total; -        int diff_idle, diff_total, diff_usage; +    const char *walk; +    char *outwalk = buffer; +    char buf[1024]; +    int curr_user = 0, curr_nice = 0, curr_system = 0, curr_idle = 0, curr_total; +    int diff_idle, diff_total, diff_usage;  #if defined(LINUX) -        static char statpath[512]; -        strcpy(statpath, "/proc/stat"); -        if (!slurp(statpath, buf, sizeof(buf)) || -            sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4) -                goto error; +    static char statpath[512]; +    strcpy(statpath, "/proc/stat"); +    if (!slurp(statpath, buf, sizeof(buf)) || +        sscanf(buf, "cpu %d %d %d %d", &curr_user, &curr_nice, &curr_system, &curr_idle) != 4) +        goto error; -        curr_total = curr_user + curr_nice + curr_system + curr_idle; -        diff_idle  = curr_idle - prev_idle; -        diff_total = curr_total - prev_total; -        diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0); -        prev_total = curr_total; -        prev_idle  = curr_idle; +    curr_total = curr_user + curr_nice + curr_system + curr_idle; +    diff_idle = curr_idle - prev_idle; +    diff_total = curr_total - prev_total; +    diff_usage = (diff_total ? (1000 * (diff_total - diff_idle) / diff_total + 5) / 10 : 0); +    prev_total = curr_total; +    prev_idle = curr_idle;  #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)  #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) -        size_t size; -        long cp_time[CPUSTATES]; -        size = sizeof cp_time; -        if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0) -                goto error; +    size_t size; +    long cp_time[CPUSTATES]; +    size = sizeof cp_time; +    if (sysctlbyname("kern.cp_time", &cp_time, &size, NULL, 0) < 0) +        goto error;  #else -	/* This information is taken from the boot cpu, any other cpus are currently ignored. */ -	long cp_time[CPUSTATES]; -	int mib[2]; -	size_t size = sizeof(cp_time); +    /* This information is taken from the boot cpu, any other cpus are currently ignored. */ +    long cp_time[CPUSTATES]; +    int mib[2]; +    size_t size = sizeof(cp_time); -	mib[0] = CTL_KERN; -	mib[1] = KERN_CPTIME; +    mib[0] = CTL_KERN; +    mib[1] = KERN_CPTIME; -	if (sysctl(mib, 2, cp_time, &size, NULL, 0)) -		goto error; +    if (sysctl(mib, 2, cp_time, &size, NULL, 0)) +        goto error;  #endif -        curr_user = cp_time[CP_USER]; -        curr_nice = cp_time[CP_NICE]; -        curr_system = cp_time[CP_SYS]; -        curr_idle = cp_time[CP_IDLE]; -        curr_total = curr_user + curr_nice + curr_system + curr_idle; -        diff_idle  = curr_idle - prev_idle; -        diff_total = curr_total - prev_total; -        diff_usage = (diff_total ? (1000 * (diff_total - diff_idle)/diff_total + 5)/10 : 0); -        prev_total = curr_total; -        prev_idle  = curr_idle; +    curr_user = cp_time[CP_USER]; +    curr_nice = cp_time[CP_NICE]; +    curr_system = cp_time[CP_SYS]; +    curr_idle = cp_time[CP_IDLE]; +    curr_total = curr_user + curr_nice + curr_system + curr_idle; +    diff_idle = curr_idle - prev_idle; +    diff_total = curr_total - prev_total; +    diff_usage = (diff_total ? (1000 * (diff_total - diff_idle) / diff_total + 5) / 10 : 0); +    prev_total = curr_total; +    prev_idle = curr_idle;  #else -        goto error; +    goto error;  #endif -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } -                if (BEGINS_WITH(walk+1, "usage")) { -                        outwalk += sprintf(outwalk, "%02d%%", diff_usage); -                        walk += strlen("usage"); -                } +        if (BEGINS_WITH(walk + 1, "usage")) { +            outwalk += sprintf(outwalk, "%02d%%", diff_usage); +            walk += strlen("usage");          } +    } -        OUTPUT_FULL_TEXT(buffer); -        return; +    OUTPUT_FULL_TEXT(buffer); +    return;  error: -        OUTPUT_FULL_TEXT("cant read cpu usage"); -        (void)fputs("i3status: Cannot read CPU usage\n", stderr); +    OUTPUT_FULL_TEXT("cant read cpu usage"); +    (void)fputs("i3status: Cannot read CPU usage\n", stderr);  } diff --git a/src/print_ddate.c b/src/print_ddate.c index de9a7be..1c368b5 100644 --- a/src/print_ddate.c +++ b/src/print_ddate.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <time.h>  #include <stdio.h>  #include <stdlib.h> @@ -10,213 +10,208 @@  /* define fixed output-Strings */  char *season_long[5] = { -        "Chaos", -        "Discord", -        "Confusion", -        "Bureaucracy", -        "The Aftermath" -}; +    "Chaos", +    "Discord", +    "Confusion", +    "Bureaucracy", +    "The Aftermath"};  char *season_short[5] = { -        "Chs", -        "Dsc", -        "Cfn", -        "Bcy", -        "Afm" -}; +    "Chs", +    "Dsc", +    "Cfn", +    "Bcy", +    "Afm"};  char *day_long[5] = { -        "Sweetmorn", -        "Boomtime", -        "Pungenday", -        "Prickle-Prickle", -        "Setting Orange" -}; +    "Sweetmorn", +    "Boomtime", +    "Pungenday", +    "Prickle-Prickle", +    "Setting Orange"};  char *day_short[5] = { -        "SM", -        "BT", -        "PD", -        "PP", -        "SO" -}; +    "SM", +    "BT", +    "PD", +    "PP", +    "SO"};  char *holidays[10] = { -        "Mungday", -        "Mojoday", -        "Syaday", -        "Zaraday", -        "Maladay", -        "Chaoflux", -        "Discoflux", -        "Confuflux", -        "Bureflux", -        "Afflux" -}; +    "Mungday", +    "Mojoday", +    "Syaday", +    "Zaraday", +    "Maladay", +    "Chaoflux", +    "Discoflux", +    "Confuflux", +    "Bureflux", +    "Afflux"};  /* A helper-struct, taking the discordian date */  struct disc_time { -        int year; -        int season; -        int week_day; -        int season_day; -        int st_tibs_day; +    int year; +    int season; +    int week_day; +    int season_day; +    int st_tibs_day;  };  /* Print the date *dt in format *format */  static int format_output(char *outwalk, char *format, struct disc_time *dt) { -        char *orig_outwalk = outwalk; -        char *i; -        char *tibs_end = 0; - -        for (i = format; *i != '\0'; i++) { -                if (*i != '%') { -                        *(outwalk++) = *i; -                        continue; +    char *orig_outwalk = outwalk; +    char *i; +    char *tibs_end = 0; + +    for (i = format; *i != '\0'; i++) { +        if (*i != '%') { +            *(outwalk++) = *i; +            continue; +        } +        switch (*(i + 1)) { +            /* Weekday in long and abbreviation */ +            case 'A': +                outwalk += sprintf(outwalk, "%s", day_long[dt->week_day]); +                break; +            case 'a': +                outwalk += sprintf(outwalk, "%s", day_short[dt->week_day]); +                break; +            /* Season in long and abbreviation */ +            case 'B': +                outwalk += sprintf(outwalk, "%s", season_long[dt->season]); +                break; +            case 'b': +                outwalk += sprintf(outwalk, "%s", season_short[dt->season]); +                break; +            /* Day of the season (ordinal and cardinal) */ +            case 'd': +                outwalk += sprintf(outwalk, "%d", dt->season_day + 1); +                break; +            case 'e': +                outwalk += sprintf(outwalk, "%d", dt->season_day + 1); +                if (dt->season_day > 9 && dt->season_day < 13) { +                    outwalk += sprintf(outwalk, "th"); +                    break; +                } + +                switch (dt->season_day % 10) { +                    case 0: +                        outwalk += sprintf(outwalk, "st"); +                        break; +                    case 1: +                        outwalk += sprintf(outwalk, "nd"); +                        break; +                    case 2: +                        outwalk += sprintf(outwalk, "rd"); +                        break; +                    default: +                        outwalk += sprintf(outwalk, "th"); +                        break; +                } +                break; +            /* YOLD */ +            case 'Y': +                outwalk += sprintf(outwalk, "%d", dt->year); +                break; +            /* Holidays */ +            case 'H': +                if (dt->season_day == 4) { +                    outwalk += sprintf(outwalk, "%s", holidays[dt->season]);                  } -                switch (*(i+1)) { -                        /* Weekday in long and abbreviation */ -                        case 'A': -                                outwalk += sprintf(outwalk, "%s", day_long[dt->week_day]); -                                break; -                        case 'a': -                                outwalk += sprintf(outwalk, "%s", day_short[dt->week_day]); -                                break; -                        /* Season in long and abbreviation */ -                        case 'B': -                                outwalk += sprintf(outwalk, "%s", season_long[dt->season]); -                                break; -                        case 'b': -                                outwalk += sprintf(outwalk, "%s", season_short[dt->season]); -                                break; -                        /* Day of the season (ordinal and cardinal) */ -                        case 'd': -                                outwalk += sprintf(outwalk, "%d", dt->season_day + 1); -                                break; -                        case 'e': -                                outwalk += sprintf(outwalk, "%d", dt->season_day + 1); -                                if (dt->season_day > 9 && dt->season_day < 13) { -                                        outwalk += sprintf(outwalk, "th"); -                                        break; -                                } - -                                switch (dt->season_day % 10) { -                                        case 0: -                                                outwalk += sprintf(outwalk, "st"); -                                                break; -                                        case 1: -                                                outwalk += sprintf(outwalk, "nd"); -                                                break; -                                        case 2: -                                                outwalk += sprintf(outwalk, "rd"); -                                                break; -                                        default: -                                                outwalk += sprintf(outwalk, "th"); -                                                break; -                                } -                                break; -                        /* YOLD */ -                        case 'Y': -                                outwalk += sprintf(outwalk, "%d", dt->year); -                                break; -                        /* Holidays */ -                        case 'H': -                                if (dt->season_day == 4) { -                                        outwalk += sprintf(outwalk, "%s", holidays[dt->season]); -                                } -                                if (dt->season_day == 49) { -                                        outwalk += sprintf(outwalk, "%s", holidays[dt->season + 5]); -                                } -                                break; -                        /* Stop parsing the format string, except on Holidays */ -                        case 'N': -                                if (dt->season_day != 4 && dt->season_day != 49) { -                                        return (outwalk - orig_outwalk); -                                } -                                break; -                        /* Newline- and Tabbing-characters */ -                        case 'n': -                                outwalk += sprintf(outwalk, "\n"); -                                break; -                        case 't': -                                outwalk += sprintf(outwalk, "\t"); -                                break; -                        /* The St. Tib's Day replacement */ -                        case '{': -                                tibs_end = strstr(i, "%}"); -                                if (tibs_end == NULL) { -                                        i++; -                                        break; -                                } -                                if (dt->st_tibs_day) { -                                        /* We outpt "St. Tib's Day... */ -                                        outwalk += sprintf(outwalk, "St. Tib's Day"); -                                } else { -                                        /* ...or parse the substring between %{ and %} ... */ -                                        *tibs_end = '\0'; -                                        outwalk += format_output(outwalk, i + 2, dt); -                                        *tibs_end = '%'; -                                } -                                /* ...and continue with the rest */ -                                i = tibs_end; -                                break; -                        case '}': -                                i++; -                                break; -                        default: -                                /* No escape-sequence, so we just skip */ -                                outwalk += sprintf(outwalk, "%%%c", *(i+1)); -                                break; +                if (dt->season_day == 49) { +                    outwalk += sprintf(outwalk, "%s", holidays[dt->season + 5]);                  } +                break; +            /* Stop parsing the format string, except on Holidays */ +            case 'N': +                if (dt->season_day != 4 && dt->season_day != 49) { +                    return (outwalk - orig_outwalk); +                } +                break; +            /* Newline- and Tabbing-characters */ +            case 'n': +                outwalk += sprintf(outwalk, "\n"); +                break; +            case 't': +                outwalk += sprintf(outwalk, "\t"); +                break; +            /* The St. Tib's Day replacement */ +            case '{': +                tibs_end = strstr(i, "%}"); +                if (tibs_end == NULL) { +                    i++; +                    break; +                } +                if (dt->st_tibs_day) { +                    /* We outpt "St. Tib's Day... */ +                    outwalk += sprintf(outwalk, "St. Tib's Day"); +                } else { +                    /* ...or parse the substring between %{ and %} ... */ +                    *tibs_end = '\0'; +                    outwalk += format_output(outwalk, i + 2, dt); +                    *tibs_end = '%'; +                } +                /* ...and continue with the rest */ +                i = tibs_end; +                break; +            case '}':                  i++; +                break; +            default: +                /* No escape-sequence, so we just skip */ +                outwalk += sprintf(outwalk, "%%%c", *(i + 1)); +                break;          } -        return (outwalk - orig_outwalk); +        i++; +    } +    return (outwalk - orig_outwalk);  }  /* Get the current date and convert it to discordian */  struct disc_time *get_ddate(struct tm *current_tm) { -        static struct disc_time dt; - -        if (current_tm == NULL) -                return NULL; - -        /* We have to know, whether we have to insert St. Tib's Day, so whether it's a leap -           year in gregorian calendar */ -        int is_leap_year = !(current_tm->tm_year % 4) && -                            (!(current_tm->tm_year % 400) || current_tm->tm_year % 100); - -        /* If St. Tib's Day has passed, it will be necessary to skip a day. */ -        int yday = current_tm->tm_yday; - -        if (is_leap_year && yday == 59) { -                /* On St. Tibs Day we don't have to define a date */ -                dt.st_tibs_day = 1; -        } else { -                dt.st_tibs_day = 0; -                if (is_leap_year && yday > 59) -                        yday -= 1; - -                dt.season_day = yday % 73; -                dt.week_day = yday % 5; -        } -        dt.year = current_tm->tm_year + 3066; -        dt.season = yday / 73; -        return &dt; +    static struct disc_time dt; + +    if (current_tm == NULL) +        return NULL; + +    /* We have to know, whether we have to insert St. Tib's Day, so whether it's a leap +     * year in gregorian calendar */ +    int is_leap_year = !(current_tm->tm_year % 4) && +                       (!(current_tm->tm_year % 400) || current_tm->tm_year % 100); + +    /* If St. Tib's Day has passed, it will be necessary to skip a day. */ +    int yday = current_tm->tm_yday; + +    if (is_leap_year && yday == 59) { +        /* On St. Tibs Day we don't have to define a date */ +        dt.st_tibs_day = 1; +    } else { +        dt.st_tibs_day = 0; +        if (is_leap_year && yday > 59) +            yday -= 1; + +        dt.season_day = yday % 73; +        dt.week_day = yday % 5; +    } +    dt.year = current_tm->tm_year + 3066; +    dt.season = yday / 73; +    return &dt;  }  void print_ddate(yajl_gen json_gen, char *buffer, const char *format, time_t t) { -        char *outwalk = buffer; -        static char *form = NULL; -        struct tm current_tm; -        struct disc_time *dt; -        set_timezone(NULL);  /* Use local time. */ -        localtime_r(&t, ¤t_tm); -        if ((dt = get_ddate(¤t_tm)) == NULL) -                return; -        if (form == NULL) -                if ((form = malloc(strlen(format) + 1)) == NULL) -                        return; -        strcpy(form, format); -        outwalk += format_output(outwalk, form, dt); -        OUTPUT_FULL_TEXT(buffer); +    char *outwalk = buffer; +    static char *form = NULL; +    struct tm current_tm; +    struct disc_time *dt; +    set_timezone(NULL); /* Use local time. */ +    localtime_r(&t, ¤t_tm); +    if ((dt = get_ddate(¤t_tm)) == NULL) +        return; +    if (form == NULL) +        if ((form = malloc(strlen(format) + 1)) == NULL) +            return; +    strcpy(form, format); +    outwalk += format_output(outwalk, form, dt); +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_disk_info.c b/src/print_disk_info.c index e225923..b9047e5 100644 --- a/src/print_disk_info.c +++ b/src/print_disk_info.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdio.h>  #include <stdlib.h>  #include <string.h> @@ -22,22 +22,22 @@  #define MAX_EXPONENT 4 -static const char * const iec_symbols[MAX_EXPONENT+1] = {"", "Ki", "Mi", "Gi", "Ti"}; -static const char * const si_symbols[MAX_EXPONENT+1] = {"", "k", "M", "G", "T"}; -static const char * const custom_symbols[MAX_EXPONENT+1] = {"", "K", "M", "G", "T"}; +static const char *const iec_symbols[MAX_EXPONENT + 1] = {"", "Ki", "Mi", "Gi", "Ti"}; +static const char *const si_symbols[MAX_EXPONENT + 1] = {"", "k", "M", "G", "T"}; +static const char *const custom_symbols[MAX_EXPONENT + 1] = {"", "K", "M", "G", "T"};  /*   * Formats bytes according to the given base and set of symbols.   *   */ -static int format_bytes(char *outwalk, uint64_t bytes, uint64_t base, const char * const symbols[]) { -        double size = bytes; -        int exponent = 0; -        while (size >= base && exponent < MAX_EXPONENT) { -                size /= base; -                exponent += 1; -        } -        return sprintf(outwalk, "%.1f %sB", size, symbols[exponent]); +static int format_bytes(char *outwalk, uint64_t bytes, uint64_t base, const char *const symbols[]) { +    double size = bytes; +    int exponent = 0; +    while (size >= base && exponent < MAX_EXPONENT) { +        size /= base; +        exponent += 1; +    } +    return sprintf(outwalk, "%.1f %sB", size, symbols[exponent]);  }  /* @@ -45,13 +45,13 @@ static int format_bytes(char *outwalk, uint64_t bytes, uint64_t base, const char   *   */  static int print_bytes_human(char *outwalk, uint64_t bytes, const char *prefix_type) { -        if (strcasecmp(prefix_type, "decimal") == 0) { -                return format_bytes(outwalk, bytes, DECIMAL_BASE, si_symbols); -        } else if (strcasecmp(prefix_type, "custom") == 0) { -                return format_bytes(outwalk, bytes, BINARY_BASE, custom_symbols); -        } else { -                return format_bytes(outwalk, bytes, BINARY_BASE, iec_symbols); -        } +    if (strcasecmp(prefix_type, "decimal") == 0) { +        return format_bytes(outwalk, bytes, DECIMAL_BASE, si_symbols); +    } else if (strcasecmp(prefix_type, "custom") == 0) { +        return format_bytes(outwalk, bytes, BINARY_BASE, custom_symbols); +    } else { +        return format_bytes(outwalk, bytes, BINARY_BASE, iec_symbols); +    }  }  /* @@ -63,44 +63,44 @@ static bool below_threshold(struct statfs buf, const char *prefix_type, const ch  #else  static bool below_threshold(struct statvfs buf, const char *prefix_type, const char *threshold_type, const double low_threshold) {  #endif -        if (strcasecmp(threshold_type, "percentage_free") == 0) { -                return 100.0 * (double)buf.f_bfree / (double)buf.f_blocks < low_threshold; -        } else if (strcasecmp(threshold_type, "percentage_avail") == 0) { -                return 100.0 * (double)buf.f_bavail / (double)buf.f_blocks < low_threshold; -        } else if (strcasecmp(threshold_type, "bytes_free") == 0) { -                return (double)buf.f_bsize * (double)buf.f_bfree < low_threshold; -        } else if (strcasecmp(threshold_type, "bytes_avail") == 0) { -                return (double)buf.f_bsize * (double)buf.f_bavail < low_threshold; -        } else if (threshold_type[0] != '\0' && strncasecmp(threshold_type+1, "bytes_", strlen("bytes_")) == 0) { -                uint64_t base = strcasecmp(prefix_type, "decimal") == 0 ? DECIMAL_BASE : BINARY_BASE; -                double factor = 1; - -                switch (threshold_type[0]) { -                case 'T': -                case 't': -                        factor *= base; -                case 'G': -                case 'g': -                        factor *= base; -                case 'M': -                case 'm': -                        factor *= base; -                case 'K': -                case 'k': -                        factor *= base; -                        break; -                default: -                        return false; -                } - -                if (strcasecmp(threshold_type+1, "bytes_free") == 0) { -                        return (double)buf.f_bsize * (double)buf.f_bfree < low_threshold * factor; -                } else if (strcasecmp(threshold_type+1, "bytes_avail") == 0) { -                        return (double)buf.f_bsize * (double)buf.f_bavail < low_threshold * factor; -                } +    if (strcasecmp(threshold_type, "percentage_free") == 0) { +        return 100.0 * (double)buf.f_bfree / (double)buf.f_blocks < low_threshold; +    } else if (strcasecmp(threshold_type, "percentage_avail") == 0) { +        return 100.0 * (double)buf.f_bavail / (double)buf.f_blocks < low_threshold; +    } else if (strcasecmp(threshold_type, "bytes_free") == 0) { +        return (double)buf.f_bsize * (double)buf.f_bfree < low_threshold; +    } else if (strcasecmp(threshold_type, "bytes_avail") == 0) { +        return (double)buf.f_bsize * (double)buf.f_bavail < low_threshold; +    } else if (threshold_type[0] != '\0' && strncasecmp(threshold_type + 1, "bytes_", strlen("bytes_")) == 0) { +        uint64_t base = strcasecmp(prefix_type, "decimal") == 0 ? DECIMAL_BASE : BINARY_BASE; +        double factor = 1; + +        switch (threshold_type[0]) { +            case 'T': +            case 't': +                factor *= base; +            case 'G': +            case 'g': +                factor *= base; +            case 'M': +            case 'm': +                factor *= base; +            case 'K': +            case 'k': +                factor *= base; +                break; +            default: +                return false; +        } + +        if (strcasecmp(threshold_type + 1, "bytes_free") == 0) { +            return (double)buf.f_bsize * (double)buf.f_bfree < low_threshold * factor; +        } else if (strcasecmp(threshold_type + 1, "bytes_avail") == 0) { +            return (double)buf.f_bsize * (double)buf.f_bavail < low_threshold * factor;          } +    } -        return false; +    return false;  }  /* @@ -109,97 +109,97 @@ static bool below_threshold(struct statvfs buf, const char *prefix_type, const c   *   */  void print_disk_info(yajl_gen json_gen, char *buffer, const char *path, const char *format, const char *format_not_mounted, const char *prefix_type, const char *threshold_type, const double low_threshold) { -        const char *walk; -        char *outwalk = buffer; -        bool colorful_output = false; +    const char *walk; +    char *outwalk = buffer; +    bool colorful_output = false; -        INSTANCE(path); +    INSTANCE(path);  #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) -        struct statfs buf; +    struct statfs buf; -        if (statfs(path, &buf) == -1) -                return; +    if (statfs(path, &buf) == -1) +        return;  #else -        struct statvfs buf; - -        if (statvfs(path, &buf) == -1) -                return; - -        if (format_not_mounted != NULL) { -                FILE *mntentfile = setmntent("/etc/mtab", "r"); -                struct mntent *m; -                bool found = false; - -                while ((m = getmntent(mntentfile)) != NULL) { -                        if (strcmp(m->mnt_dir, path) == 0) { -                                found = true; -                                break; -                        } -                } -                endmntent(mntentfile); - -                if (!found) { -                        format = format_not_mounted; -                } +    struct statvfs buf; + +    if (statvfs(path, &buf) == -1) +        return; + +    if (format_not_mounted != NULL) { +        FILE *mntentfile = setmntent("/etc/mtab", "r"); +        struct mntent *m; +        bool found = false; + +        while ((m = getmntent(mntentfile)) != NULL) { +            if (strcmp(m->mnt_dir, path) == 0) { +                found = true; +                break; +            } +        } +        endmntent(mntentfile); + +        if (!found) { +            format = format_not_mounted;          } +    }  #endif -        if (low_threshold > 0 && below_threshold(buf, prefix_type, threshold_type, low_threshold)) { -                START_COLOR("color_bad"); -                colorful_output = true; +    if (low_threshold > 0 && below_threshold(buf, prefix_type, threshold_type, low_threshold)) { +        START_COLOR("color_bad"); +        colorful_output = true; +    } + +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } + +        if (BEGINS_WITH(walk + 1, "free")) { +            outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bfree, prefix_type); +            walk += strlen("free"); +        } + +        if (BEGINS_WITH(walk + 1, "used")) { +            outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * ((uint64_t)buf.f_blocks - (uint64_t)buf.f_bfree), prefix_type); +            walk += strlen("used"); +        } + +        if (BEGINS_WITH(walk + 1, "total")) { +            outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_blocks, prefix_type); +            walk += strlen("total"); +        } + +        if (BEGINS_WITH(walk + 1, "avail")) { +            outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bavail, prefix_type); +            walk += strlen("avail"); +        } + +        if (BEGINS_WITH(walk + 1, "percentage_free")) { +            outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bfree / (double)buf.f_blocks); +            walk += strlen("percentage_free"); +        } + +        if (BEGINS_WITH(walk + 1, "percentage_used_of_avail")) { +            outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bavail) / (double)buf.f_blocks); +            walk += strlen("percentage_used_of_avail"); +        } + +        if (BEGINS_WITH(walk + 1, "percentage_used")) { +            outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bfree) / (double)buf.f_blocks); +            walk += strlen("percentage_used");          } -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } - -                if (BEGINS_WITH(walk+1, "free")) { -                        outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bfree, prefix_type); -                        walk += strlen("free"); -                } - -                if (BEGINS_WITH(walk+1, "used")) { -                        outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * ((uint64_t)buf.f_blocks - (uint64_t)buf.f_bfree), prefix_type); -                        walk += strlen("used"); -                } - -                if (BEGINS_WITH(walk+1, "total")) { -                        outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_blocks, prefix_type); -                        walk += strlen("total"); -                } - -                if (BEGINS_WITH(walk+1, "avail")) { -                        outwalk += print_bytes_human(outwalk, (uint64_t)buf.f_bsize * (uint64_t)buf.f_bavail, prefix_type); -                        walk += strlen("avail"); -                } - -                if (BEGINS_WITH(walk+1, "percentage_free")) { -                        outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bfree / (double)buf.f_blocks); -                        walk += strlen("percentage_free"); -                } - -                if (BEGINS_WITH(walk+1, "percentage_used_of_avail")) { -                        outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bavail) / (double)buf.f_blocks); -                        walk += strlen("percentage_used_of_avail"); -                } - -                if (BEGINS_WITH(walk+1, "percentage_used")) { -                        outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)(buf.f_blocks - buf.f_bfree) / (double)buf.f_blocks); -                        walk += strlen("percentage_used"); -                } - -                if (BEGINS_WITH(walk+1, "percentage_avail")) { -                        outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bavail / (double)buf.f_blocks); -                        walk += strlen("percentage_avail"); -                } +        if (BEGINS_WITH(walk + 1, "percentage_avail")) { +            outwalk += sprintf(outwalk, "%.01f%%", 100.0 * (double)buf.f_bavail / (double)buf.f_blocks); +            walk += strlen("percentage_avail");          } +    } -        if (colorful_output) -                END_COLOR; +    if (colorful_output) +        END_COLOR; -        *outwalk = '\0'; -        OUTPUT_FULL_TEXT(buffer); +    *outwalk = '\0'; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_eth_info.c b/src/print_eth_info.c index c446da4..af5a757 100644 --- a/src/print_eth_info.c +++ b/src/print_eth_info.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <string.h>  #include <limits.h>  #include <stdio.h> @@ -16,15 +16,15 @@  #if defined(LINUX)  #include <linux/ethtool.h>  #include <linux/sockios.h> -#define PART_ETHSPEED  "E: %s (%d Mbit/s)" +#define PART_ETHSPEED "E: %s (%d Mbit/s)"  #endif  #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)  #include <net/if_media.h> -#define IFM_TYPE_MATCH(dt, t)                       \ -        (IFM_TYPE((dt)) == 0 || IFM_TYPE((dt)) == IFM_TYPE((t))) +#define IFM_TYPE_MATCH(dt, t) \ +    (IFM_TYPE((dt)) == 0 || IFM_TYPE((dt)) == IFM_TYPE((t))) -#define PART_ETHSPEED  "E: %s (%s)" +#define PART_ETHSPEED "E: %s (%s)"  #endif  #if defined(__OpenBSD__) || defined(__NetBSD__) @@ -34,75 +34,76 @@  static int print_eth_speed(char *outwalk, const char *interface) {  #if defined(LINUX) -        /* This code path requires root privileges */ -        int ethspeed = 0; -        struct ifreq ifr; -        struct ethtool_cmd ecmd; - -        ecmd.cmd = ETHTOOL_GSET; -        (void)memset(&ifr, 0, sizeof(ifr)); -        ifr.ifr_data = (caddr_t)&ecmd; -        (void)strcpy(ifr.ifr_name, interface); -        if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0) { -                ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed); -                return sprintf(outwalk, "%d Mbit/s", ethspeed); -        } else return sprintf(outwalk, "?"); +    /* This code path requires root privileges */ +    int ethspeed = 0; +    struct ifreq ifr; +    struct ethtool_cmd ecmd; + +    ecmd.cmd = ETHTOOL_GSET; +    (void)memset(&ifr, 0, sizeof(ifr)); +    ifr.ifr_data = (caddr_t)&ecmd; +    (void)strcpy(ifr.ifr_name, interface); +    if (ioctl(general_socket, SIOCETHTOOL, &ifr) == 0) { +        ethspeed = (ecmd.speed == USHRT_MAX ? 0 : ecmd.speed); +        return sprintf(outwalk, "%d Mbit/s", ethspeed); +    } else +        return sprintf(outwalk, "?");  #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) -        char *ethspeed; -        struct ifmediareq ifm; -        (void)memset(&ifm, 0, sizeof(ifm)); -        (void)strncpy(ifm.ifm_name, interface, sizeof(ifm.ifm_name)); -        int ret = ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifm); - -        /* Get the description of the media type, partially taken from -         * FreeBSD's ifconfig */ -        const struct ifmedia_description *desc; -        struct ifmedia_description ifm_subtype_descriptions[] = -                IFM_SUBTYPE_ETHERNET_DESCRIPTIONS; - -        for (desc = ifm_subtype_descriptions; -             desc->ifmt_string != NULL; -             desc++) { -            if (IFM_TYPE_MATCH(desc->ifmt_word, ifm.ifm_active) && -                IFM_SUBTYPE(desc->ifmt_word) == IFM_SUBTYPE(ifm.ifm_active)) -                break; -        } -        ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?"); -        return sprintf(outwalk, "%s", ethspeed); +    char *ethspeed; +    struct ifmediareq ifm; +    (void)memset(&ifm, 0, sizeof(ifm)); +    (void)strncpy(ifm.ifm_name, interface, sizeof(ifm.ifm_name)); +    int ret = ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifm); + +    /* Get the description of the media type, partially taken from +     * FreeBSD's ifconfig */ +    const struct ifmedia_description *desc; +    struct ifmedia_description ifm_subtype_descriptions[] = +        IFM_SUBTYPE_ETHERNET_DESCRIPTIONS; + +    for (desc = ifm_subtype_descriptions; +         desc->ifmt_string != NULL; +         desc++) { +        if (IFM_TYPE_MATCH(desc->ifmt_word, ifm.ifm_active) && +            IFM_SUBTYPE(desc->ifmt_word) == IFM_SUBTYPE(ifm.ifm_active)) +            break; +    } +    ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?"); +    return sprintf(outwalk, "%s", ethspeed);  #elif defined(__OpenBSD__) || defined(__NetBSD__) -	char *ethspeed; -	struct ifmediareq ifmr; +    char *ethspeed; +    struct ifmediareq ifmr; -	(void) memset(&ifmr, 0, sizeof(ifmr)); -	(void) strlcpy(ifmr.ifm_name, interface, sizeof(ifmr.ifm_name)); +    (void)memset(&ifmr, 0, sizeof(ifmr)); +    (void)strlcpy(ifmr.ifm_name, interface, sizeof(ifmr.ifm_name)); -	if (ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) { -                if (errno != E2BIG) -			return sprintf(outwalk, "?"); -	} +    if (ioctl(general_socket, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) { +        if (errno != E2BIG) +            return sprintf(outwalk, "?"); +    } -	struct ifmedia_description *desc; -	struct ifmedia_description ifm_subtype_descriptions[] = -	    IFM_SUBTYPE_DESCRIPTIONS; +    struct ifmedia_description *desc; +    struct ifmedia_description ifm_subtype_descriptions[] = +        IFM_SUBTYPE_DESCRIPTIONS; -        for (desc = ifm_subtype_descriptions; desc->ifmt_string != NULL; desc++) { -		/* +    for (desc = ifm_subtype_descriptions; desc->ifmt_string != NULL; desc++) { +        /*  		 * Skip these non-informative values and go right ahead to the  		 * actual speeds.  		 */ -		if (BEGINS_WITH(desc->ifmt_string, "autoselect") || -		    BEGINS_WITH(desc->ifmt_string, "auto")) -			continue; +        if (BEGINS_WITH(desc->ifmt_string, "autoselect") || +            BEGINS_WITH(desc->ifmt_string, "auto")) +            continue; -		if (IFM_TYPE_MATCH(desc->ifmt_word, ifmr.ifm_active) && -		    IFM_SUBTYPE(desc->ifmt_word) == IFM_SUBTYPE(ifmr.ifm_active)) -			break; -        } -        ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?"); -        return sprintf(outwalk, "%s", ethspeed); +        if (IFM_TYPE_MATCH(desc->ifmt_word, ifmr.ifm_active) && +            IFM_SUBTYPE(desc->ifmt_word) == IFM_SUBTYPE(ifmr.ifm_active)) +            break; +    } +    ethspeed = (desc->ifmt_string != NULL ? desc->ifmt_string : "?"); +    return sprintf(outwalk, "%s", ethspeed);  #else -	return sprintf(outwalk, "?"); +    return sprintf(outwalk, "?");  #endif  } @@ -111,36 +112,36 @@ static int print_eth_speed(char *outwalk, const char *interface) {   *   */  void print_eth_info(yajl_gen json_gen, char *buffer, const char *interface, const char *format_up, const char *format_down) { -        const char *walk; -        const char *ip_address = get_ip_addr(interface); -        char *outwalk = buffer; +    const char *walk; +    const char *ip_address = get_ip_addr(interface); +    char *outwalk = buffer; + +    INSTANCE(interface); + +    if (ip_address == NULL) { +        START_COLOR("color_bad"); +        outwalk += sprintf(outwalk, "%s", format_down); +        goto out; +    } -        INSTANCE(interface); +    START_COLOR("color_good"); -        if (ip_address == NULL) { -                START_COLOR("color_bad"); -                outwalk += sprintf(outwalk, "%s", format_down); -                goto out; +    for (walk = format_up; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue;          } -        START_COLOR("color_good"); - -        for (walk = format_up; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } - -                if (BEGINS_WITH(walk+1, "ip")) { -                        outwalk += sprintf(outwalk, "%s", ip_address); -                        walk += strlen("ip"); -                } else if (BEGINS_WITH(walk+1, "speed")) { -                        outwalk += print_eth_speed(outwalk, interface); -                        walk += strlen("speed"); -                } +        if (BEGINS_WITH(walk + 1, "ip")) { +            outwalk += sprintf(outwalk, "%s", ip_address); +            walk += strlen("ip"); +        } else if (BEGINS_WITH(walk + 1, "speed")) { +            outwalk += print_eth_speed(outwalk, interface); +            walk += strlen("speed");          } +    }  out: -        END_COLOR; -        OUTPUT_FULL_TEXT(buffer); +    END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_ip_addr.c b/src/print_ip_addr.c index 909a8b2..09b0992 100644 --- a/src/print_ip_addr.c +++ b/src/print_ip_addr.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <sys/types.h>  #include <sys/socket.h>  #include <netinet/in.h> @@ -18,50 +18,49 @@   *   */  const char *get_ip_addr(const char *interface) { -        static char part[512]; -        socklen_t len = sizeof(struct sockaddr_in); -        memset(part, 0, sizeof(part)); +    static char part[512]; +    socklen_t len = sizeof(struct sockaddr_in); +    memset(part, 0, sizeof(part)); -        struct ifaddrs *ifaddr, *addrp; -        bool found = false; +    struct ifaddrs *ifaddr, *addrp; +    bool found = false; -        getifaddrs(&ifaddr); +    getifaddrs(&ifaddr); -        if (ifaddr == NULL) -                return NULL; +    if (ifaddr == NULL) +        return NULL; -        /* Skip until we are at the AF_INET address of interface */ -        for (addrp = ifaddr; +    /* Skip until we are at the AF_INET address of interface */ +    for (addrp = ifaddr; -             (addrp != NULL && -              (strcmp(addrp->ifa_name, interface) != 0 || -               addrp->ifa_addr == NULL || -               addrp->ifa_addr->sa_family != AF_INET)); +         (addrp != NULL && +          (strcmp(addrp->ifa_name, interface) != 0 || +           addrp->ifa_addr == NULL || +           addrp->ifa_addr->sa_family != AF_INET)); -             addrp = addrp->ifa_next) { -                /* Check if the interface is down */ -                if (strcmp(addrp->ifa_name, interface) != 0) -                        continue; -                found = true; -                if ((addrp->ifa_flags & IFF_RUNNING) == 0) { -                        freeifaddrs(ifaddr); -                        return NULL; -                } +         addrp = addrp->ifa_next) { +        /* Check if the interface is down */ +        if (strcmp(addrp->ifa_name, interface) != 0) +            continue; +        found = true; +        if ((addrp->ifa_flags & IFF_RUNNING) == 0) { +            freeifaddrs(ifaddr); +            return NULL;          } +    } -        if (addrp == NULL) { -                freeifaddrs(ifaddr); -                return (found ? "no IP" : NULL); -        } - -        int ret; -        if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) { -                fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret)); -                freeifaddrs(ifaddr); -                return "no IP"; -        } +    if (addrp == NULL) { +        freeifaddrs(ifaddr); +        return (found ? "no IP" : NULL); +    } +    int ret; +    if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) { +        fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));          freeifaddrs(ifaddr); -        return part; -} +        return "no IP"; +    } +    freeifaddrs(ifaddr); +    return part; +} diff --git a/src/print_ipv6_addr.c b/src/print_ipv6_addr.c index 7ff9c97..a24119f 100644 --- a/src/print_ipv6_addr.c +++ b/src/print_ipv6_addr.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <sys/types.h>  #include <sys/socket.h>  #include <netinet/in.h> @@ -16,48 +16,48 @@  #include "i3status.h"  static char *get_sockname(struct addrinfo *addr) { -        static char buf[INET6_ADDRSTRLEN+1]; -        struct sockaddr_storage local; -        int ret; -        int fd; - -        if ((fd = socket(addr->ai_family, SOCK_DGRAM, 0)) == -1) { -                perror("socket()"); -                return NULL; -        } - -        /* Since the socket was created with SOCK_DGRAM, this is -         * actually not establishing a connection or generating -         * any other network traffic. Instead, as a side-effect, -         * it saves the local address with which packets would -         * be sent to the destination. */ -        if (connect(fd, addr->ai_addr, addr->ai_addrlen) == -1) { -                /* We don’t display the error here because most -                 * likely, there just is no IPv6 connectivity. -                 * Thus, don’t spam the user’s console but just -                 * try the next address. */ -                (void)close(fd); -                return NULL; -        } +    static char buf[INET6_ADDRSTRLEN + 1]; +    struct sockaddr_storage local; +    int ret; +    int fd; -        socklen_t local_len = sizeof(struct sockaddr_storage); -        if (getsockname(fd, (struct sockaddr*)&local, &local_len) == -1) { -                perror("getsockname()"); -                (void)close(fd); -                return NULL; -        } +    if ((fd = socket(addr->ai_family, SOCK_DGRAM, 0)) == -1) { +        perror("socket()"); +        return NULL; +    } + +    /* Since the socket was created with SOCK_DGRAM, this is +     * actually not establishing a connection or generating +     * any other network traffic. Instead, as a side-effect, +     * it saves the local address with which packets would +     * be sent to the destination. */ +    if (connect(fd, addr->ai_addr, addr->ai_addrlen) == -1) { +        /* We don’t display the error here because most +         * likely, there just is no IPv6 connectivity. +         * Thus, don’t spam the user’s console but just +         * try the next address. */ +        (void)close(fd); +        return NULL; +    } -        memset(buf, 0, INET6_ADDRSTRLEN + 1); -        if ((ret = getnameinfo((struct sockaddr*)&local, local_len, -                               buf, sizeof(buf), NULL, 0, -                               NI_NUMERICHOST)) != 0) { -                fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret)); -                (void)close(fd); -                return NULL; -        } +    socklen_t local_len = sizeof(struct sockaddr_storage); +    if (getsockname(fd, (struct sockaddr *)&local, &local_len) == -1) { +        perror("getsockname()"); +        (void)close(fd); +        return NULL; +    } +    memset(buf, 0, INET6_ADDRSTRLEN + 1); +    if ((ret = getnameinfo((struct sockaddr *)&local, local_len, +                           buf, sizeof(buf), NULL, 0, +                           NI_NUMERICHOST)) != 0) { +        fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));          (void)close(fd); -        return buf; +        return NULL; +    } + +    (void)close(fd); +    return buf;  }  /* @@ -65,82 +65,82 @@ static char *get_sockname(struct addrinfo *addr) {   * The char * is statically allocated and mustn't be freed   */  static char *get_ipv6_addr(void) { -        struct addrinfo hints; -        struct addrinfo *result, *resp; -        static struct addrinfo *cached = NULL; - -        /* To save dns lookups (if they are not cached locally) and creating -         * sockets, we save the fd and keep it open. */ -        if (cached != NULL) -                return get_sockname(cached); - -        memset(&hints, 0, sizeof(struct addrinfo)); -        hints.ai_family = AF_INET6; -        hints.ai_socktype = SOCK_DGRAM; - -        /* We use the public IPv6 of the K root server here. It doesn’t matter -         * which IPv6 address we use (we don’t even send any packets), as long -         * as it’s considered global by the kernel. -         * NB: We don’t use a hostname since that would trigger a DNS lookup. -         * By using an IPv6 address, getaddrinfo() will *not* do a DNS lookup, -         * but return the address in the appropriate struct. */ -        if (getaddrinfo("2001:7fd::1", "domain", &hints, &result) != 0) { -                /* We don’t display the error here because most -                 * likely, there just is no connectivity. -                 * Thus, don’t spam the user’s console. */ -                return NULL; -        } - -        for (resp = result; resp != NULL; resp = resp->ai_next) { -                char *addr_string = get_sockname(resp); -                /* If we could not get our own address and there is more than -                 * one result for resolving k.root-servers.net, we cannot -                 * cache. Otherwise, no matter if we got IPv6 connectivity or -                 * not, we will cache the (single) result and are done. */ -                if (!addr_string && result->ai_next != NULL) -                        continue; - -                if ((cached = malloc(sizeof(struct addrinfo))) == NULL) -                        return NULL; -                memcpy(cached, resp, sizeof(struct addrinfo)); -                if ((cached->ai_addr = malloc(resp->ai_addrlen)) == NULL) { -                        cached = NULL; -                        return NULL; -                } -                memcpy(cached->ai_addr, resp->ai_addr, resp->ai_addrlen); -                freeaddrinfo(result); -                return addr_string; +    struct addrinfo hints; +    struct addrinfo *result, *resp; +    static struct addrinfo *cached = NULL; + +    /* To save dns lookups (if they are not cached locally) and creating +     * sockets, we save the fd and keep it open. */ +    if (cached != NULL) +        return get_sockname(cached); + +    memset(&hints, 0, sizeof(struct addrinfo)); +    hints.ai_family = AF_INET6; +    hints.ai_socktype = SOCK_DGRAM; + +    /* We use the public IPv6 of the K root server here. It doesn’t matter +     * which IPv6 address we use (we don’t even send any packets), as long +     * as it’s considered global by the kernel. +     * NB: We don’t use a hostname since that would trigger a DNS lookup. +     * By using an IPv6 address, getaddrinfo() will *not* do a DNS lookup, +     * but return the address in the appropriate struct. */ +    if (getaddrinfo("2001:7fd::1", "domain", &hints, &result) != 0) { +        /* We don’t display the error here because most +         * likely, there just is no connectivity. +         * Thus, don’t spam the user’s console. */ +        return NULL; +    } + +    for (resp = result; resp != NULL; resp = resp->ai_next) { +        char *addr_string = get_sockname(resp); +        /* If we could not get our own address and there is more than +         * one result for resolving k.root-servers.net, we cannot +         * cache. Otherwise, no matter if we got IPv6 connectivity or +         * not, we will cache the (single) result and are done. */ +        if (!addr_string && result->ai_next != NULL) +            continue; + +        if ((cached = malloc(sizeof(struct addrinfo))) == NULL) +            return NULL; +        memcpy(cached, resp, sizeof(struct addrinfo)); +        if ((cached->ai_addr = malloc(resp->ai_addrlen)) == NULL) { +            cached = NULL; +            return NULL;          } - +        memcpy(cached->ai_addr, resp->ai_addr, resp->ai_addrlen);          freeaddrinfo(result); -        return NULL; +        return addr_string; +    } + +    freeaddrinfo(result); +    return NULL;  }  void print_ipv6_info(yajl_gen json_gen, char *buffer, const char *format_up, const char *format_down) { -        const char *walk; -        char *addr_string = get_ipv6_addr(); -        char *outwalk = buffer; - -        if (addr_string == NULL) { -                START_COLOR("color_bad"); -                outwalk += sprintf(outwalk, "%s", format_down); -                END_COLOR; -                OUTPUT_FULL_TEXT(buffer); -                return; -        } +    const char *walk; +    char *addr_string = get_ipv6_addr(); +    char *outwalk = buffer; -        START_COLOR("color_good"); -        for (walk = format_up; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } - -                if (BEGINS_WITH(walk+1, "ip")) { -                        outwalk += sprintf(outwalk, "%s", addr_string); -                        walk += strlen("ip"); -                } -        } +    if (addr_string == NULL) { +        START_COLOR("color_bad"); +        outwalk += sprintf(outwalk, "%s", format_down);          END_COLOR;          OUTPUT_FULL_TEXT(buffer); +        return; +    } + +    START_COLOR("color_good"); +    for (walk = format_up; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } + +        if (BEGINS_WITH(walk + 1, "ip")) { +            outwalk += sprintf(outwalk, "%s", addr_string); +            walk += strlen("ip"); +        } +    } +    END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_load.c b/src/print_load.c index 6e61ae6..7ba4ae1 100644 --- a/src/print_load.c +++ b/src/print_load.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include "i3status.h"  #include <stdlib.h>  #include <stdio.h> @@ -7,51 +7,51 @@  #include <yajl/yajl_version.h>  void print_load(yajl_gen json_gen, char *buffer, const char *format, const float max_threshold) { -        char *outwalk = buffer; -        /* Get load */ +    char *outwalk = buffer; +/* Get load */  #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__DragonFly__) -        double loadavg[3]; -        const char *walk; -        bool colorful_output = false; - -        if (getloadavg(loadavg, 3) == -1) -                goto error; - -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } -                if (loadavg[0] >= max_threshold) { -                        START_COLOR("color_bad"); -                        colorful_output = true; -                } - -                if (BEGINS_WITH(walk+1, "1min")) { -                        outwalk += sprintf(outwalk, "%1.2f", loadavg[0]); -                        walk += strlen("1min"); -                } - -                if (BEGINS_WITH(walk+1, "5min")) { -                        outwalk += sprintf(outwalk, "%1.2f", loadavg[1]); -                        walk += strlen("5min"); -                } - -                if (BEGINS_WITH(walk+1, "15min")) { -                        outwalk += sprintf(outwalk, "%1.2f", loadavg[2]); -                        walk += strlen("15min"); -                } -                if (colorful_output) -                        END_COLOR; +    double loadavg[3]; +    const char *walk; +    bool colorful_output = false; + +    if (getloadavg(loadavg, 3) == -1) +        goto error; + +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } +        if (loadavg[0] >= max_threshold) { +            START_COLOR("color_bad"); +            colorful_output = true; +        } + +        if (BEGINS_WITH(walk + 1, "1min")) { +            outwalk += sprintf(outwalk, "%1.2f", loadavg[0]); +            walk += strlen("1min"); +        } + +        if (BEGINS_WITH(walk + 1, "5min")) { +            outwalk += sprintf(outwalk, "%1.2f", loadavg[1]); +            walk += strlen("5min"); +        } + +        if (BEGINS_WITH(walk + 1, "15min")) { +            outwalk += sprintf(outwalk, "%1.2f", loadavg[2]); +            walk += strlen("15min");          } +        if (colorful_output) +            END_COLOR; +    } -        *outwalk = '\0'; -        OUTPUT_FULL_TEXT(buffer); +    *outwalk = '\0'; +    OUTPUT_FULL_TEXT(buffer); -        return; +    return;  error:  #endif -        OUTPUT_FULL_TEXT("cant read load"); -        (void)fputs("i3status: Cannot read system load using getloadavg()\n", stderr); +    OUTPUT_FULL_TEXT("cant read load"); +    (void)fputs("i3status: Cannot read system load using getloadavg()\n", stderr);  } diff --git a/src/print_path_exists.c b/src/print_path_exists.c index a2fcb14..1b231e6 100644 --- a/src/print_path_exists.c +++ b/src/print_path_exists.c @@ -1,3 +1,4 @@ +// vim:ts=4:sw=4:expandtab  #include <stdio.h>  #include <string.h>  #include <yajl/yajl_gen.h> @@ -6,30 +7,30 @@  #include "i3status.h"  void print_path_exists(yajl_gen json_gen, char *buffer, const char *title, const char *path, const char *format) { -        const char *walk; -        char *outwalk = buffer; -        struct stat st; -        const bool exists = (stat(path, &st) == 0); +    const char *walk; +    char *outwalk = buffer; +    struct stat st; +    const bool exists = (stat(path, &st) == 0); -        INSTANCE(path); +    INSTANCE(path); -        START_COLOR((exists ? "color_good" : "color_bad")); +    START_COLOR((exists ? "color_good" : "color_bad")); -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } -                if (BEGINS_WITH(walk+1, "title")) { -                        outwalk += sprintf(outwalk, "%s", title); -                        walk += strlen("title"); -                } else if (BEGINS_WITH(walk+1, "status")) { -                        outwalk += sprintf(outwalk, "%s", (exists ? "yes" : "no")); -                        walk += strlen("status"); -                } +        if (BEGINS_WITH(walk + 1, "title")) { +            outwalk += sprintf(outwalk, "%s", title); +            walk += strlen("title"); +        } else if (BEGINS_WITH(walk + 1, "status")) { +            outwalk += sprintf(outwalk, "%s", (exists ? "yes" : "no")); +            walk += strlen("status");          } +    } -        END_COLOR; -        OUTPUT_FULL_TEXT(buffer); +    END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_run_watch.c b/src/print_run_watch.c index bc0d6dc..3d1ec3f 100644 --- a/src/print_run_watch.c +++ b/src/print_run_watch.c @@ -1,3 +1,4 @@ +// vim:ts=4:sw=4:expandtab  #include <stdio.h>  #include <string.h>  #include <yajl/yajl_gen.h> @@ -5,29 +6,29 @@  #include "i3status.h"  void print_run_watch(yajl_gen json_gen, char *buffer, const char *title, const char *pidfile, const char *format) { -	bool running = process_runs(pidfile); -	const char *walk; -	char *outwalk = buffer; +    bool running = process_runs(pidfile); +    const char *walk; +    char *outwalk = buffer; -	INSTANCE(pidfile); +    INSTANCE(pidfile); -	START_COLOR((running ? "color_good" : "color_bad")); +    START_COLOR((running ? "color_good" : "color_bad")); -        for (walk = format; *walk != '\0'; walk++) { -                if (*walk != '%') { -			*(outwalk++) = *walk; -                        continue; -                } +    for (walk = format; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } -                if (BEGINS_WITH(walk+1, "title")) { -			outwalk += sprintf(outwalk, "%s", title); -                        walk += strlen("title"); -                } else if (BEGINS_WITH(walk+1, "status")) { -			outwalk += sprintf(outwalk, "%s", (running ? "yes" : "no")); -                        walk += strlen("status"); -                } +        if (BEGINS_WITH(walk + 1, "title")) { +            outwalk += sprintf(outwalk, "%s", title); +            walk += strlen("title"); +        } else if (BEGINS_WITH(walk + 1, "status")) { +            outwalk += sprintf(outwalk, "%s", (running ? "yes" : "no")); +            walk += strlen("status");          } +    } -	END_COLOR; -	OUTPUT_FULL_TEXT(buffer); +    END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_time.c b/src/print_time.c index d19d08b..edbc828 100644 --- a/src/print_time.c +++ b/src/print_time.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <time.h>  #include <stdio.h>  #include <stdlib.h> @@ -13,34 +13,34 @@ static const char *local_timezone = NULL;  static const char *current_timezone = NULL;  void set_timezone(const char *tz) { -        if (!local_timezone_init) { -                /* First call, initialize. */ -                local_timezone = getenv("TZ"); -                local_timezone_init = true; -        } -        if (tz == NULL || tz[0] == '\0') { -                /* User wants localtime. */ -                tz = local_timezone; -        } -        if (tz != current_timezone) { -                if (tz) { -                        setenv("TZ", tz, 1); -                } else { -                        unsetenv("TZ"); -                } -                tzset(); -                current_timezone = tz; +    if (!local_timezone_init) { +        /* First call, initialize. */ +        local_timezone = getenv("TZ"); +        local_timezone_init = true; +    } +    if (tz == NULL || tz[0] == '\0') { +        /* User wants localtime. */ +        tz = local_timezone; +    } +    if (tz != current_timezone) { +        if (tz) { +            setenv("TZ", tz, 1); +        } else { +            unsetenv("TZ");          } +        tzset(); +        current_timezone = tz; +    }  }  void print_time(yajl_gen json_gen, char *buffer, const char *format, const char *tz, time_t t) { -        char *outwalk = buffer; -        struct tm tm; +    char *outwalk = buffer; +    struct tm tm; -        /* Convert time and format output. */ -        set_timezone(tz); -        localtime_r(&t, &tm); -        outwalk += strftime(outwalk, 4095, format, &tm); -        *outwalk = '\0'; -        OUTPUT_FULL_TEXT(buffer); +    /* Convert time and format output. */ +    set_timezone(tz); +    localtime_r(&t, &tm); +    outwalk += strftime(outwalk, 4095, format, &tm); +    *outwalk = '\0'; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_volume.c b/src/print_volume.c index 93868e3..ef1c913 100644 --- a/src/print_volume.c +++ b/src/print_volume.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <time.h>  #include <string.h>  #include <stdlib.h> @@ -27,154 +27,155 @@  #include "queue.h"  void print_volume(yajl_gen json_gen, char *buffer, const char *fmt, const char *fmt_muted, const char *device, const char *mixer, int mixer_idx) { -        char *outwalk = buffer; -	int pbval = 1; - -        /* Printing volume only works with ALSA at the moment */ -        if (output_format == O_I3BAR) { -                char *instance; -                asprintf(&instance, "%s.%s.%d", device, mixer, mixer_idx); -                INSTANCE(instance); -                free(instance); -        } +    char *outwalk = buffer; +    int pbval = 1; + +    /* Printing volume only works with ALSA at the moment */ +    if (output_format == O_I3BAR) { +        char *instance; +        asprintf(&instance, "%s.%s.%d", device, mixer, mixer_idx); +        INSTANCE(instance); +        free(instance); +    }  #ifdef LINUX -	int err; -	snd_mixer_t *m; -	snd_mixer_selem_id_t *sid; -	snd_mixer_elem_t *elem; -	long min, max, val; -	int avg; - -	if ((err = snd_mixer_open(&m, 0)) < 0) { -		fprintf(stderr, "i3status: ALSA: Cannot open mixer: %s\n", snd_strerror(err)); -		goto out; -	} - -	/* Attach this mixer handle to the given device */ -	if ((err = snd_mixer_attach(m, device)) < 0) { -		fprintf(stderr, "i3status: ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err)); -		snd_mixer_close(m); -		goto out; -	} - -	/* Register this mixer */ -	if ((err = snd_mixer_selem_register(m, NULL, NULL)) < 0) { -		fprintf(stderr, "i3status: ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err)); -		snd_mixer_close(m); -		goto out; -	} - -	if ((err = snd_mixer_load(m)) < 0) { -		fprintf(stderr, "i3status: ALSA: snd_mixer_load: %s\n", snd_strerror(err)); -		snd_mixer_close(m); -		goto out; -	} - -	snd_mixer_selem_id_malloc(&sid); -	if (sid == NULL) { -		snd_mixer_close(m); -		goto out; -	} - -	/* Find the given mixer */ -	snd_mixer_selem_id_set_index(sid, mixer_idx); -	snd_mixer_selem_id_set_name(sid, mixer); -	if (!(elem = snd_mixer_find_selem(m, sid))) { -		fprintf(stderr, "i3status: ALSA: Cannot find mixer %s (index %i)\n", -			snd_mixer_selem_id_get_name(sid), snd_mixer_selem_id_get_index(sid)); -		snd_mixer_close(m); -		snd_mixer_selem_id_free(sid); -		goto out; -	} - -	/* Get the volume range to convert the volume later */ -	snd_mixer_selem_get_playback_volume_range(elem, &min, &max); - -	snd_mixer_handle_events (m); -	snd_mixer_selem_get_playback_volume (elem, 0, &val); -	if (max != 100) { -		float avgf = ((float)val / max) * 100; -		avg = (int)avgf; -		avg = (avgf - avg < 0.5 ? avg : (avg+1)); -	} else avg = (int)val; - -	/* Check for mute */ -	if (snd_mixer_selem_has_playback_switch(elem)) { -		if ((err = snd_mixer_selem_get_playback_switch(elem, 0, &pbval)) < 0) -			fprintf (stderr, "i3status: ALSA: playback_switch: %s\n", snd_strerror(err)); -		if (!pbval)  { -			START_COLOR("color_degraded"); -			fmt = fmt_muted; -		} -	} - -	snd_mixer_close(m); -	snd_mixer_selem_id_free(sid); - -	const char *walk = fmt; -	for (; *walk != '\0'; walk++) { -		if (*walk != '%') { -                        *(outwalk++) = *walk; -			continue; -		} -		if (BEGINS_WITH(walk+1, "%")) { -			outwalk += sprintf(outwalk, "%%"); -			walk += strlen("%"); -		} -		if (BEGINS_WITH(walk+1, "volume")) { -			outwalk += sprintf(outwalk, "%d%%", avg); -			walk += strlen("volume"); -		} -	} +    int err; +    snd_mixer_t *m; +    snd_mixer_selem_id_t *sid; +    snd_mixer_elem_t *elem; +    long min, max, val; +    int avg; + +    if ((err = snd_mixer_open(&m, 0)) < 0) { +        fprintf(stderr, "i3status: ALSA: Cannot open mixer: %s\n", snd_strerror(err)); +        goto out; +    } + +    /* Attach this mixer handle to the given device */ +    if ((err = snd_mixer_attach(m, device)) < 0) { +        fprintf(stderr, "i3status: ALSA: Cannot attach mixer to device: %s\n", snd_strerror(err)); +        snd_mixer_close(m); +        goto out; +    } + +    /* Register this mixer */ +    if ((err = snd_mixer_selem_register(m, NULL, NULL)) < 0) { +        fprintf(stderr, "i3status: ALSA: snd_mixer_selem_register: %s\n", snd_strerror(err)); +        snd_mixer_close(m); +        goto out; +    } + +    if ((err = snd_mixer_load(m)) < 0) { +        fprintf(stderr, "i3status: ALSA: snd_mixer_load: %s\n", snd_strerror(err)); +        snd_mixer_close(m); +        goto out; +    } + +    snd_mixer_selem_id_malloc(&sid); +    if (sid == NULL) { +        snd_mixer_close(m); +        goto out; +    } + +    /* Find the given mixer */ +    snd_mixer_selem_id_set_index(sid, mixer_idx); +    snd_mixer_selem_id_set_name(sid, mixer); +    if (!(elem = snd_mixer_find_selem(m, sid))) { +        fprintf(stderr, "i3status: ALSA: Cannot find mixer %s (index %i)\n", +                snd_mixer_selem_id_get_name(sid), snd_mixer_selem_id_get_index(sid)); +        snd_mixer_close(m); +        snd_mixer_selem_id_free(sid); +        goto out; +    } + +    /* Get the volume range to convert the volume later */ +    snd_mixer_selem_get_playback_volume_range(elem, &min, &max); + +    snd_mixer_handle_events(m); +    snd_mixer_selem_get_playback_volume(elem, 0, &val); +    if (max != 100) { +        float avgf = ((float)val / max) * 100; +        avg = (int)avgf; +        avg = (avgf - avg < 0.5 ? avg : (avg + 1)); +    } else +        avg = (int)val; + +    /* Check for mute */ +    if (snd_mixer_selem_has_playback_switch(elem)) { +        if ((err = snd_mixer_selem_get_playback_switch(elem, 0, &pbval)) < 0) +            fprintf(stderr, "i3status: ALSA: playback_switch: %s\n", snd_strerror(err)); +        if (!pbval) { +            START_COLOR("color_degraded"); +            fmt = fmt_muted; +        } +    } + +    snd_mixer_close(m); +    snd_mixer_selem_id_free(sid); + +    const char *walk = fmt; +    for (; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue; +        } +        if (BEGINS_WITH(walk + 1, "%")) { +            outwalk += sprintf(outwalk, "%%"); +            walk += strlen("%"); +        } +        if (BEGINS_WITH(walk + 1, "volume")) { +            outwalk += sprintf(outwalk, "%d%%", avg); +            walk += strlen("volume"); +        } +    }  #endif  #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) -        char *mixerpath; -        char defaultmixer[] = "/dev/mixer"; -        int mixfd, vol, devmask = 0; -        pbval = 1; - -        if (mixer_idx > 0) -                asprintf(&mixerpath, "/dev/mixer%d", mixer_idx); -        else -                mixerpath = defaultmixer; - -        if ((mixfd = open(mixerpath, O_RDWR)) < 0) -                return; - -        if (mixer_idx > 0) -                free(mixerpath); - -        if (ioctl(mixfd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) -                return; -        if (ioctl(mixfd, MIXER_READ(0),&vol) == -1) -                return; - -        if (((vol & 0x7f) == 0) && (((vol >> 8) & 0x7f) == 0)) { -                START_COLOR("color_degraded"); -                pbval = 0; +    char *mixerpath; +    char defaultmixer[] = "/dev/mixer"; +    int mixfd, vol, devmask = 0; +    pbval = 1; + +    if (mixer_idx > 0) +        asprintf(&mixerpath, "/dev/mixer%d", mixer_idx); +    else +        mixerpath = defaultmixer; + +    if ((mixfd = open(mixerpath, O_RDWR)) < 0) +        return; + +    if (mixer_idx > 0) +        free(mixerpath); + +    if (ioctl(mixfd, SOUND_MIXER_READ_DEVMASK, &devmask) == -1) +        return; +    if (ioctl(mixfd, MIXER_READ(0), &vol) == -1) +        return; + +    if (((vol & 0x7f) == 0) && (((vol >> 8) & 0x7f) == 0)) { +        START_COLOR("color_degraded"); +        pbval = 0; +    } + +    const char *walk = fmt; +    for (; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue;          } - -        const char *walk = fmt; -        for (; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } -                if (BEGINS_WITH(walk+1, "%")) { -                        outwalk += sprintf(outwalk, "%%"); -                        walk += strlen("%"); -                } -                if (BEGINS_WITH(walk+1, "volume")) { -                        outwalk += sprintf(outwalk, "%d%%", vol & 0x7f); -                        walk += strlen("volume"); -                } +        if (BEGINS_WITH(walk + 1, "%")) { +            outwalk += sprintf(outwalk, "%%"); +            walk += strlen("%"); +        } +        if (BEGINS_WITH(walk + 1, "volume")) { +            outwalk += sprintf(outwalk, "%d%%", vol & 0x7f); +            walk += strlen("volume");          } -        close(mixfd); +    } +    close(mixfd);  #endif  out: -        *outwalk = '\0'; -        if (!pbval) -		END_COLOR; -        OUTPUT_FULL_TEXT(buffer); +    *outwalk = '\0'; +    if (!pbval) +        END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/print_wireless_info.c b/src/print_wireless_info.c index 7f7c52e..eae942b 100644 --- a/src/print_wireless_info.c +++ b/src/print_wireless_info.c @@ -1,4 +1,4 @@ -// vim:ts=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdio.h>  #include <string.h>  #include <yajl/yajl_gen.h> @@ -51,383 +51,380 @@  #include "i3status.h" -#define WIRELESS_INFO_FLAG_HAS_ESSID                    (1 << 0) -#define WIRELESS_INFO_FLAG_HAS_QUALITY                  (1 << 1) -#define WIRELESS_INFO_FLAG_HAS_SIGNAL                   (1 << 2) -#define WIRELESS_INFO_FLAG_HAS_NOISE                    (1 << 3) -#define WIRELESS_INFO_FLAG_HAS_FREQUENCY                (1 << 4) +#define WIRELESS_INFO_FLAG_HAS_ESSID (1 << 0) +#define WIRELESS_INFO_FLAG_HAS_QUALITY (1 << 1) +#define WIRELESS_INFO_FLAG_HAS_SIGNAL (1 << 2) +#define WIRELESS_INFO_FLAG_HAS_NOISE (1 << 3) +#define WIRELESS_INFO_FLAG_HAS_FREQUENCY (1 << 4)  #define PERCENT_VALUE(value, total) ((int)(value * 100 / (float)total + 0.5f))  typedef struct { -        int flags; -        char essid[IW_ESSID_MAX_SIZE + 1]; -        int quality; -        int quality_max; -        int quality_average; -        int signal_level; -        int signal_level_max; -        int noise_level; -        int noise_level_max; -        int bitrate; -        double frequency; +    int flags; +    char essid[IW_ESSID_MAX_SIZE + 1]; +    int quality; +    int quality_max; +    int quality_average; +    int signal_level; +    int signal_level_max; +    int noise_level; +    int noise_level_max; +    int bitrate; +    double frequency;  } wireless_info_t;  static int get_wireless_info(const char *interface, wireless_info_t *info) { -        memset(info, 0, sizeof(wireless_info_t)); +    memset(info, 0, sizeof(wireless_info_t));  #ifdef LINUX -        int skfd = iw_sockets_open(); -        if (skfd < 0) { -                perror("iw_sockets_open"); -                return 0; -        } - -        wireless_config wcfg; -        if (iw_get_basic_config(skfd, interface, &wcfg) < 0) { -            close(skfd); -            return 0; -        } - -        if (wcfg.has_essid && wcfg.essid_on) { -                info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; -                strncpy(&info->essid[0], wcfg.essid, IW_ESSID_MAX_SIZE); -                info->essid[IW_ESSID_MAX_SIZE] = '\0'; -        } - -        if (wcfg.has_freq) { -                info->frequency = wcfg.freq; -                info->flags |= WIRELESS_INFO_FLAG_HAS_FREQUENCY; -        } - -        /* If the function iw_get_stats does not return proper stats, the -           wifi is considered as down. -           Since ad-hoc network does not have theses stats, we need to return -           here for this mode. */ -        if (wcfg.mode == 1) { -                close(skfd); -                return 1; -        } +    int skfd = iw_sockets_open(); +    if (skfd < 0) { +        perror("iw_sockets_open"); +        return 0; +    } + +    wireless_config wcfg; +    if (iw_get_basic_config(skfd, interface, &wcfg) < 0) { +        close(skfd); +        return 0; +    } -        /* Wireless quality is a relative value in a driver-specific range. -           Signal and noise level can be either relative or absolute values -           in dBm. Furthermore, noise and quality can be expressed directly -           in dBm or in RCPI (802.11k), which we convert to dBm. When those -           values are expressed directly in dBm, they range from -192 to 63, -           and since the values are packed into 8 bits, we need to perform -           8-bit arithmetic on them. Assume absolute values if everything -           else fails (driver bug). */ - -        iwrange range; -        if (iw_get_range_info(skfd, interface, &range) < 0) { -                close(skfd); -                return 0; -        } +    if (wcfg.has_essid && wcfg.essid_on) { +        info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; +        strncpy(&info->essid[0], wcfg.essid, IW_ESSID_MAX_SIZE); +        info->essid[IW_ESSID_MAX_SIZE] = '\0'; +    } + +    if (wcfg.has_freq) { +        info->frequency = wcfg.freq; +        info->flags |= WIRELESS_INFO_FLAG_HAS_FREQUENCY; +    } + +    /* If the function iw_get_stats does not return proper stats, the +     * wifi is considered as down. +     * Since ad-hoc network does not have theses stats, we need to return +     * here for this mode. */ +    if (wcfg.mode == 1) { +        close(skfd); +        return 1; +    } + +    /* Wireless quality is a relative value in a driver-specific range. +     * Signal and noise level can be either relative or absolute values +     * in dBm. Furthermore, noise and quality can be expressed directly +     * in dBm or in RCPI (802.11k), which we convert to dBm. When those +     * values are expressed directly in dBm, they range from -192 to 63, +     * and since the values are packed into 8 bits, we need to perform +     * 8-bit arithmetic on them. Assume absolute values if everything +     * else fails (driver bug). */ + +    iwrange range; +    if (iw_get_range_info(skfd, interface, &range) < 0) { +        close(skfd); +        return 0; +    } -        iwstats stats; -        if (iw_get_stats(skfd, interface, &stats, &range, 1) < 0) { -                close(skfd); -                return 0; +    iwstats stats; +    if (iw_get_stats(skfd, interface, &stats, &range, 1) < 0) { +        close(skfd); +        return 0; +    } + +    if (stats.qual.level != 0 || (stats.qual.updated & (IW_QUAL_DBM | IW_QUAL_RCPI))) { +        if (!(stats.qual.updated & IW_QUAL_QUAL_INVALID)) { +            info->quality = stats.qual.qual; +            info->quality_max = range.max_qual.qual; +            info->quality_average = range.avg_qual.qual; +            info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY;          } -        if (stats.qual.level != 0 || (stats.qual.updated & (IW_QUAL_DBM | IW_QUAL_RCPI))) { -                if (!(stats.qual.updated & IW_QUAL_QUAL_INVALID)) { -                        info->quality = stats.qual.qual; -                        info->quality_max = range.max_qual.qual; -                        info->quality_average = range.avg_qual.qual; -                        info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY; -                } - -                if (stats.qual.updated & IW_QUAL_RCPI) { -                        if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { -                                info->signal_level = stats.qual.level / 2.0 - 110 + 0.5; -                                info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; -                        } -                        if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { -                                info->noise_level = stats.qual.noise / 2.0 - 110 + 0.5; -                                info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; -                        } -                } -                else { -                        if ((stats.qual.updated & IW_QUAL_DBM) || stats.qual.level > range.max_qual.level) { -                                if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { -                                        info->signal_level = stats.qual.level; -                                        if (info->signal_level > 63) -                                                info->signal_level -= 256; -                                        info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; -                                } -                                if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { -                                        info->noise_level = stats.qual.noise; -                                        if (info->noise_level > 63) -                                                info->noise_level -= 256; -                                        info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; -                                } -                        } -                        else { -                                if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { -                                        info->signal_level = stats.qual.level; -                                        info->signal_level_max = range.max_qual.level; -                                        info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; -                                } -                                if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { -                                        info->noise_level = stats.qual.noise; -                                        info->noise_level_max = range.max_qual.noise; -                                        info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; -                                } -                        } +        if (stats.qual.updated & IW_QUAL_RCPI) { +            if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { +                info->signal_level = stats.qual.level / 2.0 - 110 + 0.5; +                info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; +            } +            if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { +                info->noise_level = stats.qual.noise / 2.0 - 110 + 0.5; +                info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; +            } +        } else { +            if ((stats.qual.updated & IW_QUAL_DBM) || stats.qual.level > range.max_qual.level) { +                if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { +                    info->signal_level = stats.qual.level; +                    if (info->signal_level > 63) +                        info->signal_level -= 256; +                    info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL;                  } -        } -        else { -                if (!(stats.qual.updated & IW_QUAL_QUAL_INVALID)) { -                        info->quality = stats.qual.qual; -                        info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY; +                if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { +                    info->noise_level = stats.qual.noise; +                    if (info->noise_level > 63) +                        info->noise_level -= 256; +                    info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE;                  } +            } else {                  if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { -                        info->quality = stats.qual.level; -                        info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; +                    info->signal_level = stats.qual.level; +                    info->signal_level_max = range.max_qual.level; +                    info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL;                  }                  if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { -                        info->quality = stats.qual.noise; -                        info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; +                    info->noise_level = stats.qual.noise; +                    info->noise_level_max = range.max_qual.noise; +                    info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE;                  } +            } +        } +    } else { +        if (!(stats.qual.updated & IW_QUAL_QUAL_INVALID)) { +            info->quality = stats.qual.qual; +            info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY; +        } +        if (!(stats.qual.updated & IW_QUAL_LEVEL_INVALID)) { +            info->quality = stats.qual.level; +            info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL;          } +        if (!(stats.qual.updated & IW_QUAL_NOISE_INVALID)) { +            info->quality = stats.qual.noise; +            info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; +        } +    } -        struct iwreq wrq; -        if (iw_get_ext(skfd, interface, SIOCGIWRATE, &wrq) >= 0) -                info->bitrate = wrq.u.bitrate.value; +    struct iwreq wrq; +    if (iw_get_ext(skfd, interface, SIOCGIWRATE, &wrq) >= 0) +        info->bitrate = wrq.u.bitrate.value; -        close(skfd); -        return 1; +    close(skfd); +    return 1;  #endif  #if defined(__FreeBSD__) || defined(__DragonFly__) -        int s, len, inwid; -        uint8_t buf[24 * 1024], *cp; -        struct ieee80211req na; -        char network_id[IEEE80211_NWID_LEN + 1]; - -        if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) -                return (0); - -        memset(&na, 0, sizeof(na)); -        strlcpy(na.i_name, interface, sizeof(na.i_name)); -        na.i_type = IEEE80211_IOC_SSID; -        na.i_data = &info->essid[0]; -        na.i_len = IEEE80211_NWID_LEN + 1; -        if ((inwid = ioctl(s, SIOCG80211, (caddr_t)&na)) == -1) { -                close(s); -                return (0); -        } -        if (inwid == 0) { -                if (na.i_len <= IEEE80211_NWID_LEN) -                        len = na.i_len + 1; -                else -                        len = IEEE80211_NWID_LEN + 1; -                info->essid[len -1] = '\0'; -        } else { -                close(s); -                return (0); -        } -        info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; +    int s, len, inwid; +    uint8_t buf[24 * 1024], *cp; +    struct ieee80211req na; +    char network_id[IEEE80211_NWID_LEN + 1]; + +    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) +        return (0); + +    memset(&na, 0, sizeof(na)); +    strlcpy(na.i_name, interface, sizeof(na.i_name)); +    na.i_type = IEEE80211_IOC_SSID; +    na.i_data = &info->essid[0]; +    na.i_len = IEEE80211_NWID_LEN + 1; +    if ((inwid = ioctl(s, SIOCG80211, (caddr_t)&na)) == -1) { +        close(s); +        return (0); +    } +    if (inwid == 0) { +        if (na.i_len <= IEEE80211_NWID_LEN) +            len = na.i_len + 1; +        else +            len = IEEE80211_NWID_LEN + 1; +        info->essid[len - 1] = '\0'; +    } else { +        close(s); +        return (0); +    } +    info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; + +    memset(&na, 0, sizeof(na)); +    strlcpy(na.i_name, interface, sizeof(na.i_name)); +    na.i_type = IEEE80211_IOC_SCAN_RESULTS; +    na.i_data = buf; +    na.i_len = sizeof(buf); + +    if (ioctl(s, SIOCG80211, (caddr_t)&na) == -1) { +        printf("fail\n"); +        close(s); +        return (0); +    } + +    close(s); +    len = na.i_len; +    cp = buf; +    struct ieee80211req_scan_result *sr; +    uint8_t *vp; +    sr = (struct ieee80211req_scan_result *)cp; +    vp = (u_int8_t *)(sr + 1); +    strlcpy(network_id, (const char *)vp, sr->isr_ssid_len + 1); +    if (!strcmp(network_id, &info->essid[0])) { +        info->signal_level = sr->isr_rssi; +        info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; +        info->noise_level = sr->isr_noise; +        info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; +        info->quality = sr->isr_intval; +        info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY; +    } + +    return 1; +#endif +#ifdef __OpenBSD__ +    struct ifreq ifr; +    struct ieee80211_bssid bssid; +    struct ieee80211_nwid nwid; +    struct ieee80211_nodereq nr; -        memset(&na, 0, sizeof(na)); -        strlcpy(na.i_name, interface, sizeof(na.i_name)); -        na.i_type = IEEE80211_IOC_SCAN_RESULTS; -        na.i_data = buf; -        na.i_len = sizeof(buf); +    struct ether_addr ea; -        if (ioctl(s, SIOCG80211, (caddr_t)&na) == -1) { -                printf("fail\n"); -                close(s); -                return (0); -        } +    int s, len, ibssid, inwid; +    u_int8_t zero_bssid[IEEE80211_ADDR_LEN]; + +    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) +        return (0); + +    memset(&ifr, 0, sizeof(ifr)); +    ifr.ifr_data = (caddr_t)&nwid; +    (void)strlcpy(ifr.ifr_name, interface, sizeof(ifr.ifr_name)); +    inwid = ioctl(s, SIOCG80211NWID, (caddr_t)&ifr); +    memset(&bssid, 0, sizeof(bssid)); +    strlcpy(bssid.i_name, interface, sizeof(bssid.i_name)); +    ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + +    if (ibssid != 0 || inwid != 0) {          close(s); -        len = na.i_len; -        cp = buf; -        struct ieee80211req_scan_result *sr; -        uint8_t *vp; -        sr = (struct ieee80211req_scan_result *)cp; -        vp = (u_int8_t *)(sr + 1); -        strlcpy(network_id, (const char *)vp, sr->isr_ssid_len + 1); -        if (!strcmp(network_id, &info->essid[0])) { -                info->signal_level = sr->isr_rssi; +        return 0; +    } + +    /* NWID */ +    { +        if (nwid.i_len <= IEEE80211_NWID_LEN) +            len = nwid.i_len + 1; +        else +            len = IEEE80211_NWID_LEN + 1; + +        strncpy(&info->essid[0], nwid.i_nwid, len); +        info->essid[IW_ESSID_MAX_SIZE] = '\0'; +        info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; +    } + +    /* Signal strength */ +    { +        memset(&zero_bssid, 0, sizeof(zero_bssid)); +        if (ibssid == 0 && memcmp(bssid.i_bssid, zero_bssid, IEEE80211_ADDR_LEN) != 0) { +            memcpy(&ea.ether_addr_octet, bssid.i_bssid, sizeof(ea.ether_addr_octet)); + +            bzero(&nr, sizeof(nr)); +            bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); +            strlcpy(nr.nr_ifname, interface, sizeof(nr.nr_ifname)); + +            if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { +                if (nr.nr_max_rssi) +                    info->signal_level_max = IEEE80211_NODEREQ_RSSI(&nr); +                else +                    info->signal_level = nr.nr_rssi; +                  info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; -                info->noise_level = sr->isr_noise; -                info->flags |= WIRELESS_INFO_FLAG_HAS_NOISE; -                info->quality = sr->isr_intval; -                info->flags |= WIRELESS_INFO_FLAG_HAS_QUALITY; +            }          } +    } -        return 1; +    close(s); +    return 1;  #endif -#ifdef __OpenBSD__ -	struct ifreq ifr; -	struct ieee80211_bssid bssid; -	struct ieee80211_nwid nwid; -	struct ieee80211_nodereq nr; - -	struct ether_addr ea; - -        int s, len, ibssid, inwid; -	u_int8_t zero_bssid[IEEE80211_ADDR_LEN]; - -	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) -		return (0); - -        memset(&ifr, 0, sizeof(ifr)); -        ifr.ifr_data = (caddr_t)&nwid; -	(void)strlcpy(ifr.ifr_name, interface, sizeof(ifr.ifr_name)); -        inwid = ioctl(s, SIOCG80211NWID, (caddr_t)&ifr); - -	memset(&bssid, 0, sizeof(bssid)); -	strlcpy(bssid.i_name, interface, sizeof(bssid.i_name)); -	ibssid = ioctl(s, SIOCG80211BSSID, &bssid); - -	if (ibssid != 0 || inwid != 0) { -		close(s); -		return 0; -	} - -	/* NWID */ -	{ -		if (nwid.i_len <= IEEE80211_NWID_LEN) -			len = nwid.i_len + 1; -		else -			len = IEEE80211_NWID_LEN + 1; - -		strncpy(&info->essid[0], nwid.i_nwid, len); -		info->essid[IW_ESSID_MAX_SIZE] = '\0'; -		info->flags |= WIRELESS_INFO_FLAG_HAS_ESSID; -	} - -	/* Signal strength */ -	{ -		memset(&zero_bssid, 0, sizeof(zero_bssid)); -		if (ibssid == 0 && memcmp(bssid.i_bssid, zero_bssid, IEEE80211_ADDR_LEN) != 0) { -			memcpy(&ea.ether_addr_octet, bssid.i_bssid, sizeof(ea.ether_addr_octet)); - -			bzero(&nr, sizeof(nr)); -			bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); -			strlcpy(nr.nr_ifname, interface, sizeof(nr.nr_ifname)); - -			if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { -				if (nr.nr_max_rssi) -					info->signal_level_max = IEEE80211_NODEREQ_RSSI(&nr); -				else -					info->signal_level = nr.nr_rssi; - -		                info->flags |= WIRELESS_INFO_FLAG_HAS_SIGNAL; -			} -		} -	} - -	close(s); -	return 1; -#endif -	return 0; +    return 0;  }  void print_wireless_info(yajl_gen json_gen, char *buffer, const char *interface, const char *format_up, const char *format_down) { -        const char *walk; -        char *outwalk = buffer; -        wireless_info_t info; - -        INSTANCE(interface); - -	const char *ip_address = get_ip_addr(interface); -	if (ip_address == NULL) { -		START_COLOR("color_bad"); -		outwalk += sprintf(outwalk, "%s", format_down); -		goto out; -	} - -        if (get_wireless_info(interface, &info)) { -                walk = format_up; -                if (info.flags & WIRELESS_INFO_FLAG_HAS_QUALITY) -                        START_COLOR((info.quality < info.quality_average ? "color_degraded" : "color_good")); -                else -                        START_COLOR("color_good"); -        } else { -                walk = format_down; -                START_COLOR("color_bad"); +    const char *walk; +    char *outwalk = buffer; +    wireless_info_t info; + +    INSTANCE(interface); + +    const char *ip_address = get_ip_addr(interface); +    if (ip_address == NULL) { +        START_COLOR("color_bad"); +        outwalk += sprintf(outwalk, "%s", format_down); +        goto out; +    } + +    if (get_wireless_info(interface, &info)) { +        walk = format_up; +        if (info.flags & WIRELESS_INFO_FLAG_HAS_QUALITY) +            START_COLOR((info.quality < info.quality_average ? "color_degraded" : "color_good")); +        else +            START_COLOR("color_good"); +    } else { +        walk = format_down; +        START_COLOR("color_bad"); +    } + +    for (; *walk != '\0'; walk++) { +        if (*walk != '%') { +            *(outwalk++) = *walk; +            continue;          } -        for (; *walk != '\0'; walk++) { -                if (*walk != '%') { -                        *(outwalk++) = *walk; -                        continue; -                } - -                if (BEGINS_WITH(walk+1, "quality")) { -                        if (info.flags & WIRELESS_INFO_FLAG_HAS_QUALITY) { -                                if (info.quality_max) -                                        outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.quality, info.quality_max)); -                                else -                                        outwalk += sprintf(outwalk, "%d", info.quality); -                        } else { -                                *(outwalk++) = '?'; -                        } -                        walk += strlen("quality"); -                } +        if (BEGINS_WITH(walk + 1, "quality")) { +            if (info.flags & WIRELESS_INFO_FLAG_HAS_QUALITY) { +                if (info.quality_max) +                    outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.quality, info.quality_max)); +                else +                    outwalk += sprintf(outwalk, "%d", info.quality); +            } else { +                *(outwalk++) = '?'; +            } +            walk += strlen("quality"); +        } -                if (BEGINS_WITH(walk+1, "signal")) { -                        if (info.flags & WIRELESS_INFO_FLAG_HAS_SIGNAL) { -                                if (info.signal_level_max) -                                        outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.signal_level, info.signal_level_max)); -                                else -                                        outwalk += sprintf(outwalk, "%d dBm", info.signal_level); -                        } else { -                                *(outwalk++) = '?'; -                        } -                        walk += strlen("signal"); -                } +        if (BEGINS_WITH(walk + 1, "signal")) { +            if (info.flags & WIRELESS_INFO_FLAG_HAS_SIGNAL) { +                if (info.signal_level_max) +                    outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.signal_level, info.signal_level_max)); +                else +                    outwalk += sprintf(outwalk, "%d dBm", info.signal_level); +            } else { +                *(outwalk++) = '?'; +            } +            walk += strlen("signal"); +        } -                if (BEGINS_WITH(walk+1, "noise")) { -                        if (info.flags & WIRELESS_INFO_FLAG_HAS_NOISE) { -                                if (info.noise_level_max) -                                        outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.noise_level, info.noise_level_max)); -                                else -                                        outwalk += sprintf(outwalk, "%d dBm", info.noise_level); -                        } else { -                                *(outwalk++) = '?'; -                        } -                        walk += strlen("noise"); -                } +        if (BEGINS_WITH(walk + 1, "noise")) { +            if (info.flags & WIRELESS_INFO_FLAG_HAS_NOISE) { +                if (info.noise_level_max) +                    outwalk += sprintf(outwalk, "%03d%%", PERCENT_VALUE(info.noise_level, info.noise_level_max)); +                else +                    outwalk += sprintf(outwalk, "%d dBm", info.noise_level); +            } else { +                *(outwalk++) = '?'; +            } +            walk += strlen("noise"); +        } -                if (BEGINS_WITH(walk+1, "essid")) { -                        if (info.flags & WIRELESS_INFO_FLAG_HAS_ESSID) -                                outwalk += sprintf(outwalk, "%s", info.essid); -                        else -                                *(outwalk++) = '?'; -                        walk += strlen("essid"); -                } +        if (BEGINS_WITH(walk + 1, "essid")) { +            if (info.flags & WIRELESS_INFO_FLAG_HAS_ESSID) +                outwalk += sprintf(outwalk, "%s", info.essid); +            else +                *(outwalk++) = '?'; +            walk += strlen("essid"); +        } -                if (BEGINS_WITH(walk+1, "frequency")) { -                        if (info.flags & WIRELESS_INFO_FLAG_HAS_FREQUENCY) -                                outwalk += sprintf(outwalk, "%1.1f GHz", info.frequency / 1e9); -                        else -                                *(outwalk++) = '?'; -                        walk += strlen("frequency"); -                } +        if (BEGINS_WITH(walk + 1, "frequency")) { +            if (info.flags & WIRELESS_INFO_FLAG_HAS_FREQUENCY) +                outwalk += sprintf(outwalk, "%1.1f GHz", info.frequency / 1e9); +            else +                *(outwalk++) = '?'; +            walk += strlen("frequency"); +        } -                if (BEGINS_WITH(walk+1, "ip")) { -			outwalk += sprintf(outwalk, "%s", ip_address); -			walk += strlen("ip"); -                } +        if (BEGINS_WITH(walk + 1, "ip")) { +            outwalk += sprintf(outwalk, "%s", ip_address); +            walk += strlen("ip"); +        }  #ifdef LINUX -                if (BEGINS_WITH(walk+1, "bitrate")) { -                        char br_buffer[128]; +        if (BEGINS_WITH(walk + 1, "bitrate")) { +            char br_buffer[128]; -                        iw_print_bitrate(br_buffer, sizeof(br_buffer), info.bitrate); +            iw_print_bitrate(br_buffer, sizeof(br_buffer), info.bitrate); -                        outwalk += sprintf(outwalk, "%s", br_buffer); -                        walk += strlen("bitrate"); -                } -#endif +            outwalk += sprintf(outwalk, "%s", br_buffer); +            walk += strlen("bitrate");          } +#endif +    }  out: -        END_COLOR; -        OUTPUT_FULL_TEXT(buffer); +    END_COLOR; +    OUTPUT_FULL_TEXT(buffer);  } diff --git a/src/process_runs.c b/src/process_runs.c index 1836507..b5e8f11 100644 --- a/src/process_runs.c +++ b/src/process_runs.c @@ -1,4 +1,4 @@ -// vim:ts=8:sw=8:expandtab +// vim:ts=4:sw=4:expandtab  #include <stdbool.h>  #include <glob.h>  #include <string.h> @@ -20,30 +20,30 @@   *   */  bool process_runs(const char *path) { -        static char pidbuf[16]; -        static glob_t globbuf; -        memset(pidbuf, 0, sizeof(pidbuf)); +    static char pidbuf[16]; +    static glob_t globbuf; +    memset(pidbuf, 0, sizeof(pidbuf)); -        if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0) -                die("glob() failed\n"); -        if (globbuf.gl_pathc == 0) { -                /* No glob matches, the specified path does not contain a wildcard. */ -                globfree(&globbuf); -                if (!slurp(path, pidbuf, sizeof(pidbuf))) -                        return false; -                return (kill(strtol(pidbuf, NULL, 10), 0) == 0 || errno == EPERM); +    if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0) +        die("glob() failed\n"); +    if (globbuf.gl_pathc == 0) { +        /* No glob matches, the specified path does not contain a wildcard. */ +        globfree(&globbuf); +        if (!slurp(path, pidbuf, sizeof(pidbuf))) +            return false; +        return (kill(strtol(pidbuf, NULL, 10), 0) == 0 || errno == EPERM); +    } +    for (size_t i = 0; i < globbuf.gl_pathc; i++) { +        if (!slurp(globbuf.gl_pathv[i], pidbuf, sizeof(pidbuf))) { +            globfree(&globbuf); +            return false;          } -        for (size_t i = 0; i < globbuf.gl_pathc; i++) { -                if (!slurp(globbuf.gl_pathv[i], pidbuf, sizeof(pidbuf))) { -                        globfree(&globbuf); -                        return false; -                } -                if (kill(strtol(pidbuf, NULL, 10), 0) == 0 || errno == EPERM) { -                        globfree(&globbuf); -                        return true; -                } +        if (kill(strtol(pidbuf, NULL, 10), 0) == 0 || errno == EPERM) { +            globfree(&globbuf); +            return true;          } -        globfree(&globbuf); +    } +    globfree(&globbuf); -        return false; +    return false;  }  | 
