chiark / gitweb /
Merge branch 'master' into newacpi
[chiark-utils.git] / cprogs / xacpi-simple.c
1 /*
2  * display outputs, per line:
3  *
4  *   Remaining: | Empty:        | Degraded:
5  *     blue     |  black        |  dimgrey      discharging
6  *     green    |  black        |  dimgrey      charging
7  *     cyan     |  black        |  dimgrey      charged
8  *     grey     |  black        |  dimgrey      charging&discharching!
9  *     blue     |  red          |  dimgrey      discharging - low!
10  *     green    |  red          |  dimgrey      charging - low
11  *     cyan     |  red          |  dimgrey      charged - low [1]
12  *     grey     |  red          |  dimgrey      charging&discharching, low [1]
13  *       ...  darkgreen  ...                    no batteries present
14  *       ...  yellow  ...                       error
15  *
16  * [1] battery must be quite badly degraded
17  */
18 /*
19  * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
20  *
21  * This is free software; you can redistribute it and/or modify
22  * it under the terms of the GNU General Public License as
23  * published by the Free Software Foundation; either version 3,
24  * or (at your option) any later version.
25  *
26  * This is distributed in the hope that it will be useful, but
27  * WITHOUT ANY WARRANTY; without even the implied warranty of
28  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29  * GNU General Public License for more details.
30  *
31  * You should have received a copy of the GNU General Public
32  * License along with this file; if not, consult the Free Software
33  * Foundation's website at www.fsf.org, or the GNU Project website at
34  * www.gnu.org.
35  */
36
37 #include <stdio.h>
38 #include <assert.h>
39 #include <math.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <errno.h>
43 #include <unistd.h>
44 #include <ctype.h>
45
46 #include <sys/poll.h>
47 #include <sys/types.h>
48 #include <dirent.h>
49
50 #include <X11/Xlib.h>
51 #include <X11/Xutil.h>
52 #include <X11/Xresource.h>
53
54 #define TOP      60
55 #define BOTTOM 3600
56
57 #define TIMEOUT         5000 /* milliseconds */
58 #define TIMEOUT_ONERROR 3333 /* milliseconds */
59
60 static const char program_name[]= "xacpi-simple";
61
62 /*---------- general utility stuff and declarations ----------*/
63
64 static void fail(const char *m) {
65   fprintf(stderr,"error: %s\n", m);
66   exit(-1);
67 }
68 static void badusage(void) { fail("bad usage"); }
69
70 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state)  */
71 #define CHGST_CHARGING    1 /*  in fields table.  Also, much code assumes */
72 #define CHGST_CHARGED     2 /*  exactly these three possible states.      */
73 #define CHGST_ERROR       8 /* Except that this one is an extra bit.      */
74
75 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
76 /* variables thisbat_... are the results from readbattery();
77  * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
78  */
79
80 typedef struct batinfo_field {
81   const char *file;
82   const char *label;
83   const char *acpi_label;
84   double acpi_conversion_factor;
85   unsigned long *valuep;
86   const char *unit;
87   const char *enumarray[10];
88 } batinfo_field;
89
90 #define QUANTITY_FIELDS                                                 \
91   QF(info,  design_capacity,    "mWh", energy_full_design, 1e-3)        \
92   QF(info,  last_full_capacity, "mWh", energy_full,        1e-3)        \
93   QF(state, present_rate,       "mW",  power_now,          1e-3)        \
94   QF(state, remaining_capacity, "mWh", energy_now,         1e-3)        \
95   QF(alarm, alarm,              "mWh", alarm,              1e-3)
96
97 #define QF(f,l,u,a,ac) static unsigned long thisbat_##f##_##l;
98   QUANTITY_FIELDS
99 #undef QF
100
101 static unsigned long thisbat_alarm_present, thisbat_info_present;
102 static unsigned long thisbat_state_present, thisbat_state_charging_state;
103
104 #define VAL_NOTFOUND (~0UL)
105
106 static const batinfo_field fields[]= {
107 #define E(f,l)       #f, #l, &thisbat_##f##_##l, 0
108 #define QF(f,l,u)  { #f, #l, &thisbat_##f##_##l, u },
109   { E(alarm, present), 0,0,      { "no", "yes" }                          },
110   { E(info, present),  0,0,      { "no", "yes" }                          },
111   { E(state,present),  0,0,      { "no", "yes" }                          },
112   { E(state,charging_state),     { "discharging", "charging", "charged" } },
113   QUANTITY_FIELDS           /* take care re charging_state values order -  */
114   { 0 }                     /* if you must change it, search for CHGST_... */
115 #undef E
116 #undef QF
117 };
118
119 static const char *files[]= { "info", "state", "alarm" };
120
121 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
122
123 /* variables private to the parser and its error handlers */
124 static char batlinebuf[1000];
125 static FILE *batfile;
126 static const char *batdirname;
127 static const char *batfilename;
128 static const char *batlinevalue;
129
130 static int batfailf(const char *why) {
131   if (batlinevalue) {
132     fprintf(stderr,"battery/%s/%s: %s value `%s': %s\n",
133             batdirname,batfilename, batlinebuf,batlinevalue,why);
134   } else {
135     fprintf(stderr,"battery/%s/%s: %s: `%s'\n",
136             batdirname,batfilename, why, batlinebuf);
137   }
138   return -1;
139 }
140
141 static int batfaile(const char *syscall, const char *target) {
142   fprintf(stderr,"battery/%s: failed to %s %s: %s\n",
143           batdirname ? batdirname : "*", syscall, target, strerror(errno));
144   return -1;
145 }
146
147 static void chdir_base(void) {
148   int r;
149   
150   r= chdir("/proc/acpi/battery");
151   if (r) batfaile("chdir","/proc/acpi/battery");
152 }
153
154 static void tidybattery(void) {
155   if (batfile) { fclose(batfile); batfile=0; }
156   if (batdirname) { chdir_base(); batdirname=0; }
157 }
158
159 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
160   const batinfo_field *field;
161   const char *const *cfilename, *const *enumsearch;
162   char *colon, *ep, *sr, *p;
163   int r, l, missing;
164   
165   r= chdir(batdirname);
166   if (r) return batfaile("chdir",batdirname);
167
168   for (field=fields; field->file; field++)
169     *field->valuep= VAL_NOTFOUND;
170
171   for (cfilename=files;
172        (batfilename= *cfilename);
173        cfilename++) {
174     batfile= fopen(batfilename,"r");
175     if (!batfile) return batfaile("open",batfilename);
176
177     for (;;) {
178       batlinevalue= 0;
179       
180       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
181       if (ferror(batfile)) return batfaile("read",batfilename);
182       if (!sr && feof(batfile)) break;
183       l= strlen(batlinebuf);
184       assert(l>0);
185       if (batlinebuf[l-1] != '\n')
186         return batfailf("line too long");
187       batlinebuf[l-1]= 0;
188       colon= strchr(batlinebuf,':');
189       if (!colon)
190         return batfailf("line without a colon");
191       *colon= 0;
192
193       for (batlinevalue= colon+1;
194            *batlinevalue && isspace((unsigned char)*batlinevalue);
195            batlinevalue++);
196
197       if (!strcmp(batlinebuf,"ERROR"))
198         return batfailf("kernel reports error");
199
200       for (p=batlinebuf; p<colon; p++)
201         if (*p == ' ')
202           *p= '_';
203
204       for (field=fields; field->file; field++) {
205         if (!strcmp(field->file,batfilename) &&
206             !strcmp(field->label,batlinebuf))
207           goto label_interesting;
208       }
209       continue;
210
211     label_interesting:
212       if (field->unit) {
213
214         *field->valuep= strtoul(batlinevalue,&ep,10);
215         if (ep==batlinevalue || *ep!=' ')
216           batfailf("value number syntax incorrect");
217         if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
218
219       } else {
220         
221         for (*field->valuep=0, enumsearch=field->enumarray;
222              *enumsearch && strcmp(*enumsearch,batlinevalue);
223              (*field->valuep)++, enumsearch++);
224         if (!*enumsearch)
225           batfailf("unknown enum value");
226
227       }
228     }
229
230     fclose(batfile);
231     batfile= 0;
232   }
233
234   if (!(thisbat_alarm_present==0 ||
235         thisbat_state_present==0 || thisbat_info_present==0)) {
236     if (thisbat_alarm_present == VAL_NOTFOUND)
237       thisbat_alarm_present= 1;
238     
239     for (field=fields, missing=0;
240          field->file;
241          field++) {
242       if (*field->valuep == VAL_NOTFOUND) {
243         fprintf(stderr,"battery/%s/%s: %s: not found\n",
244                 batdirname, field->file,field->label);
245         missing++;
246       }
247     }
248     if (missing) return -1;
249   }
250
251   r= chdir("..");
252   if (r) return batfaile("chdir","..");
253   batdirname= 0;
254
255   return 0;
256 }   
257
258 /*---------- data collection and analysis ----------*/
259
260 /* These next three variables are the results of the charging state */
261 static unsigned charging_state_mask; /* 1u<<CHGST_* | ... */
262 static double nondegraded_norm, fill_norm, ratepersec_norm;
263 static int alarm_level; /* 0=ok, 1=low */
264
265 #define QF(f,l,u) \
266   static double total_##f##_##l;
267   QUANTITY_FIELDS
268 #undef QF
269
270 static void acquiredata(void) {
271   DIR *di;
272   struct dirent *de;
273   int r;
274   
275   charging_state_mask= 0;
276
277 #define QF(f,l,u) \
278   total_##f##_##l= 0;
279   QUANTITY_FIELDS
280 #undef QF
281
282   di= opendir(".");  if (!di) batfaile("opendir","battery");
283   while ((de= readdir(di))) {
284     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
285
286     batdirname= de->d_name;
287     r= readbattery();
288     tidybattery();
289
290     if (r) { charging_state_mask |= CHGST_ERROR; continue; }
291
292     if (!thisbat_info_present || !thisbat_state_present)
293       continue;
294
295     charging_state_mask |= 1u << thisbat_state_charging_state;
296
297 #define QF(f,l,u) \
298     total_##f##_##l += thisbat_##f##_##l;
299     QUANTITY_FIELDS
300 #undef QF
301
302     if (thisbat_state_charging_state == CHGST_DISCHARGING)
303       /* negate it */
304       total_state_present_rate -= 2.0 * thisbat_state_present_rate;
305       
306   }
307   closedir(di);
308
309   if (total_info_design_capacity < 0.5)
310     total_info_design_capacity= 1.0;
311
312   if (total_info_last_full_capacity < total_state_remaining_capacity)
313     total_info_last_full_capacity= total_state_remaining_capacity;
314   if (total_info_design_capacity < total_info_last_full_capacity)
315     total_info_design_capacity= total_info_last_full_capacity;
316
317   alarm_level=
318     (total_state_remaining_capacity < total_alarm_alarm &&
319      !(charging_state_mask & 1u << CHGST_CHARGING));
320
321   nondegraded_norm= total_info_last_full_capacity / total_info_design_capacity;
322   fill_norm= total_state_remaining_capacity / total_info_design_capacity;
323   ratepersec_norm=  total_state_present_rate
324     / (3600.0 * total_info_design_capacity);
325 }
326
327 static void initacquire(void) {
328   chdir_base();
329 }  
330
331 /*---------- argument parsing ----------*/
332
333 #define COLOURS                                 \
334   C(blue,      discharging)                     \
335   C(green,     charging)                        \
336   C(cyan,      charged)                         \
337   C(grey,      confusing)                       \
338   C(black,     normal)                          \
339   C(red,       low)                             \
340   C(dimgrey,   degraded)                        \
341   C(darkgreen, absent)                          \
342   C(yellow,    error)                           \
343   C(white,     equilibrium)                     \
344   GC(remain)                                    \
345   GC(white)                                     \
346   GC(empty)
347
348 static XrmDatabase xrm;
349 static Display *disp;
350 static int screen;
351
352 static const char defaultresources[]=
353 #define GC(g)
354 #define C(c,u)                                  \
355   "*" #u "Color: " #c "\n"
356   COLOURS
357 #undef GC
358 #undef C
359   ;
360
361 #define S(s) ((char*)(s))
362 static const XrmOptionDescRec optiontable[]= {
363   { S("-display"),      S("*display"),      XrmoptionSepArg },
364   { S("-geometry"),     S("*geometry"),     XrmoptionSepArg },
365 #define GC(g)
366 #define C(c,u)                                                  \
367   { S("-" #u "Color"),  S("*" #u "Color"),  XrmoptionSepArg },  \
368   { S("-" #u "Colour"), S("*" #u "Color"),  XrmoptionSepArg },
369   COLOURS
370 #undef GC
371 #undef C
372 };
373
374 static const char *getresource(const char *want) {
375   char name_buf[256], class_buf[256];
376   XrmValue val;
377   char *rep_type_dummy;
378   int r;
379
380   assert(strlen(want) < 128);
381   sprintf(name_buf,"xacpi-simple.%s",want);
382   sprintf(class_buf,"Xacpi-Simple.%s",want);
383   
384   r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
385   if (!r) return 0;
386   
387   return val.addr;
388 }
389
390 static void more_resources(const char *str, const char *why) {
391   XrmDatabase more;
392
393   if (!str) return;
394
395   more= XrmGetStringDatabase((char*)str);
396   if (!more) fail(why);
397   XrmCombineDatabase(more,&xrm,0);
398 }
399
400 static void parseargs(int argc, char **argv) {
401   Screen *screenscreen;
402   
403   XrmInitialize();
404
405   XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
406                   sizeof(optiontable)/sizeof(*optiontable),
407                   program_name, &argc, argv);
408
409   if (argc>1) badusage();
410
411   disp= XOpenDisplay(getresource("display"));
412   if (!disp) fail("could not open display");
413
414   screen= DefaultScreen(disp);
415
416   screenscreen= ScreenOfDisplay(disp,screen);
417   if (!screenscreen) fail("screenofdisplay");
418   more_resources(XScreenResourceString(screenscreen), "screen resources");
419   more_resources(XResourceManagerString(disp), "display resources");
420   more_resources(defaultresources, "default resources");
421
422
423 /*---------- display ----------*/
424
425 static Window win;
426 static int width, height;
427 static Colormap cmap;
428 static unsigned long lastbackground;
429
430 typedef struct {
431   GC gc;
432   unsigned long lastfg;
433 } Gcstate;
434
435 #define C(c,u) static unsigned long pix_##c;
436 #define GC(g) static Gcstate gc_##g;
437   COLOURS
438 #undef C
439 #undef GC
440
441 static void refresh(void);
442
443 #define CHGMASK_CHG_DIS (1u<<CHGST_CHARGING | 1u<<CHGST_DISCHARGING)
444
445 static void failr(const char *m, int r) {
446   fprintf(stderr,"error: %s (code %d)\n", m, r);
447   exit(-1);
448 }
449
450 static void setbackground(unsigned long newbg) {
451   int r;
452   
453   if (newbg == lastbackground) return;
454   r= XSetWindowBackground(disp,win,newbg);
455   if (!r) fail("XSetWindowBackground");
456   lastbackground= newbg;
457 }
458
459 static void setforeground(Gcstate *g, unsigned long px) {
460   XGCValues gcv;
461   int r;
462   
463   if (g->lastfg == px) return;
464   
465   memset(&gcv,0,sizeof(gcv));
466   g->lastfg= gcv.foreground= px;
467   r= XChangeGC(disp,g->gc,GCForeground,&gcv);
468   if (!r) fail("XChangeGC");
469 }
470
471 static void show_solid(unsigned long px) {
472   setbackground(px);
473   XClearWindow(disp,win);
474 }
475
476 static void show(void) {
477   double elap, then;
478   int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
479
480   if (!charging_state_mask)
481     return show_solid(pix_darkgreen);
482
483   if (charging_state_mask & CHGST_ERROR)
484     return show_solid(pix_yellow);
485
486   setbackground(pix_dimgrey);
487   XClearWindow(disp,win);
488   
489   setforeground(&gc_remain,
490                 !(charging_state_mask & CHGMASK_CHG_DIS) ? pix_cyan :
491                 !(~charging_state_mask & CHGMASK_CHG_DIS) ? pix_grey :
492                 charging_state_mask & (1u<<CHGST_CHARGING)
493                 ? pix_green : pix_blue);
494                 
495   setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
496
497   for (i=0, first_beyond=1; i<height; i++) {
498     elap= !i ? 0 :
499       height==2 ? BOTTOM :
500       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
501     
502     then= fill_norm + ratepersec_norm * elap;
503
504     beyond=
505       ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
506        (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
507
508     if (then <= 0.0) then= 0.0;
509     else if (then >= nondegraded_norm) then= nondegraded_norm;
510
511     leftmost_lit= width * then;
512     leftmost_nondeg= width * nondegraded_norm;
513
514     if (beyond && first_beyond) {
515       XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
516       first_beyond= 0;
517     } else {
518       if (leftmost_lit < leftmost_nondeg)
519         XDrawLine(disp, win, gc_empty.gc,
520                   leftmost_lit,i, leftmost_nondeg,i);
521       if (leftmost_lit >= 0)
522         XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
523     }
524   }
525 }
526
527 static void initgc(Gcstate *gc_r) {
528   XGCValues gcv;
529
530   memset(&gcv,0,sizeof(gcv));
531   gcv.function= GXcopy;
532   gcv.line_width= 1;
533   gc_r->lastfg= gcv.foreground= pix_white;
534   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
535 }
536
537 static void colour(unsigned long *pix_r, const char *whichcolour) {
538   XColor xc;
539   const char *name;
540   Status st;
541
542   name= getresource(whichcolour);
543   if (!name) fail("get colour resource");
544   
545   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
546   if (!st) fail(name);
547   
548   *pix_r= xc.pixel;
549 }
550
551 static void initgraphics(int argc, char **argv) {
552   int xwmgr, r;
553   const char *geom_string;
554   XSizeHints *normal_hints;
555   XWMHints *wm_hints;
556   XClassHint *class_hint;
557   int pos_x, pos_y, gravity;
558   char *program_name_silly;
559   
560   program_name_silly= (char*)program_name;
561
562   normal_hints= XAllocSizeHints();
563   wm_hints= XAllocWMHints();
564   class_hint= XAllocClassHint();
565
566   if (!normal_hints || !wm_hints || !class_hint)
567     fail("could not alloc hint(s)");
568
569   geom_string= getresource("geometry");
570
571   xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
572                  normal_hints,
573                  &pos_x, &pos_y,
574                  &width, &height,
575                  &gravity);
576
577   win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
578                            pos_x,pos_y,width,height,0,0,0);
579   cmap= DefaultColormap(disp,screen);
580   
581 #define C(c,u) colour(&pix_##c, #u "Color");
582 #define GC(g) initgc(&gc_##g);
583   COLOURS
584 #undef C
585 #undef GC
586
587   r= XSetWindowBackground(disp,win,pix_dimgrey);
588   if (!r) fail("init set background");
589   lastbackground= pix_dimgrey;
590
591   normal_hints->flags= PWinGravity;
592   normal_hints->win_gravity= gravity;
593   normal_hints->x= pos_x;
594   normal_hints->y= pos_y;
595   normal_hints->width= width;
596   normal_hints->height= height;
597   if ((xwmgr & XValue) || (xwmgr & YValue))
598     normal_hints->flags |= USPosition;
599
600   wm_hints->flags= InputHint;
601   wm_hints->input= False;
602
603   class_hint->res_name= program_name_silly;
604   class_hint->res_class= program_name_silly;
605
606   XmbSetWMProperties(disp,win, program_name,program_name,
607                      argv,argc, normal_hints, wm_hints, class_hint);
608
609   XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
610   XMapWindow(disp,win);
611 }
612  
613 static void refresh(void) {
614   acquiredata();
615   show();
616 }
617
618 static void newgeometry(void) {
619   int dummy;
620   Window dummyw;
621   
622   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
623 }
624
625 static void eventloop(void) {
626   XEvent ev;
627   struct pollfd pfd;
628   int r, timeout;
629   
630   newgeometry();
631   refresh();
632
633   for (;;) {
634     XFlush(disp);
635
636     pfd.fd= ConnectionNumber(disp);
637     pfd.events= POLLIN|POLLERR;
638
639     timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
640     r= poll(&pfd,1,timeout);
641     if (r==-1 && errno!=EINTR) failr("poll",errno);
642
643     while (XPending(disp)) {
644       XNextEvent(disp,&ev);
645       if (ev.type == ConfigureNotify) {
646         XConfigureEvent *ce= (void*)&ev;
647         width= ce->width;
648         height= ce->height;
649       }
650     }
651     refresh();
652   }
653 }
654
655 int main(int argc, char **argv) {
656   parseargs(argc,argv);
657   initacquire();
658   initgraphics(argc,argv);
659   eventloop();
660   return 0;
661 }