]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
Write information in separate files, define order
[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         close(fd);
82 }
83
84 static void write_to_statusbar(const char *name, const char *message) {
85         char pathbuf[strlen(wmii_path)+256+1];
86
87         sprintf(pathbuf, "%s%s", wmii_path, name);
88         int fd = open(pathbuf, O_RDWR);
89         if (fd == -1)
90                 exit(-2);
91         write(fd, message, strlen(message));
92         close(fd);
93 }
94
95 static void write_error_to_statusbar(const char *message) {
96         cleanup_rbar_dir();
97         write_to_statusbar("error", message);
98 }
99
100 /*
101  * Write errormessage to statusbar and exit
102  *
103  */
104 static void die(const char *fmt, ...) {
105         char buffer[512];
106         va_list ap;
107         va_start(ap, fmt);
108         vsprintf(buffer, fmt, ap);
109         va_end(ap);
110
111         write_error_to_statusbar(buffer);
112         exit(-1);
113 }
114
115 static char *skip_character(char *input, char character, int amount) {
116         char *walk;
117         int len = strlen(input),
118             blanks = 0;
119
120         for (walk = input; ((walk - input) < len) && (blanks < amount); walk++)
121                 if (*walk == character)
122                         blanks++;
123
124         return (walk == input ? walk : walk-1);
125 }
126
127 static void push_part(const char *input, const int n) {
128         if (first_push)
129                 first_push = false;
130         else
131                 strncpy(output+strlen(output), " | ", strlen(" | "));
132         strncpy(output+strlen(output), input, n);
133 }
134
135 /*
136  * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
137  * not the full capacity.
138  *
139  */
140 static char *get_battery_info() {
141         char buf[1024];
142         static char part[512];
143         char *walk, *last = buf;
144         int fd = open(battery, O_RDONLY);
145         if (fd == -1)
146                 die("Could not open %s", battery);
147         int full_design = -1,
148             remaining = -1,
149             present_rate = -1;
150         charging_status_t status = CS_DISCHARGING;
151         memset(part, '\0', sizeof(part));
152         read(fd, buf, sizeof(buf));
153         for (walk = buf; (walk-buf) < 1024; walk++)
154                 if (*walk == '=') {
155                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
156                                 full_design = atoi(walk+1);
157                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW"))
158                                 remaining = atoi(walk+1);
159                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
160                                 present_rate = atoi(walk+1);
161                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
162                                 status = CS_CHARGING;
163                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
164                                 status = CS_FULL;
165                 } else if (*walk == '\n')
166                         last = walk+1;
167         close(fd);
168
169         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
170                 float remaining_time, perc;
171                 if (status == CS_CHARGING)
172                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
173                 else if (status == CS_DISCHARGING)
174                         remaining_time = ((float)remaining / (float)present_rate);
175                 else {
176                         snprintf(part, sizeof(part), "FULL");
177                         return part;
178                 }
179                 perc = ((float)remaining / (float)full_design);
180
181                 int seconds = (int)(remaining_time * 3600.0);
182                 int hours = seconds / 3600;
183                 seconds -= (hours * 3600);
184                 int minutes = seconds / 60;
185                 seconds -= (minutes * 60);
186
187                 sprintf(part, "%s %.02f%% %02d:%02d:%02d", (status == CS_CHARGING? "CHR" : "BAT"),
188                         (perc * 100), hours, minutes, seconds);
189         }
190         return part;
191 }
192
193 /*
194  * Just parses /proc/net/wireless
195  *
196  */
197 static char *get_wireless_info() {
198         char buf[1024];
199         static char part[512];
200         char *interfaces;
201         memset(buf, '\0', sizeof(buf));
202         memset(part, '\0', sizeof(part));
203
204         int fd = open("/proc/net/wireless", O_RDONLY);
205         if (fd == -1)
206                 die("Could not open /proc/net/wireless");
207         read(fd, buf, sizeof(buf));
208         close(fd);
209
210         interfaces = skip_character(buf, '\n', 2) + 1;
211         while (interfaces < buf+strlen(buf)) {
212                 while (isspace((int)*interfaces))
213                         interfaces++;
214                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
215                         /* Skip status field (0000) */
216                         interfaces += strlen(wlan_interface) + 2;
217                         interfaces = skip_character(interfaces, ' ', 1);
218                         while (isspace((int)*interfaces))
219                                 interfaces++;
220                         int quality = atoi(interfaces);
221                         /* For some reason, I get 255 sometimes */
222                         if ((quality == 255) || (quality == 0))
223                                 snprintf(part, sizeof(part), "W: down");
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              *end;
315         unsigned int i;
316
317         cleanup_rbar_dir();
318         create_file(ORDER_WLAN "wlan");
319         create_file(ORDER_ETH "eth");
320         create_file(ORDER_BATTERY "battery");
321         create_file(ORDER_LOAD "load");
322         create_file(ORDER_TIME "time");
323
324         while (1) {
325                 memset(output, '\0', sizeof(output));
326                 first_push = true;
327
328                 for (i = 0; i < sizeof(run_watches) / sizeof(char*); i += 2) {
329                         sprintf(part, "%s: %s", run_watches[i], (process_runs(run_watches[i+1]) ? "yes" : "no"));
330                         push_part(part, strlen(part));
331                 }
332
333                 char *wireless_info = get_wireless_info();
334                 write_to_statusbar(ORDER_WLAN "wlan", wireless_info);
335
336                 char *eth_info = get_eth_info();
337                 write_to_statusbar(ORDER_ETH "eth", eth_info);
338
339                 char *battery_info = get_battery_info();
340                 write_to_statusbar(ORDER_BATTERY "battery", battery_info);
341
342                 /* Get load */
343                 int load_avg = open("/proc/loadavg", O_RDONLY);
344                 if (load_avg == -1)
345                         die("Could not open /proc/loadavg");
346                 read(load_avg, part, sizeof(part));
347                 close(load_avg);
348                 end = skip_character(part, ' ', 3);
349                 *end = '\0';
350                 write_to_statusbar(ORDER_LOAD "load", part);
351
352                 /* Get date & time */
353                 time_t current_time = time(NULL);
354                 struct tm *current_tm = localtime(&current_time);
355                 strftime(part, sizeof(part), time_format, current_tm);
356                 write_to_statusbar(ORDER_TIME "time", part);
357
358                 sleep(1);
359         }
360 }