1 /* wmbattery - display laptop battery info, dockable in WindowMaker
2 * Copyright (C) 1998-2014 Joey Hess <joey@kitenet.net>
3 * Copyright (C) 2014 Window Maker Developers Team
4 * <wmaker-dev@lists.windowmaker.org>
6 * Portions of code derived from:
7 * wmapm - Copyright (C) 1998-1999 Chris D. Faulhaber <jedgar@fxp.org>
8 * wmmon - Copyright (C) 1998 Martijn Pieterse <pieterse@xs4all.nl>
9 * Copyright (C) 1998 Antoine Nulle <warp@xs4all.nl>
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of version 2 of the GNU General Public License
13 * as published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>. */
28 #include <X11/extensions/shape.h>
34 #include <sys/types.h>
36 #include "wmbattery.h"
46 #include "simplehal.h"
52 Pixmap images
[NUM_IMAGES
];
53 Window root
, iconwin
, win
;
61 #define APM_STATUS_FILE "/dev/apm"
63 #define APM_STATUS_FILE "/proc/apm"
66 char *apm_status_file
= APM_STATUS_FILE
;
68 char *crit_audio_fn
= NULL
;
71 char *crit_command
= NULL
;
75 int use_simplehal
= 0;
83 int always_estimate_remaining
= 0;
84 int granularity_estimate_remaining
= 1;
85 int initial_state
= WithdrawnState
;
87 signed int low_pct
= -1;
88 signed int critical_pct
= -1;
90 void error(const char *fmt
, ...)
94 va_start(arglist
, fmt
);
95 fprintf(stderr
, "Error: ");
96 vfprintf(stderr
, fmt
, arglist
);
97 fprintf(stderr
, "\n");
103 #if defined (HAVE_MACHINE_APM_BIOS_H) || defined (HAVE_I386_APMVAR_H) /* BSD */
104 int apm_read(apm_info
*i
)
107 #ifdef HAVE_MACHINE_APM_BIOS_H /* FreeBSD */
108 unsigned long request
= APMIO_GETINFO
;
109 struct apm_info info
;
110 #else /* NetBSD or OpenBSD */
111 unsigned long request
= APM_IOC_GETPOWER
;
112 struct apm_power_info info
;
115 if ((fd
= open(apm_status_file
, O_RDONLY
)) == -1) {
118 if (ioctl(fd
, request
, &info
) == -1) {
123 #ifdef HAVE_MACHINE_APM_BIOS_H /* FreeBSD */
124 i
->ac_line_status
= info
.ai_acline
;
125 i
->battery_status
= info
.ai_batt_stat
;
126 i
->battery_flags
= (info
.ai_batt_stat
== 3) ? 8: 0;
127 i
->battery_percentage
= info
.ai_batt_life
;
128 i
->battery_time
= info
.ai_batt_time
;
129 i
->using_minutes
= 0;
130 #else /* NetBSD or OpenBSD */
131 i
->ac_line_status
= info
.ac_state
;
132 i
->battery_status
= info
.battery_state
;
133 i
->battery_flags
= (info
.battery_state
== 3) ? 8: 0;
134 i
->battery_percentage
= info
.battery_life
;
135 i
->battery_time
= info
.minutes_left
;
136 i
->using_minutes
= 1;
146 if (access(apm_status_file
, R_OK
))
152 int apm_change(apm_info
*cur
)
154 static int ac_line_status
= 0, battery_status
= 0, battery_flags
= 0,
155 battery_percentage
= 0, battery_time
= 0, using_minutes
= 0;
157 int i
= cur
->ac_line_status
== ac_line_status
&&
158 cur
->battery_status
== battery_status
&&
159 cur
->battery_flags
== battery_flags
&&
160 cur
->battery_percentage
== battery_percentage
&&
161 cur
->battery_time
== battery_time
&&
162 cur
->using_minutes
== using_minutes
;
164 ac_line_status
= cur
->ac_line_status
;
165 battery_status
= cur
->battery_status
;
166 battery_flags
= cur
->battery_flags
;
167 battery_percentage
= cur
->battery_percentage
;
168 battery_time
= cur
->battery_time
;
169 using_minutes
= cur
->using_minutes
;
174 /* Calculate battery estimate */
175 void estimate_timeleft(apm_info
*cur_info
)
177 /* Time of the last estimate */
178 static time_t estimate_time
;
179 /* Estimated time left */
180 static time_t estimate
;
181 /* Time when we last noticed a battery level change */
182 static time_t battery_change_time
;
183 /* The previous estimation we had before the battery level changed */
184 static time_t prev_estimate
;
185 /* Percentage at the last estimate */
186 static short percent
;
187 /* Where we charging or discharging the last time we were called? */
188 static short was_charging
= 1;
189 /* Have we made a guess lately? */
190 static short guessed_lately
;
194 short is_charging
= cur_info
->battery_flags
& BATTERY_FLAGS_CHARGING
;
197 if (time(&t
) == ((time_t)-1) && errno
!= 0)
201 /* AC is on and battery is not charging anymore or ... */
202 (cur_info
->ac_line_status
== AC_LINE_STATUS_ON
) && !is_charging
205 /* ... the charging state has changed */
206 is_charging
^ was_charging
209 battery_change_time
= t
;
217 /* No change: decrease estimate */
218 if ((percent
- cur_info
->battery_percentage
)
219 / granularity_estimate_remaining
== 0) {
220 estimate
-= t
- estimate_time
;
222 if (guessed_lately
&& estimate
< 0)
227 /* The battery level changed: calculate estimate based
228 * on change speed and previous estimate */
231 interval
= estimate_time
- battery_change_time
;
232 prev_estimate
= estimate
;
233 battery_change_time
= estimate_time
;
234 estimate
= (is_charging
235 ? (cur_info
->battery_percentage
- 100)
236 : cur_info
->battery_percentage
)
237 * interval
/ (percent
- cur_info
->battery_percentage
);
238 if (prev_estimate
> 0)
239 estimate
= (estimate
* 2 + prev_estimate
) / 3;
242 percent
= cur_info
->battery_percentage
;
243 was_charging
= is_charging
;
244 cur_info
->battery_time
= estimate
;
247 cur_info
->using_minutes
= 0;
250 /* Load up the images this program uses. */
251 void load_images(void)
254 char fn
[128]; /* enough? */
256 for (x
= 0; x
< NUM_IMAGES
; x
++) {
257 sprintf(fn
, "%s/%s.xpm", ICONDIR
, image_info
[x
].filename
);
258 if (XpmReadFileToPixmap(display
, root
, fn
, &images
[x
], NULL
, NULL
)) {
259 /* Check in current direcotry for fallback. */
260 sprintf(fn
, "%s.xpm", image_info
[x
].filename
);
261 if (XpmReadFileToPixmap(display
, root
, fn
, &images
[x
], NULL
, NULL
))
262 error("Failed to load %s\n", fn
);
267 void load_audio(void)
273 if (crit_audio_fn
== NULL
)
275 fd
= open(crit_audio_fn
, 0);
277 error("unable to open audio file");
278 if (fstat(fd
, &s
) == 0) {
279 crit_audio_size
= s
.st_size
;
280 crit_audio
= malloc(crit_audio_size
);
281 /* XXX: make this more robust? (loop?) */
282 if (read(fd
, crit_audio
, crit_audio_size
) != crit_audio_size
) {
285 error("unable to read audio file");
291 /* string replacement function by Laird Shaw, in public domain
292 * http://creativeandcritical.net/str-replace-c */
293 char *replace_str(const char *str
, const char *old
, const char *new)
297 size_t oldlen
= strlen(old
);
298 size_t count
, retlen
, newlen
= strlen(new);
300 if (oldlen
!= newlen
) {
301 for (count
= 0, p
= str
; (q
= strstr(p
, old
)) != NULL
; p
= q
+ oldlen
)
303 /* this is undefined if p - str > PTRDIFF_MAX */
304 retlen
= p
- str
+ strlen(p
) + count
* (newlen
- oldlen
);
306 retlen
= strlen(str
);
308 ret
= malloc(retlen
+ 1);
312 for (r
= ret
, p
= str
; (q
= strstr(p
, old
)) != NULL
; p
= q
+ oldlen
) {
313 /* this is undefined if q - p > PTRDIFF_MAX */
317 memcpy(r
, new, newlen
);
325 void cmd_crit(const char *cmd
, int percentage
, int time
)
327 char prc_str
[255] = "";
328 char min_str
[255] = "";
329 char sec_str
[255] = "";
332 char *command
= NULL
;
337 if (percentage
> 100 || percentage
< 0)
339 if (time
> 65535 || time
< 0)
342 sprintf(prc_str
, "%i", percentage
);
343 sprintf(min_str
, "%i", time
/ 60);
344 sprintf(sec_str
, "%i", time
% 60);
346 tmp_a
= replace_str(cmd
, STR_SUB_PERCENT
, prc_str
);
349 tmp_b
= replace_str(tmp_a
, STR_SUB_MINUTES
, min_str
);
352 command
= replace_str(tmp_b
, STR_SUB_SECONDS
, sec_str
);
356 ret
= system(command
);
358 error("unable to run command: %s", command
);
365 /* Returns the display to run on (or NULL for default). */
366 char *parse_commandline(int argc
, char *argv
[])
373 c
= getopt(argc
, argv
, "hd:g:if:b:w:c:l:es:a:x:v");
376 printf("Usage: wmbattery [options]\n");
377 printf("\t-d <display>\tselects target display\n");
378 printf("\t-h\t\tdisplay this help\n");
379 printf("\t-g +x+y\t\tposition of the window\n");
380 printf("\t-i start\n");
381 printf("\t-b num\t\tnumber of battery to display\n");
382 printf("\t-w secs\t\tseconds between updates\n");
383 printf("\t-l percent\tlow percentage\n");
384 printf("\t-c percent\tcritical percentage\n");
385 printf("\t-e\t\tuse own time estimates\n");
386 printf("\t-s granularity\tignore fluctuations less than granularity%% (implies -e)\n");
387 printf("\t-a file\t\twhen critical send file to /dev/audio\n");
388 printf("\t-x command\twhen critical execute this command\n");
389 printf("\t-v\t\tdisplay version number\n");
393 ret
= strdup(optarg
);
396 s
= strtok(optarg
, "+");
399 s
= strtok(NULL
, "+");
407 initial_state
= IconicState
;
410 battnum
= atoi(optarg
);
413 delay
= atoi(optarg
);
416 low_pct
= atoi(optarg
);
419 critical_pct
= atoi(optarg
);
422 always_estimate_remaining
= 1;
425 always_estimate_remaining
= 1;
426 granularity_estimate_remaining
= atoi(optarg
);
429 crit_audio_fn
= strdup(optarg
);
432 crit_command
= strdup(optarg
);
435 printf("wmbattery "PACKAGE_VERSION
"\n");
444 /* Sets up the window and icon and all the nasty X stuff. */
445 void make_window(char *display_name
, int argc
, char *argv
[])
447 XClassHint classhint
;
448 char *wname
= argv
[0];
451 int dummy
= 0, borderwidth
= 1;
452 XSizeHints sizehints
;
454 Pixel back_pix
, fore_pix
;
457 display
= XOpenDisplay(display_name
);
459 error("can't open display %s", XDisplayName(display_name
));
461 screen
= DefaultScreen(display
);
462 root
= RootWindow(display
, screen
);
465 sizehints
.flags
= USSize
| USPosition
;
468 XWMGeometry(display
, screen
, "", NULL
, borderwidth
,
469 &sizehints
, &sizehints
.x
, &sizehints
.y
,
470 &sizehints
.width
, &sizehints
.height
, &dummy
);
472 sizehints
.width
= 64;
473 sizehints
.height
= 64;
474 sizehints
.x
= pos
[0];
475 sizehints
.y
= pos
[1];
476 back_pix
= WhitePixel(display
, screen
);
477 fore_pix
= BlackPixel(display
, screen
);
478 win
= XCreateSimpleWindow(display
, root
, sizehints
.x
, sizehints
.y
,
479 sizehints
.width
, sizehints
.height
,
480 borderwidth
, fore_pix
, back_pix
);
481 iconwin
= XCreateSimpleWindow(display
, win
, sizehints
.x
,
482 sizehints
.y
, sizehints
.width
,
483 sizehints
.height
, borderwidth
,
487 XSetWMNormalHints(display
, win
, &sizehints
);
488 classhint
.res_name
= wname
;
489 classhint
.res_class
= wname
;
490 XSetClassHint(display
, win
, &classhint
);
492 if (!XStringListToTextProperty(&wname
, 1, &name
))
493 error("Can't allocate window name.");
495 XSetWMName(display
, win
, &name
);
497 /* Create GC for drawing */
498 gcv
.foreground
= fore_pix
;
499 gcv
.background
= back_pix
;
500 gcv
.graphics_exposures
= 0;
501 NormalGC
= XCreateGC(display
, root
,
502 GCForeground
| GCBackground
| GCGraphicsExposures
,
505 pixmask
= XCreateBitmapFromData(display
, win
, mask_bits
,
506 mask_width
, mask_height
);
507 XShapeCombineMask(display
, win
, ShapeBounding
, 0, 0,
509 XShapeCombineMask(display
, iconwin
, ShapeBounding
, 0, 0,
512 wmhints
.initial_state
= initial_state
;
513 wmhints
.icon_window
= iconwin
;
514 wmhints
.icon_x
= sizehints
.x
;
515 wmhints
.icon_y
= sizehints
.y
;
516 wmhints
.window_group
= win
;
517 wmhints
.flags
= StateHint
| IconWindowHint
|
518 IconPositionHint
| WindowGroupHint
;
520 XSetWMHints(display
, win
, &wmhints
);
521 XSetCommand(display
, win
, argv
, argc
);
523 XSelectInput(display
, iconwin
, ExposureMask
);
524 XSelectInput(display
, win
, ExposureMask
);
526 XMapWindow(display
, win
);
529 void flush_expose(Window w
)
533 while (XCheckTypedWindowEvent(display
, w
, Expose
, &dummy
))
537 void redraw_window(void)
539 XCopyArea(display
, images
[FACE
], iconwin
, NormalGC
, 0, 0,
540 image_info
[FACE
].width
, image_info
[FACE
].height
, 0, 0);
541 flush_expose(iconwin
);
542 XCopyArea(display
, images
[FACE
], win
, NormalGC
, 0, 0,
543 image_info
[FACE
].width
, image_info
[FACE
].height
, 0, 0);
548 * Display an image, using XCopyArea. Can display only part of an image,
551 void copy_image(int image
, int xoffset
, int yoffset
,
552 int width
, int height
, int x
, int y
)
554 XCopyArea(display
, images
[image
], images
[FACE
], NormalGC
,
555 xoffset
, yoffset
, width
, height
, x
, y
);
559 * Display a letter in one of two fonts, at the specified x position.
560 * Note that 10 is passed for special characters `:' or `1' at the
563 void draw_letter(int letter
, int font
, int x
)
565 copy_image(font
, image_info
[font
].charwidth
* letter
, 0,
566 image_info
[font
].charwidth
, image_info
[font
].height
,
567 x
, image_info
[font
].y
);
570 /* Display an image at its normal location. */
571 void draw_image(int image
)
573 copy_image(image
, 0, 0,
574 image_info
[image
].width
, image_info
[image
].height
,
575 image_info
[image
].x
, image_info
[image
].y
);
578 void recalc_window(apm_info cur_info
)
580 int time_left
, hour_left
, min_left
, digit
, x
;
583 /* Display if it's plugged in. */
584 switch (cur_info
.ac_line_status
) {
585 case AC_LINE_STATUS_ON
:
589 draw_image(UNPLUGGED
);
592 /* Display the appropriate color battery. */
593 switch (cur_info
.battery_status
) {
594 case BATTERY_STATUS_HIGH
:
595 case BATTERY_STATUS_CHARGING
:
596 draw_image(BATTERY_HIGH
);
598 case BATTERY_STATUS_LOW
:
599 draw_image(BATTERY_LOW
);
601 case BATTERY_STATUS_CRITICAL
: /* blinking red battery */
603 draw_image(BATTERY_CRITICAL
);
605 draw_image(BATTERY_BLINK
);
609 draw_image(BATTERY_NONE
);
612 /* Show if the battery is charging. */
613 if (cur_info
.battery_flags
& BATTERY_FLAGS_CHARGING
)
614 draw_image(CHARGING
);
616 draw_image(NOCHARGING
);
619 * Display the percent left dial. This has the side effect of
620 * clearing the time left field.
622 x
= DIAL_MULTIPLIER
* cur_info
.battery_percentage
;
624 /* Start by displaying bright on the dial. */
625 copy_image(DIAL_BRIGHT
, 0, 0,
626 x
, image_info
[DIAL_BRIGHT
].height
,
627 image_info
[DIAL_BRIGHT
].x
,
628 image_info
[DIAL_BRIGHT
].y
);
630 /* Now display dim on the remainder of the dial. */
631 copy_image(DIAL_DIM
, x
, 0,
632 image_info
[DIAL_DIM
].width
- x
,
633 image_info
[DIAL_DIM
].height
,
634 image_info
[DIAL_DIM
].x
+ x
,
635 image_info
[DIAL_DIM
].y
);
637 /* Show percent remaining */
638 if (cur_info
.battery_percentage
>= 0) {
639 digit
= cur_info
.battery_percentage
/ 10;
641 /* 11 is the `1' for the hundreds place. */
642 draw_letter(11, SMALLFONT
, HUNDREDS_OFFSET
);
645 draw_letter(digit
, SMALLFONT
, TENS_OFFSET
);
646 digit
= cur_info
.battery_percentage
% 10;
647 draw_letter(digit
, SMALLFONT
, ONES_OFFSET
);
649 /* There is no battery, so we need to dim out the
650 * percent sign that is normally bright. */
651 draw_letter(10, SMALLFONT
, PERCENT_OFFSET
);
656 /* A negative number means that it is unknown. Dim the field. */
657 if (cur_info
.battery_time
< 0) {
658 draw_letter(10, BIGFONT
, COLON_OFFSET
);
663 if (cur_info
.using_minutes
)
664 time_left
= cur_info
.battery_time
;
666 time_left
= cur_info
.battery_time
/ 60;
667 hour_left
= time_left
/ 60;
668 min_left
= time_left
% 60;
669 digit
= hour_left
/ 10;
670 draw_letter(digit
, BIGFONT
, HOURS_TENS_OFFSET
);
671 digit
= hour_left
% 10;
672 draw_letter(digit
, BIGFONT
, HOURS_ONES_OFFSET
);
673 digit
= min_left
/ 10;
674 draw_letter(digit
, BIGFONT
, MINUTES_TENS_OFFSET
);
675 digit
= min_left
% 10;
676 draw_letter(digit
, BIGFONT
, MINUTES_ONES_OFFSET
);
686 audio
= open("/dev/audio", O_WRONLY
);
688 n
= write(audio
, crit_audio
, crit_audio_size
);
689 if (n
!= crit_audio_size
)
690 fprintf(stderr
, "write failed (%d/%d bytes)\n", n
, crit_audio_size
);
696 void alarmhandler(int sig
)
703 if (upower_read(1, &cur_info
) != 0)
704 error("Cannot read upower information.");
705 } else if (use_acpi
) {
709 if (acpi_read(battnum
, &cur_info
) != 0)
710 error("Cannot read ACPI information.");
713 else if (use_simplehal
) {
714 if (simplehal_read(battnum
, &cur_info
) != 0)
715 error("Cannot read HAL information.");
718 else if (!use_sonypi
) {
719 if (apm_read(&cur_info
) != 0)
720 error("Cannot read APM information.");
722 if (sonypi_read(&cur_info
) != 0)
723 error("Cannot read sonypi information.");
726 old_status
= cur_info
.battery_status
;
728 /* Always calculate remaining lifetime? apm and acpi both use a
729 * negative number here to indicate error, missing battery, or
730 * cannot determine time. */
731 if (always_estimate_remaining
|| cur_info
.battery_time
< 0)
732 estimate_timeleft(&cur_info
);
734 /* Override the battery status? */
735 if ((low_pct
> -1 || critical_pct
> -1) &&
736 cur_info
.ac_line_status
!= AC_LINE_STATUS_ON
) {
737 if (cur_info
.battery_percentage
<= critical_pct
)
738 cur_info
.battery_status
= BATTERY_STATUS_CRITICAL
;
739 else if (cur_info
.battery_percentage
<= low_pct
)
740 cur_info
.battery_status
= BATTERY_STATUS_LOW
;
742 cur_info
.battery_status
= BATTERY_STATUS_HIGH
;
745 /* If APM data changes redraw and wait for next update */
746 /* Always redraw if the status is critical, to make it blink. */
747 if (!apm_change(&cur_info
) || cur_info
.battery_status
== BATTERY_STATUS_CRITICAL
)
748 recalc_window(cur_info
);
750 if ((old_status
== BATTERY_STATUS_HIGH
) &&
751 (cur_info
.battery_status
== BATTERY_STATUS_LOW
)) {
753 } else if (cur_info
.battery_status
== BATTERY_STATUS_CRITICAL
) {
755 cmd_crit(crit_command
, cur_info
.battery_percentage
,
756 cur_info
.battery_time
);
762 void check_battery_num(int real
, int requested
)
764 if (requested
> real
|| requested
< 1) {
765 error("There %s only %i batter%s, and you asked for number %i.",
766 real
== 1 ? "is" : "are",
768 real
== 1 ? "y" : "ies",
773 int main(int argc
, char *argv
[])
775 make_window(parse_commandline(argc
, argv
), argc
, argv
);
777 /* Check for APM support (returns 0 on success). */
778 if (apm_exists() == 0) {
783 /* Check for hal support. */
784 else if (simplehal_supported()) {
791 else if (upower_supported())
794 /* Check for ACPI support. */
795 else if (acpi_supported() && acpi_batt_count
> 0) {
796 check_battery_num(acpi_batt_count
, battnum
);
799 delay
= 3; /* slow interface! */
800 } else if (sonypi_supported()) {
807 error("No APM, ACPI, UPOWER, HAL or SPIC support detected.");
813 signal(SIGALRM
, alarmhandler
);
814 alarmhandler(SIGALRM
);
818 XNextEvent(display
, &ev
);
819 if (ev
.type
== Expose
)