]> git.sur5r.net Git - i3/i3status/blob - src/print_load.c
able to print percentage
[i3/i3status] / src / print_load.c
1 // vim:ts=4:sw=4:expandtab
2 #include "i3status.h"
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <yajl/yajl_gen.h>
7 #include <yajl/yajl_version.h>
8
9 void print_load(yajl_gen json_gen, char *buffer, const char *format, const char *format_above_threshold, const float max_threshold) {
10     char *outwalk = buffer;
11 /* Get load */
12
13 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) || defined(sun) || defined(__DragonFly__)
14     double loadavg[3];
15     const char *selected_format = format;
16     const char *walk;
17     bool colorful_output = false;
18
19     if (getloadavg(loadavg, 3) == -1)
20         goto error;
21
22     if (loadavg[0] >= max_threshold) {
23         START_COLOR("color_bad");
24         colorful_output = true;
25         if (format_above_threshold != NULL)
26             selected_format = format_above_threshold;
27     }
28
29     for (walk = selected_format; *walk != '\0'; walk++) {
30         if (*walk != '%') {
31             *(outwalk++) = *walk;
32
33         } else if (BEGINS_WITH(walk + 1, "1min")) {
34             outwalk += sprintf(outwalk, "%1.2f", loadavg[0]);
35             walk += strlen("1min");
36
37         } else if (BEGINS_WITH(walk + 1, "5min")) {
38             outwalk += sprintf(outwalk, "%1.2f", loadavg[1]);
39             walk += strlen("5min");
40
41         } else if (BEGINS_WITH(walk + 1, "15min")) {
42             outwalk += sprintf(outwalk, "%1.2f", loadavg[2]);
43             walk += strlen("15min");
44
45         } else {
46             *(outwalk++) = '%';
47         }
48     }
49
50     if (colorful_output)
51         END_COLOR;
52
53     *outwalk = '\0';
54     OUTPUT_FULL_TEXT(buffer);
55
56     return;
57 error:
58 #endif
59     OUTPUT_FULL_TEXT("cant read load");
60     (void)fputs("i3status: Cannot read system load using getloadavg()\n", stderr);
61 }