]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
44d13a479c644b05d16f7c1b88f582300fc3e721
[i3/i3status] / wmiistatus.c
1 /*
2  * Generates a status line for use with wmii or other minimal window managers
3  *
4  *
5  * Copyright (c) 2008 Michael Stapelberg and contributors
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without modification,
9  * are permitted provided that the following conditions are met:
10  *
11  * * Redistributions of source code must retain the above copyright notice, this
12  *   list of conditions and the following disclaimer.
13  *
14  * * Redistributions in binary form must reproduce the above copyright notice, this
15  *   list of conditions and the following disclaimer in the documentation and/or other
16  *   materials provided with the distribution.
17  *
18  * * Neither the name of Michael Stapelberg nor the names of contributors
19  *   may be used to endorse or promote products derived from this software without
20  *   specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
31  * DAMAGE.
32  *
33  */
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <time.h>
40 #include <stdbool.h>
41 #include <stdarg.h>
42 #include <unistd.h>
43 #include <stdlib.h>
44 #include <ctype.h>
45 #include <net/if.h>
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <glob.h>
51 #include <dirent.h>
52
53 #include "wmiistatus.h"
54 #include "config.h"
55
56 static void cleanup_rbar_dir() {
57         struct dirent *ent;
58         DIR *dir;
59         char pathbuf[strlen(wmii_path)+256+1];
60
61         if ((dir = opendir(wmii_path)) == NULL)
62                 exit(-3);
63
64         while ((ent = readdir(dir)) != NULL) {
65                 if (ent->d_type == DT_REG) {
66                         sprintf(pathbuf, "%s%s", wmii_path, ent->d_name);
67                         unlink(pathbuf);
68                 }
69         }
70
71         closedir(dir);
72 }
73
74 static void create_file(const char *name) {
75         char pathbuf[strlen(wmii_path)+256+1];
76
77         sprintf(pathbuf, "%s%s", wmii_path, name);
78         int fd = creat(pathbuf, S_IRUSR | S_IWUSR);
79         if (fd < 0)
80                 exit(-4);
81 #ifdef USE_COLORS
82         write(fd, "#888888 " WMII_NORMCOLORS, strlen("#888888 " WMII_NORMCOLORS));
83 #endif
84         close(fd);
85 }
86
87 static void write_to_statusbar(const char *name, const char *message) {
88         char pathbuf[strlen(wmii_path)+256+1];
89
90         sprintf(pathbuf, "%s%s", wmii_path, name);
91         int fd = open(pathbuf, O_RDWR);
92         if (fd == -1)
93                 exit(-2);
94         write(fd, message, strlen(message));
95         close(fd);
96 }
97
98 static void write_error_to_statusbar(const char *message) {
99         cleanup_rbar_dir();
100         write_to_statusbar("error", message);
101 }
102
103 /*
104  * Write errormessage to statusbar and exit
105  *
106  */
107 static void die(const char *fmt, ...) {
108         char buffer[512];
109         va_list ap;
110         va_start(ap, fmt);
111         vsprintf(buffer, fmt, ap);
112         va_end(ap);
113
114         write_error_to_statusbar(buffer);
115         exit(-1);
116 }
117
118 static char *skip_character(char *input, char character, int amount) {
119         char *walk;
120         int len = strlen(input),
121             blanks = 0;
122
123         for (walk = input; ((walk - input) < len) && (blanks < amount); walk++)
124                 if (*walk == character)
125                         blanks++;
126
127         return (walk == input ? walk : walk-1);
128 }
129
130 /*
131  * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
132  * not the full capacity.
133  *
134  */
135 static char *get_battery_info() {
136         char buf[1024];
137         static char part[512];
138         char *walk, *last = buf;
139         int fd = open(battery, O_RDONLY);
140         if (fd == -1)
141                 die("Could not open %s", battery);
142         int full_design = -1,
143             remaining = -1,
144             present_rate = -1;
145         charging_status_t status = CS_DISCHARGING;
146         memset(part, '\0', sizeof(part));
147         read(fd, buf, sizeof(buf));
148         for (walk = buf; (walk-buf) < 1024; walk++)
149                 if (*walk == '=') {
150                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
151                                 full_design = atoi(walk+1);
152                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW"))
153                                 remaining = atoi(walk+1);
154                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
155                                 present_rate = atoi(walk+1);
156                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
157                                 status = CS_CHARGING;
158                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
159                                 status = CS_FULL;
160                 } else if (*walk == '\n')
161                         last = walk+1;
162         close(fd);
163
164         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
165                 float remaining_time, perc;
166                 if (status == CS_CHARGING)
167                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
168                 else if (status == CS_DISCHARGING)
169                         remaining_time = ((float)remaining / (float)present_rate);
170                 else {
171                         snprintf(part, sizeof(part), "FULL");
172                         return part;
173                 }
174                 perc = ((float)remaining / (float)full_design);
175
176                 int seconds = (int)(remaining_time * 3600.0);
177                 int hours = seconds / 3600;
178                 seconds -= (hours * 3600);
179                 int minutes = seconds / 60;
180                 seconds -= (minutes * 60);
181
182                 sprintf(part, "%s %.02f%% %02d:%02d:%02d", (status == CS_CHARGING? "CHR" : "BAT"),
183                         (perc * 100), hours, minutes, seconds);
184         }
185         return part;
186 }
187
188 /*
189  * Just parses /proc/net/wireless
190  *
191  */
192 static char *get_wireless_info() {
193         char buf[1024];
194         static char part[512];
195         char *interfaces;
196         memset(buf, '\0', sizeof(buf));
197         memset(part, '\0', sizeof(part));
198
199         int fd = open("/proc/net/wireless", O_RDONLY);
200         if (fd == -1)
201                 die("Could not open /proc/net/wireless");
202         read(fd, buf, sizeof(buf));
203         close(fd);
204
205         interfaces = skip_character(buf, '\n', 2) + 1;
206         while (interfaces < buf+strlen(buf)) {
207                 while (isspace((int)*interfaces))
208                         interfaces++;
209                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
210                         /* Skip status field (0000) */
211                         interfaces += strlen(wlan_interface) + 2;
212                         interfaces = skip_character(interfaces, ' ', 1);
213                         while (isspace((int)*interfaces))
214                                 interfaces++;
215                         int quality = atoi(interfaces);
216                         /* For some reason, I get 255 sometimes */
217                         if ((quality == 255) || (quality == 0)) {
218 #ifdef USE_COLORS
219                         snprintf(part, sizeof(part), "#FF0000 " WMII_NORMCOLORS " W: down");
220 #else
221                         snprintf(part, sizeof(part), "W: down");
222 #endif
223
224                         } else {
225                                 snprintf(part, sizeof(part), "W: (%02d%%) ", quality);
226                                 char *ip_address = get_ip_address(wlan_interface);
227                                 strcpy(part+strlen(part), ip_address);
228                         }
229
230                         return part;
231                 }
232                 interfaces = skip_character(interfaces, '\n', 1) + 1;
233         }
234
235         return part;
236 }
237
238 static char *get_ip_address(const char *interface) {
239         static char part[512];
240         struct ifreq ifr;
241         memset(part, '\0', sizeof(part));
242
243         int fd = socket(AF_INET, SOCK_DGRAM, 0);
244
245         strcpy(ifr.ifr_name, interface);
246         if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
247                 die("Could not get interface flags (SIOCGIFFLAGS)");
248
249         if (!(ifr.ifr_flags & IFF_UP) ||
250             !(ifr.ifr_flags & IFF_RUNNING)) {
251                 close(fd);
252                 return NULL;
253         }
254
255         strcpy(ifr.ifr_name, interface);
256         ifr.ifr_addr.sa_family = AF_INET;
257         if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
258                 struct sockaddr_in addr;
259                 memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
260                 inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, sizeof(struct sockaddr_in));
261                 if (strlen(part) == 0)
262                         sprintf(part, "no IP");
263         }
264
265         close(fd);
266         return part;
267 }
268
269 static char *get_eth_info() {
270         static char part[512];
271         char *ip_address = get_ip_address(eth_interface);
272
273         if (ip_address == NULL)
274                 snprintf(part, sizeof(part), "E: down");
275         else snprintf(part, sizeof(part), "E: %s", ip_address);
276
277         return part;
278 }
279
280 /*
281  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
282  *
283  */
284 static bool process_runs(const char *path) {
285         char pidbuf[512],
286              procbuf[512],
287              *walk;
288         int n;
289         static glob_t globbuf;
290         struct stat statbuf;
291
292         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
293                 die("glob() failed");
294         const char *real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
295         int fd = open(real_path, O_RDONLY);
296         globfree(&globbuf);
297         if (fd < 0)
298                 return false;
299         n = read(fd, pidbuf, sizeof(pidbuf));
300         if (n > 0)
301                 pidbuf[n] = '\0';
302         close(fd);
303         for (walk = pidbuf; *walk != '\0'; walk++)
304                 if (!isdigit((int)(*walk))) {
305                         *walk = '\0';
306                         break;
307                 }
308         sprintf(procbuf, "/proc/%s", pidbuf);
309         return (stat(procbuf, &statbuf) >= 0);
310 }
311
312 int main(void) {
313         char part[512],
314              pathbuf[512],
315              *end;
316         unsigned int i;
317
318         cleanup_rbar_dir();
319         create_file(ORDER_WLAN "wlan");
320         create_file(ORDER_ETH "eth");
321         create_file(ORDER_BATTERY "battery");
322         create_file(ORDER_LOAD "load");
323         create_file(ORDER_TIME "time");
324         for (i = 0; i < sizeof(run_watches) / sizeof(char*); i += 2) {
325                 sprintf(pathbuf, "%s%s", ORDER_RUN, run_watches[i]);
326                 create_file(pathbuf);
327         }
328
329         while (1) {
330                 for (i = 0; i < sizeof(run_watches) / sizeof(char*); i += 2) {
331                         bool running = process_runs(run_watches[i+1]);
332 #ifdef USE_COLORS
333                         sprintf(part, "%s %s: %s", (running ? "#00FF00 " WMII_NORMCOLORS : "#FF0000 " WMII_NORMCOLORS), run_watches[i], (running ? "yes" : "no"));
334 #else
335                         sprintf(part, "%s: %s", run_watches[i], (running ? "yes" : "no"));
336 #endif
337                         sprintf(pathbuf, "%s%s", ORDER_RUN, run_watches[i]);
338                         write_to_statusbar(pathbuf, part);
339                 }
340
341                 write_to_statusbar(ORDER_WLAN "wlan", get_wireless_info());
342                 write_to_statusbar(ORDER_ETH "eth", get_eth_info());
343                 write_to_statusbar(ORDER_BATTERY "battery", get_battery_info());
344
345                 /* Get load */
346                 int load_avg = open("/proc/loadavg", O_RDONLY);
347                 if (load_avg == -1)
348                         die("Could not open /proc/loadavg");
349                 read(load_avg, part, sizeof(part));
350                 close(load_avg);
351                 end = skip_character(part, ' ', 3);
352                 *end = '\0';
353                 write_to_statusbar(ORDER_LOAD "load", part);
354
355                 /* Get date & time */
356                 time_t current_time = time(NULL);
357                 struct tm *current_tm = localtime(&current_time);
358                 strftime(part, sizeof(part), time_format, current_tm);
359                 write_to_statusbar(ORDER_TIME "time", part);
360
361                 sleep(1);
362         }
363 }