]> git.sur5r.net Git - i3/i3status/blob - src/print_battery_info.c
fix: use SYSCONFDIR in error message
[i3/i3status] / src / print_battery_info.c
1 // vim:ts=4:sw=4:expandtab
2 #include <config.h>
3 #include <ctype.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <time.h>
8 #include <yajl/yajl_gen.h>
9 #include <yajl/yajl_version.h>
10
11 #include "i3status.h"
12
13 #if defined(__linux__)
14 #include <errno.h>
15 #include <glob.h>
16 #include <sys/types.h>
17 #endif
18
19 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
20 #include <dev/acpica/acpiio.h>
21 #include <sys/sysctl.h>
22 #include <sys/types.h>
23 #endif
24
25 #if defined(__DragonFly__)
26 #include <sys/fcntl.h>
27 #endif
28
29 #if defined(__OpenBSD__)
30 #include <machine/apmvar.h>
31 #include <sys/fcntl.h>
32 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #endif
35
36 #if defined(__NetBSD__)
37 #include <fcntl.h>
38 #include <prop/proplib.h>
39 #include <sys/envsys.h>
40 #endif
41
42 typedef enum {
43     CS_UNKNOWN,
44     CS_DISCHARGING,
45     CS_CHARGING,
46     CS_FULL,
47 } charging_status_t;
48
49 /* A description of the state of one or more batteries. */
50 struct battery_info {
51     /* measured properties */
52     int full_design;  /* in uAh */
53     int full_last;    /* in uAh */
54     int remaining;    /* in uAh */
55     int present_rate; /* in uA, always non-negative */
56
57     /* derived properties */
58     int seconds_remaining;
59     float percentage_remaining;
60     charging_status_t status;
61 };
62
63 #if defined(__DragonFly__)
64 #define ACPIDEV "/dev/acpi"
65 static int acpifd;
66
67 static bool acpi_init(void) {
68     if (acpifd == 0) {
69         acpifd = open(ACPIDEV, O_RDWR);
70         if (acpifd == -1)
71             acpifd = open(ACPIDEV, O_RDONLY);
72         if (acpifd == -1)
73             return false;
74     }
75     return true;
76 }
77 #endif
78
79 #if defined(__linux__) || defined(__NetBSD__)
80 /*
81  * Add batt_info data to acc.
82  */
83 static void add_battery_info(struct battery_info *acc, const struct battery_info *batt_info) {
84     if (acc->remaining < 0) {
85         /* initialize accumulator so we can add to it */
86         acc->full_design = 0;
87         acc->full_last = 0;
88         acc->remaining = 0;
89         acc->present_rate = 0;
90     }
91
92     acc->full_design += batt_info->full_design;
93     acc->full_last += batt_info->full_last;
94     acc->remaining += batt_info->remaining;
95
96     /* make present_rate negative for discharging and positive for charging */
97     int present_rate = (acc->status == CS_DISCHARGING ? -1 : 1) * acc->present_rate;
98     present_rate += (batt_info->status == CS_DISCHARGING ? -1 : 1) * batt_info->present_rate;
99
100     /* merge status */
101     switch (acc->status) {
102         case CS_UNKNOWN:
103             acc->status = batt_info->status;
104             break;
105
106         case CS_DISCHARGING:
107             if (present_rate > 0)
108                 acc->status = CS_CHARGING;
109             /* else if batt_info is DISCHARGING: no conflict
110              * else if batt_info is CHARGING: present_rate should indicate that
111              * else if batt_info is FULL: but something else is discharging */
112             break;
113
114         case CS_CHARGING:
115             if (present_rate < 0)
116                 acc->status = CS_DISCHARGING;
117             /* else if batt_info is DISCHARGING: present_rate should indicate that
118              * else if batt_info is CHARGING: no conflict
119              * else if batt_info is FULL: but something else is charging */
120             break;
121
122         case CS_FULL:
123             if (batt_info->status != CS_UNKNOWN)
124                 acc->status = batt_info->status;
125             /* else: retain FULL, since it is more specific than UNKNOWN */
126             break;
127     }
128
129     acc->present_rate = abs(present_rate);
130 }
131 #endif
132
133 static bool slurp_battery_info(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, int number, const char *path, const char *format_down) {
134     char *outwalk = buffer;
135
136 #if defined(__linux__)
137     char buf[1024];
138     const char *walk, *last;
139     bool watt_as_unit = false;
140     int voltage = -1;
141     char batpath[512];
142     sprintf(batpath, path, number);
143     INSTANCE(batpath);
144
145     if (!slurp(batpath, buf, sizeof(buf))) {
146         OUTPUT_FULL_TEXT(format_down);
147         return false;
148     }
149
150     for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
151         if (*walk == '\n') {
152             last = walk + 1;
153             continue;
154         }
155
156         if (*walk != '=')
157             continue;
158
159         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW=")) {
160             watt_as_unit = true;
161             batt_info->remaining = atoi(walk + 1);
162             batt_info->percentage_remaining = -1;
163         } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW=")) {
164             watt_as_unit = false;
165             batt_info->remaining = atoi(walk + 1);
166             batt_info->percentage_remaining = -1;
167         } else if (BEGINS_WITH(last, "POWER_SUPPLY_CAPACITY=") && batt_info->remaining == -1) {
168             batt_info->percentage_remaining = atoi(walk + 1);
169         } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW="))
170             batt_info->present_rate = abs(atoi(walk + 1));
171         else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW="))
172             voltage = abs(atoi(walk + 1));
173         /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
174          * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
175          * unit instead of μAh. We will calculate it as we need it
176          * later. */
177         else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW="))
178             batt_info->present_rate = abs(atoi(walk + 1));
179         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
180             batt_info->status = CS_CHARGING;
181         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
182             batt_info->status = CS_FULL;
183         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging") || BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Not charging"))
184             batt_info->status = CS_DISCHARGING;
185         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
186             batt_info->status = CS_UNKNOWN;
187         else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN=") ||
188                  BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN="))
189             batt_info->full_design = atoi(walk + 1);
190         else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL=") ||
191                  BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL="))
192             batt_info->full_last = atoi(walk + 1);
193     }
194
195     /* the difference between POWER_SUPPLY_ENERGY_NOW and
196      * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
197      * given in mWh, the charge in mAh. So calculate every value given in
198      * ampere to watt */
199     if (!watt_as_unit && voltage >= 0) {
200         if (batt_info->present_rate > 0) {
201             batt_info->present_rate = (((float)voltage / 1000.0) * ((float)batt_info->present_rate / 1000.0));
202         }
203         if (batt_info->remaining > 0) {
204             batt_info->remaining = (((float)voltage / 1000.0) * ((float)batt_info->remaining / 1000.0));
205         }
206         if (batt_info->full_design > 0) {
207             batt_info->full_design = (((float)voltage / 1000.0) * ((float)batt_info->full_design / 1000.0));
208         }
209         if (batt_info->full_last > 0) {
210             batt_info->full_last = (((float)voltage / 1000.0) * ((float)batt_info->full_last / 1000.0));
211         }
212     }
213 #elif defined(__DragonFly__)
214     union acpi_battery_ioctl_arg battio;
215     if (acpi_init()) {
216         battio.unit = number;
217         ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio);
218         batt_info->full_design = battio.bif.dcap;
219         batt_info->full_last = battio.bif.lfcap;
220         battio.unit = number;
221         ioctl(acpifd, ACPIIO_BATT_GET_BATTINFO, &battio);
222         batt_info->percentage_remaining = battio.battinfo.cap;
223         batt_info->present_rate = battio.battinfo.rate;
224         batt_info->seconds_remaining = battio.battinfo.min * 60;
225         switch (battio.battinfo.state) {
226             case 0:
227                 batt_info->status = CS_FULL;
228                 break;
229             case ACPI_BATT_STAT_CHARGING:
230                 batt_info->status = CS_CHARGING;
231                 break;
232             case ACPI_BATT_STAT_DISCHARG:
233                 batt_info->status = CS_DISCHARGING;
234                 break;
235             default:
236                 batt_info->status = CS_UNKNOWN;
237         }
238         OUTPUT_FULL_TEXT(format_down);
239     }
240 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
241     int state;
242     int sysctl_rslt;
243     size_t sysctl_size = sizeof(sysctl_rslt);
244
245     if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
246         OUTPUT_FULL_TEXT(format_down);
247         return false;
248     }
249
250     batt_info->percentage_remaining = sysctl_rslt;
251     if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
252         OUTPUT_FULL_TEXT(format_down);
253         return false;
254     }
255
256     batt_info->seconds_remaining = sysctl_rslt * 60;
257     if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
258         OUTPUT_FULL_TEXT(format_down);
259         return false;
260     }
261
262     state = sysctl_rslt;
263     if (state == 0 && batt_info->percentage_remaining == 100)
264         batt_info->status = CS_FULL;
265     else if ((state & ACPI_BATT_STAT_CHARGING) && batt_info->percentage_remaining < 100)
266         batt_info->status = CS_CHARGING;
267     else
268         batt_info->status = CS_DISCHARGING;
269 #elif defined(__OpenBSD__)
270     /*
271          * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
272          * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
273          * probing acpi(4) devices.
274          */
275     struct apm_power_info apm_info;
276     int apm_fd;
277
278     apm_fd = open("/dev/apm", O_RDONLY);
279     if (apm_fd < 0) {
280         OUTPUT_FULL_TEXT("can't open /dev/apm");
281         return false;
282     }
283     if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
284         OUTPUT_FULL_TEXT("can't read power info");
285
286     close(apm_fd);
287
288     /* Don't bother to go further if there's no battery present. */
289     if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
290         (apm_info.battery_state == APM_BATT_UNKNOWN)) {
291         OUTPUT_FULL_TEXT(format_down);
292         return false;
293     }
294
295     switch (apm_info.ac_state) {
296         case APM_AC_OFF:
297             batt_info->status = CS_DISCHARGING;
298             break;
299         case APM_AC_ON:
300             batt_info->status = CS_CHARGING;
301             break;
302         default:
303             /* If we don't know what's going on, just assume we're discharging. */
304             batt_info->status = CS_DISCHARGING;
305             break;
306     }
307
308     batt_info->percentage_remaining = apm_info.battery_life;
309
310     /* Can't give a meaningful value for remaining minutes if we're charging. */
311     if (batt_info->status != CS_CHARGING) {
312         batt_info->seconds_remaining = apm_info.minutes_left * 60;
313     }
314 #elif defined(__NetBSD__)
315     /*
316      * Using envsys(4) via sysmon(4).
317      */
318     int fd, rval;
319     bool is_found = false;
320     char sensor_desc[16];
321
322     prop_dictionary_t dict;
323     prop_array_t array;
324     prop_object_iterator_t iter;
325     prop_object_iterator_t iter2;
326     prop_object_t obj, obj2, obj3, obj4, obj5;
327
328     if (number >= 0)
329         (void)snprintf(sensor_desc, sizeof(sensor_desc), "acpibat%d", number);
330
331     fd = open("/dev/sysmon", O_RDONLY);
332     if (fd < 0) {
333         OUTPUT_FULL_TEXT("can't open /dev/sysmon");
334         return false;
335     }
336
337     rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
338     if (rval == -1) {
339         close(fd);
340         return false;
341     }
342
343     if (prop_dictionary_count(dict) == 0) {
344         prop_object_release(dict);
345         close(fd);
346         return false;
347     }
348
349     iter = prop_dictionary_iterator(dict);
350     if (iter == NULL) {
351         prop_object_release(dict);
352         close(fd);
353     }
354
355     /* iterate over the dictionary returned by the kernel */
356     while ((obj = prop_object_iterator_next(iter)) != NULL) {
357         /* skip this dict if it's not what we're looking for */
358         if (number < 0) {
359             /* we want all batteries */
360             if (!BEGINS_WITH(prop_dictionary_keysym_cstring_nocopy(obj),
361                              "acpibat"))
362                 continue;
363         } else {
364             /* we want a specific battery */
365             if (strcmp(sensor_desc,
366                        prop_dictionary_keysym_cstring_nocopy(obj)) != 0)
367                 continue;
368         }
369
370         is_found = true;
371
372         array = prop_dictionary_get_keysym(dict, obj);
373         if (prop_object_type(array) != PROP_TYPE_ARRAY) {
374             prop_object_iterator_release(iter);
375             prop_object_release(dict);
376             close(fd);
377             return false;
378         }
379
380         iter2 = prop_array_iterator(array);
381         if (!iter2) {
382             prop_object_iterator_release(iter);
383             prop_object_release(dict);
384             close(fd);
385             return false;
386         }
387
388         struct battery_info batt_buf = {
389             .full_design = 0,
390             .full_last = 0,
391             .remaining = 0,
392             .present_rate = 0,
393             .status = CS_UNKNOWN,
394         };
395         int voltage = -1;
396         bool watt_as_unit = false;
397
398         /* iterate over array of dicts specific to target battery */
399         while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
400             obj3 = prop_dictionary_get(obj2, "description");
401
402             if (obj3 == NULL)
403                 continue;
404
405             if (strcmp("charging", prop_string_cstring_nocopy(obj3)) == 0) {
406                 obj3 = prop_dictionary_get(obj2, "cur-value");
407
408                 if (prop_number_integer_value(obj3))
409                     batt_buf.status = CS_CHARGING;
410                 else
411                     batt_buf.status = CS_DISCHARGING;
412             } else if (strcmp("charge", prop_string_cstring_nocopy(obj3)) == 0) {
413                 obj3 = prop_dictionary_get(obj2, "cur-value");
414                 obj4 = prop_dictionary_get(obj2, "max-value");
415                 obj5 = prop_dictionary_get(obj2, "type");
416
417                 batt_buf.remaining = prop_number_integer_value(obj3);
418                 batt_buf.full_design = prop_number_integer_value(obj4);
419
420                 if (strcmp("Ampere hour", prop_string_cstring_nocopy(obj5)) == 0)
421                     watt_as_unit = false;
422                 else
423                     watt_as_unit = true;
424             } else if (strcmp("discharge rate", prop_string_cstring_nocopy(obj3)) == 0) {
425                 obj3 = prop_dictionary_get(obj2, "cur-value");
426                 batt_buf.present_rate = prop_number_integer_value(obj3);
427             } else if (strcmp("charge rate", prop_string_cstring_nocopy(obj3)) == 0) {
428                 obj3 = prop_dictionary_get(obj2, "cur-value");
429                 batt_info->present_rate = prop_number_integer_value(obj3);
430             } else if (strcmp("last full cap", prop_string_cstring_nocopy(obj3)) == 0) {
431                 obj3 = prop_dictionary_get(obj2, "cur-value");
432                 batt_buf.full_last = prop_number_integer_value(obj3);
433             } else if (strcmp("voltage", prop_string_cstring_nocopy(obj3)) == 0) {
434                 obj3 = prop_dictionary_get(obj2, "cur-value");
435                 voltage = prop_number_integer_value(obj3);
436             }
437         }
438         prop_object_iterator_release(iter2);
439
440         if (!watt_as_unit && voltage != -1) {
441             batt_buf.present_rate = (((float)voltage / 1000.0) * ((float)batt_buf.present_rate / 1000.0));
442             batt_buf.remaining = (((float)voltage / 1000.0) * ((float)batt_buf.remaining / 1000.0));
443             batt_buf.full_design = (((float)voltage / 1000.0) * ((float)batt_buf.full_design / 1000.0));
444             batt_buf.full_last = (((float)voltage / 1000.0) * ((float)batt_buf.full_last / 1000.0));
445         }
446
447         if (batt_buf.remaining == batt_buf.full_design)
448             batt_buf.status = CS_FULL;
449
450         add_battery_info(batt_info, &batt_buf);
451     }
452
453     prop_object_iterator_release(iter);
454     prop_object_release(dict);
455     close(fd);
456
457     if (!is_found) {
458         OUTPUT_FULL_TEXT(format_down);
459         return false;
460     }
461
462     batt_info->present_rate = abs(batt_info->present_rate);
463 #endif
464
465     return true;
466 }
467
468 /*
469  * Populate batt_info with aggregate information about all batteries.
470  * Returns false on error, and an error message will have been written.
471  */
472 static bool slurp_all_batteries(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, const char *path, const char *format_down) {
473 #if defined(__linux__)
474     char *outwalk = buffer;
475     bool is_found = false;
476
477     char *placeholder;
478     char *globpath = sstrdup(path);
479     if ((placeholder = strstr(path, "%d")) != NULL) {
480         char *globplaceholder = globpath + (placeholder - path);
481         *globplaceholder = '*';
482         strcpy(globplaceholder + 1, placeholder + 2);
483     }
484
485     if (!strcmp(globpath, path)) {
486         OUTPUT_FULL_TEXT("no '%d' in battery path");
487         return false;
488     }
489
490     glob_t globbuf;
491     if (glob(globpath, 0, NULL, &globbuf) == 0) {
492         for (size_t i = 0; i < globbuf.gl_pathc; i++) {
493             /* Probe to see if there is such a battery. */
494             struct battery_info batt_buf = {
495                 .full_design = 0,
496                 .full_last = 0,
497                 .remaining = 0,
498                 .present_rate = 0,
499                 .status = CS_UNKNOWN,
500             };
501             if (!slurp_battery_info(&batt_buf, json_gen, buffer, i, globbuf.gl_pathv[i], format_down)) {
502                 globfree(&globbuf);
503                 free(globpath);
504                 return false;
505             }
506
507             is_found = true;
508             add_battery_info(batt_info, &batt_buf);
509         }
510         globfree(&globbuf);
511     }
512     free(globpath);
513
514     if (!is_found) {
515         OUTPUT_FULL_TEXT(format_down);
516         return false;
517     }
518
519     batt_info->present_rate = abs(batt_info->present_rate);
520 #else
521     /* FreeBSD and OpenBSD only report aggregates. NetBSD always
522      * iterates through all batteries, so it's more efficient to
523      * aggregate in slurp_battery_info. */
524     return slurp_battery_info(batt_info, json_gen, buffer, -1, path, format_down);
525 #endif
526
527     return true;
528 }
529
530 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_unk, const char *status_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) {
531     const char *walk;
532     char *outwalk = buffer;
533     struct battery_info batt_info = {
534         .full_design = -1,
535         .full_last = -1,
536         .remaining = -1,
537         .present_rate = -1,
538         .seconds_remaining = -1,
539         .percentage_remaining = -1,
540         .status = CS_UNKNOWN,
541     };
542     bool colorful_output = false;
543
544 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
545     /* These OSes report battery stats in whole percent. */
546     integer_battery_capacity = true;
547 #endif
548 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
549     /* These OSes report battery time in minutes. */
550     hide_seconds = true;
551 #endif
552
553     if (number < 0) {
554         if (!slurp_all_batteries(&batt_info, json_gen, buffer, path, format_down))
555             return;
556     } else {
557         if (!slurp_battery_info(&batt_info, json_gen, buffer, number, path, format_down))
558             return;
559     }
560
561     // *Choose* a measure of the 'full' battery. It is whichever is better of
562     // the battery's (hardware-given) design capacity (batt_info.full_design)
563     // and the battery's last known good charge (batt_info.full_last).
564     // We prefer the design capacity, but use the last capacity if we don't have it,
565     // or if we are asked to (last_full_capacity == true); but similarly we use
566     // the design capacity if we don't have the last capacity.
567     // If we don't have either then both full_design and full_last <= 0,
568     // which implies full <= 0, which bails out on the following line.
569     int full = batt_info.full_design;
570     if (full <= 0 || (last_full_capacity && batt_info.full_last > 0)) {
571         full = batt_info.full_last;
572     }
573     if (full <= 0 && batt_info.remaining < 0 && batt_info.percentage_remaining < 0) {
574         /* We have no physical measurements and no estimates. Nothing
575          * much we can report, then. */
576         OUTPUT_FULL_TEXT(format_down);
577         return;
578     }
579
580     if (batt_info.percentage_remaining < 0) {
581         batt_info.percentage_remaining = (((float)batt_info.remaining / (float)full) * 100);
582         /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
583          * charged, even though that’s plainly wrong. For people who chose to see
584          * the percentage calculated based on the last full capacity, we clamp the
585          * value to 100%, as that makes more sense.
586          * See http://bugs.debian.org/785398 */
587         if (last_full_capacity && batt_info.percentage_remaining > 100) {
588             batt_info.percentage_remaining = 100;
589         }
590     }
591
592     if (batt_info.seconds_remaining < 0 && batt_info.present_rate > 0 && batt_info.status != CS_FULL) {
593         if (batt_info.status == CS_CHARGING)
594             batt_info.seconds_remaining = 3600.0 * (full - batt_info.remaining) / batt_info.present_rate;
595         else if (batt_info.status == CS_DISCHARGING)
596             batt_info.seconds_remaining = 3600.0 * batt_info.remaining / batt_info.present_rate;
597         else
598             batt_info.seconds_remaining = 0;
599     }
600
601     if (batt_info.status == CS_DISCHARGING && low_threshold > 0) {
602         if (batt_info.percentage_remaining >= 0 && strcasecmp(threshold_type, "percentage") == 0 && batt_info.percentage_remaining < low_threshold) {
603             START_COLOR("color_bad");
604             colorful_output = true;
605         } else if (batt_info.seconds_remaining >= 0 && strcasecmp(threshold_type, "time") == 0 && batt_info.seconds_remaining < 60 * low_threshold) {
606             START_COLOR("color_bad");
607             colorful_output = true;
608         }
609     }
610
611 #define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT()                   \
612     do {                                                       \
613         if (outwalk == prevoutwalk) {                          \
614             if (outwalk > buffer && isspace((int)outwalk[-1])) \
615                 outwalk--;                                     \
616             else if (isspace((int)*(walk + 1)))                \
617                 walk++;                                        \
618         }                                                      \
619     } while (0)
620
621     for (walk = format; *walk != '\0'; walk++) {
622         char *prevoutwalk = outwalk;
623
624         if (*walk != '%') {
625             *(outwalk++) = *walk;
626
627         } else if (BEGINS_WITH(walk + 1, "status")) {
628             const char *statusstr;
629             switch (batt_info.status) {
630                 case CS_CHARGING:
631                     statusstr = status_chr;
632                     break;
633                 case CS_DISCHARGING:
634                     statusstr = status_bat;
635                     break;
636                 case CS_FULL:
637                     statusstr = status_full;
638                     break;
639                 default:
640                     statusstr = status_unk;
641             }
642
643             outwalk += sprintf(outwalk, "%s", statusstr);
644             walk += strlen("status");
645
646         } else if (BEGINS_WITH(walk + 1, "percentage")) {
647             if (integer_battery_capacity) {
648                 outwalk += sprintf(outwalk, "%.00f%s", batt_info.percentage_remaining, pct_mark);
649             } else {
650                 outwalk += sprintf(outwalk, "%.02f%s", batt_info.percentage_remaining, pct_mark);
651             }
652             walk += strlen("percentage");
653
654         } else if (BEGINS_WITH(walk + 1, "remaining")) {
655             if (batt_info.seconds_remaining >= 0) {
656                 int seconds, hours, minutes;
657
658                 hours = batt_info.seconds_remaining / 3600;
659                 seconds = batt_info.seconds_remaining - (hours * 3600);
660                 minutes = seconds / 60;
661                 seconds -= (minutes * 60);
662
663                 if (hide_seconds)
664                     outwalk += sprintf(outwalk, "%02d:%02d",
665                                        max(hours, 0), max(minutes, 0));
666                 else
667                     outwalk += sprintf(outwalk, "%02d:%02d:%02d",
668                                        max(hours, 0), max(minutes, 0), max(seconds, 0));
669             }
670             walk += strlen("remaining");
671             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
672
673         } else if (BEGINS_WITH(walk + 1, "emptytime")) {
674             if (batt_info.seconds_remaining >= 0) {
675                 time_t empty_time = time(NULL) + batt_info.seconds_remaining;
676                 set_timezone(NULL); /* Use local time. */
677                 struct tm *empty_tm = localtime(&empty_time);
678
679                 if (hide_seconds)
680                     outwalk += sprintf(outwalk, "%02d:%02d",
681                                        max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
682                 else
683                     outwalk += sprintf(outwalk, "%02d:%02d:%02d",
684                                        max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
685             }
686             walk += strlen("emptytime");
687             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
688
689         } else if (BEGINS_WITH(walk + 1, "consumption")) {
690             if (batt_info.present_rate >= 0)
691                 outwalk += sprintf(outwalk, "%1.2fW", batt_info.present_rate / 1e6);
692
693             walk += strlen("consumption");
694             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
695
696         } else {
697             *(outwalk++) = '%';
698         }
699     }
700
701     if (colorful_output)
702         END_COLOR;
703
704     OUTPUT_FULL_TEXT(buffer);
705 }