]> git.sur5r.net Git - i3/i3status/blob - wmiistatus.c
Make everything configurable
[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 #define _IS_WMIISTATUS_C
54 #include "wmiistatus.h"
55 #undef _IS_WMIISTATUS_C
56 #include "config.h"
57
58 /*
59  * This function just concats two strings in place, it should only be used
60  * for concatting order to the name of a file or concatting color codes.
61  * Otherwise, the buffer size would have to be increased.
62  *
63  */
64 static char *concat(const char *str1, const char *str2) {
65         static char concatbuf[32];
66         snprintf(concatbuf, sizeof(concatbuf), "%s%s", str1, str2);
67         return concatbuf;
68 }
69
70 static void cleanup_rbar_dir() {
71         struct dirent *ent;
72         DIR *dir;
73         char pathbuf[strlen(wmii_path)+256+1];
74
75         if ((dir = opendir(wmii_path)) == NULL)
76                 exit(-3);
77
78         while ((ent = readdir(dir)) != NULL) {
79                 if (ent->d_type == DT_REG) {
80                         sprintf(pathbuf, "%s%s", wmii_path, ent->d_name);
81                         unlink(pathbuf);
82                 }
83         }
84
85         closedir(dir);
86 }
87
88 static void create_file(const char *name) {
89         char pathbuf[strlen(wmii_path)+256+1];
90
91         sprintf(pathbuf, "%s%s", wmii_path, name);
92         int fd = creat(pathbuf, S_IRUSR | S_IWUSR);
93         if (fd < 0)
94                 exit(-4);
95         if (use_colors) {
96                 char *tmp = concat("#888888 ", wmii_normcolors);
97                 write(fd, tmp, strlen(tmp));
98         }
99         close(fd);
100 }
101
102 static void write_to_statusbar(const char *name, const char *message) {
103         char pathbuf[strlen(wmii_path)+256+1];
104
105         sprintf(pathbuf, "%s%s", wmii_path, name);
106         int fd = open(pathbuf, O_RDWR);
107         if (fd == -1)
108                 exit(-2);
109         write(fd, message, strlen(message));
110         close(fd);
111 }
112
113 static void write_error_to_statusbar(const char *message) {
114         cleanup_rbar_dir();
115         create_file("error");
116         write_to_statusbar("error", message);
117 }
118
119 /*
120  * Write errormessage to statusbar and exit
121  *
122  */
123 void die(const char *fmt, ...) {
124         char buffer[512];
125         va_list ap;
126         va_start(ap, fmt);
127         vsprintf(buffer, fmt, ap);
128         va_end(ap);
129
130         write_error_to_statusbar(buffer);
131         exit(-1);
132 }
133
134 static char *skip_character(char *input, char character, int amount) {
135         char *walk;
136         int len = strlen(input),
137             blanks = 0;
138
139         for (walk = input; ((walk - input) < len) && (blanks < amount); walk++)
140                 if (*walk == character)
141                         blanks++;
142
143         return (walk == input ? walk : walk-1);
144 }
145
146 /*
147  * Get battery information from /sys. Note that it uses the design capacity to calculate the percentage,
148  * not the full capacity.
149  *
150  */
151 static char *get_battery_info() {
152         char buf[1024];
153         static char part[512];
154         char *walk, *last = buf;
155         int fd = open(battery_path, O_RDONLY);
156         if (fd == -1)
157                 die("Could not open %s", battery_path);
158         int full_design = -1,
159             remaining = -1,
160             present_rate = -1;
161         charging_status_t status = CS_DISCHARGING;
162         memset(part, '\0', sizeof(part));
163         read(fd, buf, sizeof(buf));
164         for (walk = buf; (walk-buf) < 1024; walk++)
165                 if (*walk == '=') {
166                         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
167                                 full_design = atoi(walk+1);
168                         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW"))
169                                 remaining = atoi(walk+1);
170                         else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
171                                 present_rate = atoi(walk+1);
172                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
173                                 status = CS_CHARGING;
174                         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
175                                 status = CS_FULL;
176                 } else if (*walk == '\n')
177                         last = walk+1;
178         close(fd);
179
180         if ((full_design != -1) && (remaining != -1) && (present_rate != -1)) {
181                 float remaining_time, perc;
182                 if (status == CS_CHARGING)
183                         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
184                 else if (status == CS_DISCHARGING)
185                         remaining_time = ((float)remaining / (float)present_rate);
186                 else {
187                         snprintf(part, sizeof(part), "FULL");
188                         return part;
189                 }
190                 perc = ((float)remaining / (float)full_design);
191
192                 int seconds = (int)(remaining_time * 3600.0);
193                 int hours = seconds / 3600;
194                 seconds -= (hours * 3600);
195                 int minutes = seconds / 60;
196                 seconds -= (minutes * 60);
197
198                 sprintf(part, "%s %.02f%% %02d:%02d:%02d", (status == CS_CHARGING? "CHR" : "BAT"),
199                         (perc * 100), hours, minutes, seconds);
200         }
201         return part;
202 }
203
204 /*
205  * Just parses /proc/net/wireless
206  *
207  */
208 static char *get_wireless_info() {
209         char buf[1024];
210         static char part[512];
211         char *interfaces;
212         memset(buf, '\0', sizeof(buf));
213         memset(part, '\0', sizeof(part));
214
215         int fd = open("/proc/net/wireless", O_RDONLY);
216         if (fd == -1)
217                 die("Could not open /proc/net/wireless");
218         read(fd, buf, sizeof(buf));
219         close(fd);
220
221         interfaces = skip_character(buf, '\n', 2) + 1;
222         while (interfaces < buf+strlen(buf)) {
223                 while (isspace((int)*interfaces))
224                         interfaces++;
225                 if (strncmp(interfaces, wlan_interface, strlen(wlan_interface)) == 0) {
226                         /* Skip status field (0000) */
227                         interfaces += strlen(wlan_interface) + 2;
228                         interfaces = skip_character(interfaces, ' ', 1);
229                         while (isspace((int)*interfaces))
230                                 interfaces++;
231                         int quality = atoi(interfaces);
232                         /* For some reason, I get 255 sometimes */
233                         if ((quality == 255) || (quality == 0)) {
234                         if (use_colors)
235                                 snprintf(part, sizeof(part), "%s%s", concat("#FF0000 ", wmii_normcolors), " W: down");
236                         else snprintf(part, sizeof(part), "W: down");
237
238                         } else {
239                                 snprintf(part, sizeof(part), "W: (%02d%%) ", quality);
240                                 char *ip_address = get_ip_address(wlan_interface);
241                                 strcpy(part+strlen(part), ip_address);
242                         }
243
244                         return part;
245                 }
246                 interfaces = skip_character(interfaces, '\n', 1) + 1;
247         }
248
249         return part;
250 }
251
252 static char *get_ip_address(const char *interface) {
253         static char part[512];
254         struct ifreq ifr;
255         memset(part, '\0', sizeof(part));
256
257         int fd = socket(AF_INET, SOCK_DGRAM, 0);
258
259         strcpy(ifr.ifr_name, interface);
260         if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
261                 die("Could not get interface flags (SIOCGIFFLAGS)");
262
263         if (!(ifr.ifr_flags & IFF_UP) ||
264             !(ifr.ifr_flags & IFF_RUNNING)) {
265                 close(fd);
266                 return NULL;
267         }
268
269         strcpy(ifr.ifr_name, interface);
270         ifr.ifr_addr.sa_family = AF_INET;
271         if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) {
272                 struct sockaddr_in addr;
273                 memcpy(&addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
274                 inet_ntop(AF_INET, &addr.sin_addr.s_addr, part, sizeof(struct sockaddr_in));
275                 if (strlen(part) == 0)
276                         sprintf(part, "no IP");
277         }
278
279         close(fd);
280         return part;
281 }
282
283 static char *get_eth_info() {
284         static char part[512];
285         char *ip_address = get_ip_address(eth_interface);
286
287         if (ip_address == NULL)
288                 snprintf(part, sizeof(part), "E: down");
289         else snprintf(part, sizeof(part), "E: %s", ip_address);
290
291         return part;
292 }
293
294 /*
295  * Checks if the PID in path is still valid by checking if /proc/<pid> exists
296  *
297  */
298 static bool process_runs(const char *path) {
299         char pidbuf[512],
300              procbuf[512],
301              *walk;
302         int n;
303         static glob_t globbuf;
304         struct stat statbuf;
305
306         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
307                 die("glob() failed");
308         const char *real_path = (globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
309         int fd = open(real_path, O_RDONLY);
310         globfree(&globbuf);
311         if (fd < 0)
312                 return false;
313         n = read(fd, pidbuf, sizeof(pidbuf));
314         if (n > 0)
315                 pidbuf[n] = '\0';
316         close(fd);
317         for (walk = pidbuf; *walk != '\0'; walk++)
318                 if (!isdigit((int)(*walk))) {
319                         *walk = '\0';
320                         break;
321                 }
322         sprintf(procbuf, "/proc/%s", pidbuf);
323         return (stat(procbuf, &statbuf) >= 0);
324 }
325
326 int main(void) {
327         char part[512],
328              pathbuf[512],
329              *end;
330         unsigned int i;
331
332         load_configuration("/etc/wmiistatus.conf");
333         cleanup_rbar_dir();
334         if (wlan_interface)
335                 create_file(concat(order[ORDER_WLAN],"wlan"));
336         if (eth_interface)
337                 create_file(concat(order[ORDER_ETH],"eth"));
338         if (battery_path)
339                 create_file(concat(order[ORDER_BATTERY],"battery"));
340         create_file(concat(order[ORDER_LOAD],"load"));
341         if (time_format)
342                 create_file(concat(order[ORDER_TIME],"time"));
343         for (i = 0; i < num_run_watches; i += 2) {
344                 sprintf(pathbuf, "%s%s", order[ORDER_RUN], run_watches[i]);
345                 create_file(pathbuf);
346         }
347
348         while (1) {
349                 for (i = 0; i < num_run_watches; i += 2) {
350                         bool running = process_runs(run_watches[i+1]);
351                         if (use_colors)
352                                 sprintf(part, "%s %s: %s", (running ? concat("#00FF00 ", wmii_normcolors) : concat("#FF0000 ", wmii_normcolors)), run_watches[i], (running ? "yes" : "no"));
353                         else sprintf(part, "%s: %s", run_watches[i], (running ? "yes" : "no"));
354                         sprintf(pathbuf, "%s%s", order[ORDER_RUN], run_watches[i]);
355                         write_to_statusbar(pathbuf, part);
356                 }
357
358                 if (wlan_interface)
359                         write_to_statusbar(concat(order[ORDER_WLAN], "wlan"), get_wireless_info());
360                 if (eth_interface)
361                         write_to_statusbar(concat(order[ORDER_ETH], "eth"), get_eth_info());
362                 if (battery_path)
363                         write_to_statusbar(concat(order[ORDER_BATTERY], "battery"), get_battery_info());
364
365                 /* Get load */
366                 int load_avg = open("/proc/loadavg", O_RDONLY);
367                 if (load_avg == -1)
368                         die("Could not open /proc/loadavg");
369                 read(load_avg, part, sizeof(part));
370                 close(load_avg);
371                 end = skip_character(part, ' ', 3);
372                 *end = '\0';
373                 write_to_statusbar(concat(order[ORDER_LOAD], "load"), part);
374
375                 if (time_format) {
376                         /* Get date & time */
377                         time_t current_time = time(NULL);
378                         struct tm *current_tm = localtime(&current_time);
379                         strftime(part, sizeof(part), time_format, current_tm);
380                         write_to_statusbar(concat(order[ORDER_TIME], "time"), part);
381                 }
382
383                 sleep(1);
384         }
385 }