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