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