chiark / gitweb /
9d67c37bbbe7ba69b1e287853645afb05bc7f112
[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  *     darkcyan |  black        |  dimgrey      none of the above
10  *     blue     |  red          |  dimgrey      discharging - low!
11  *     green    |  red          |  dimgrey      charging - low
12  *     cyan     |  red          |  dimgrey      charged - low [1]
13  *     grey     |  red          |  dimgrey      charging&discharching, low [1]
14  *       ...  darkgreen  ...                    no batteries present
15  *       ...  yellow  ...                       error
16  *
17  * [1] battery must be quite badly degraded
18  */
19 /*
20  * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
21  *
22  * This is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as
24  * published by the Free Software Foundation; either version 3,
25  * or (at your option) any later version.
26  *
27  * This is distributed in the hope that it will be useful, but
28  * WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public
33  * License along with this file; if not, consult the Free Software
34  * Foundation's website at www.fsf.org, or the GNU Project website at
35  * www.gnu.org.
36  */
37
38 #include <stdio.h>
39 #include <assert.h>
40 #include <math.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <ctype.h>
46 #include <stdint.h>
47 #include <limits.h>
48 #include <inttypes.h>
49
50 #include <sys/poll.h>
51 #include <sys/types.h>
52 #include <dirent.h>
53
54 #include <X11/Xlib.h>
55 #include <X11/Xutil.h>
56 #include <X11/Xresource.h>
57
58 #define TOP      60
59 #define BOTTOM 3600
60
61 #define TIMEOUT         5000 /* milliseconds */
62 #define TIMEOUT_ONERROR 3333 /* milliseconds */
63
64 static const char program_name[]= "xacpi-simple";
65 static int debug, alarmlevel;
66
67 /*---------- general utility stuff and declarations ----------*/
68
69 static void fail(const char *m) {
70   fprintf(stderr,"error: %s\n", m);
71   exit(-1);
72 }
73 static void badusage(void) { fail("bad usage"); }
74
75 typedef uint64_t value;
76 #define VAL_NOTFOUND (~(value)0)
77
78 typedef struct fileinfo fileinfo;
79 typedef int parser(const fileinfo*);
80
81 static parser parse_uevent;
82
83 struct fileinfo {
84   const char *filename;
85   parser *parse;
86   const void *extra;
87 };
88
89 /*---------- structure of and results from /sys/class/power/... ----------*/
90 /* variables this_... are the results from readbattery();
91  * if readbattery() succeeds the appropriate ones are all valid
92  * and not VAL_NOTFOUND
93  */
94
95 typedef struct batinfo_field {
96   const char *label;
97   value *valuep;
98   const char *enumarray[10];
99 } batinfo_field;
100
101 #define BAT_QTYS(_, _ec, EC_, PC_)                              \
102   _(design_capacity##_ec,    BATTERY,  EC_##FULL_DESIGN )       \
103   _(last_full_capacity##_ec, BATTERY,  EC_##FULL        )       \
104   _(remaining_capacity##_ec, BATTERY,  EC_##NOW         )       \
105   _(present_rate##_ec,       BATTERY,  PC_##NOW         )
106  /* ENERGY [mWh]; POWER [mW]; CHARGE [uAh]; CURRENT [uA] */
107
108 #define UEVENT_ESSENTIAL_QUANTITY_FIELDS(_)                     \
109   _(present,                 BATTERY,  PRESENT /* bool */ )     \
110   _(online,                  MAINS,    ONLINE  /* bool */ )
111
112 #define UEVENT_FUNKY_QUANTITY_FIELDS(_)         \
113   BAT_QTYS(_,_energy,ENERGY_,POWER_)            \
114   BAT_QTYS(_,_charge,CHARGE_,CURRENT_)
115
116 #define UEVENT_OPTIONAL_QUANTITY_FIELDS(_)                      \
117   _(voltage,                 BATTERY,  VOLTAGE_NOW /* uV */ )
118
119 #define UEVENT_ENUM_FIELDS(_)                                           \
120   _(state,   BATTERY,  STATUS,  "Discharging","Charging","Full","Unknown" ) \
121   _(type,    BOTH,     TYPE,    "Mains",       "Battery"              )
122
123 #define CHGST_DISCHARGING 0 /* Reflects order in _(state,...) above     */
124 #define CHGST_CHARGING    1 /* Also, much code assumes exactly          */
125 #define CHGST_CHARGED     2 /* these three possible states.             */
126 #define CHGST_UNKNOWN     3 /* these three possible states.             */
127 #define CHGST_ERROR       8 /* Except that this one is an extra bit.    */
128
129 #define TYPE_MAINS        0 /* Reflects order in _(type,...) above        */
130 #define TYPE_BATTERY      1 /* Also, much code assumes exactly these two  */
131 #define TYPE_BOTH       100 /* Except this is a magic invalid value.      */
132
133 #define SEPARATE_QUANTITY_FIELDS(_)             \
134   /* See commit ec6f5f0be800bc5f2a27046833dba04e0c67ffac for
135      the code needed to use this */
136
137
138 #define ALL_DIRECT_VARS(_)                      \
139   UEVENT_ESSENTIAL_QUANTITY_FIELDS(_)           \
140   UEVENT_FUNKY_QUANTITY_FIELDS(_)               \
141   UEVENT_OPTIONAL_QUANTITY_FIELDS(_)            \
142   UEVENT_ENUM_FIELDS(_)                         \
143   SEPARATE_QUANTITY_FIELDS(_)
144
145 #define ALL_VARS(_)                             \
146   ALL_DIRECT_VARS(_)                            \
147   BAT_QTYS(_,,,)
148
149 #define ALL_NEEDED_FIELDS(_)                    \
150   UEVENT_ESSENTIAL_QUANTITY_FIELDS(_)           \
151   UEVENT_ENUM_FIELDS(_)                         \
152   SEPARATE_QUANTITY_FIELDS(_)
153
154 #define ALL_PLAIN_ACCUMULATE_FIELDS(_)          \
155   UEVENT_ESSENTIAL_QUANTITY_FIELDS(_)           \
156   UEVENT_ENUM_FIELDS(_)                         \
157   SEPARATE_QUANTITY_FIELDS(_)
158
159 #define ALL_ACCUMULATE_FIELDS(_)                \
160   ALL_PLAIN_ACCUMULATE_FIELDS(_)                \
161   BAT_QTYS(_,,,)
162
163
164 #define F_VAR(f,...) \
165 static value this_##f;
166 ALL_VARS(F_VAR)
167
168 #define Q_FLD(f,t,l)        { "POWER_SUPPLY_" #l, &this_##f },
169 #define E_FLD(f,t,l,vl...)  { "POWER_SUPPLY_" #l, &this_##f, { vl } },
170
171 static const batinfo_field uevent_fields[]= {
172   UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
173   UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
174   UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
175   UEVENT_ENUM_FIELDS(E_FLD)
176   { 0 }
177 };
178
179 #define S_FLD(f,t,fn,vl...)                                             \
180 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
181   SEPARATE_QUANTITY_FIELDS(S_FLD)
182
183 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
184
185 static const fileinfo files[]= {
186   { "uevent",  parse_uevent,  uevent_fields },
187   SEPARATE_QUANTITY_FIELDS(S_FILE)
188   { 0 }
189 };
190
191 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
192
193 /* variables private to the parser and its error handlers */
194 static char batlinebuf[1000];
195 static FILE *batfile;
196 static const char *batdirname;
197 static const char *batfilename;
198 static const char *batlinevalue;
199
200 static int batfailf(const char *why) {
201   if (batlinevalue) {
202     fprintf(stderr,"%s/%s: %s value `%s': %s\n",
203             batdirname,batfilename, batlinebuf,batlinevalue,why);
204   } else {
205     fprintf(stderr,"%s/%s: %s: `%s'\n",
206             batdirname,batfilename, why, batlinebuf);
207   }
208   return -1;
209 }
210
211 static int batfailc(const char *why) {
212   fprintf(stderr,"%s/%s: %s\n",
213           batdirname,batfilename, why);
214   return -1;
215 }
216
217 static int batfaile(const char *syscall, const char *target) {
218   fprintf(stderr,"%s: failed to %s %s: %s\n",
219           batdirname ? batdirname : "*", syscall, target, strerror(errno));
220   return -1;
221 }
222
223 static int chdir_base(void) {
224   int r;
225   
226   r= chdir("/sys/class/power_supply");
227   if (r) return batfaile("chdir","/sys/class/power_supply");
228
229   return 0;
230 }
231
232 static void tidybattery(void) {
233   if (batfile) { fclose(batfile); batfile=0; }
234 }
235
236 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
237   if (*field->valuep != VAL_NOTFOUND)
238     return batfailf("value specified multiple times");
239
240   if (!field->enumarray[0]) {
241
242     char *ep;
243     *field->valuep= strtoull(batlinevalue,&ep,10);
244     if (*ep)
245       batfailf("value number syntax incorrect");
246
247   } else {
248         
249     const char *const *enumsearch;
250     for (*field->valuep=0, enumsearch=field->enumarray;
251          *enumsearch && strcmp(*enumsearch,batlinevalue);
252          (*field->valuep)++, enumsearch++);
253     if (!*enumsearch)
254       batfailf("unknown enum value");
255
256   }
257   return 0;
258 }
259
260 static int parse_uevent(const fileinfo *cfile) {
261   char *equals= strchr(batlinebuf,'=');
262   if (!equals)
263     return batfailf("line without a equals");
264   *equals= 0;
265   batlinevalue = equals+1;
266
267   const batinfo_field *field;
268   for (field=cfile->extra; field->label; field++) {
269     if (!strcmp(field->label,batlinebuf))
270       goto found;
271   }
272   return 0;
273
274  found:
275   return parse_value(cfile, field);
276 }
277
278 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
279   
280   const fileinfo *cfile;
281   char *sr;
282   int r, l;
283   
284   r= chdir_base();
285   if (r) return r;
286
287   r= chdir(batdirname);
288   if (r) return batfaile("chdir",batdirname);
289
290 #define V_NOTFOUND(f,...) \
291   this_##f = VAL_NOTFOUND;
292 ALL_VARS(V_NOTFOUND)
293
294   for (cfile=files;
295        (batfilename= cfile->filename);
296        cfile++) {
297     batfile= fopen(batfilename,"r");
298     if (!batfile) {
299       if (errno == ENOENT) continue;
300       return batfaile("open",batfilename);
301     }
302
303     for (;;) {
304       batlinevalue= 0;
305       
306       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
307       if (ferror(batfile)) return batfaile("read",batfilename);
308       if (!sr && feof(batfile)) break;
309       l= strlen(batlinebuf);
310       assert(l>0);
311       if (batlinebuf[l-1] != '\n')
312         return batfailf("line too long");
313       batlinebuf[l-1]= 0;
314
315       if (cfile->parse(cfile))
316         return -1;
317     }
318
319     fclose(batfile);
320     batfile= 0;
321   }
322
323   if (debug) {
324     printf("%s:\n",batdirname);
325 #define V_PRINT(f,...)                                  \
326     printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
327 ALL_DIRECT_VARS(V_PRINT)
328   }
329
330   int needsfields_MAINS   = this_type == TYPE_MAINS;
331   int needsfields_BATTERY = this_type == TYPE_BATTERY;
332   int needsfields_BOTH    = 1;
333
334   int missing = 0;
335
336 #define V_NEEDED(f,t,...)                               \
337   if (needsfields_##t && this_##f == VAL_NOTFOUND) {    \
338     fprintf(stderr,"%s: %s: not found\n",               \
339             batdirname, #f);                            \
340     missing++;                                          \
341   }
342 ALL_NEEDED_FIELDS(V_NEEDED)
343
344   if (missing) return -1;
345
346   return 0;
347 }   
348
349 /*---------- data collection and analysis ----------*/
350
351 /* These next three variables are the results of the charging state */
352 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
353 static double nondegraded_norm, fill_norm, ratepersec_norm;
354 static int alarmed;
355
356 #define Q_VAR(f,t,...) \
357 static double total_##f;
358   ALL_ACCUMULATE_FIELDS(Q_VAR)
359
360 static void acquiredata(void) {
361   DIR *di;
362   struct dirent *de;
363   int r;
364   
365   charging_mask= 0;
366   alarmed = 0;
367
368 #define Q_ZERO(f,t,...) \
369   total_##f= 0;
370 ALL_ACCUMULATE_FIELDS(Q_ZERO)
371
372   r = chdir_base();
373   if (r) goto bad;
374
375   di= opendir(".");  if (!di) { batfaile("opendir","battery"); goto bad; }
376   while ((de= readdir(di))) {
377     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
378
379     batdirname= de->d_name;
380     r= readbattery();
381     tidybattery();
382
383     if (r) {
384     bad:
385       charging_mask |= (1u << CHGST_ERROR);
386       break;
387     }
388
389     if (this_type == TYPE_BATTERY) {
390       if (!this_present)
391         continue;
392
393       charging_mask |= 1u << this_state;
394
395 #define QTY_SUPPLIED(f,...)   this_##f != VAL_NOTFOUND &&
396 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
397 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
398
399       double funky_multiplier;
400       if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
401         if (debug) printf(" using energy\n");
402         BAT_QTYS(QTY_USE_ENERGY,,,);
403         funky_multiplier = 1.0;
404       } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
405                  this_voltage != VAL_NOTFOUND) {
406         if (debug) printf(" using charge\n");
407         BAT_QTYS(QTY_USE_CHARGE,,,);
408         funky_multiplier = this_voltage * 1e-6;
409       } else {
410         batfailc("neither complete set of energy nor charge");
411         continue;
412       }
413       if (this_state == CHGST_DISCHARGING)
414         /* negate it */
415         total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
416
417 #define Q_ACCUMULATE_FUNKY(f,...)                       \
418       total_##f += this_##f * funky_multiplier;
419 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
420     }
421
422 #define Q_ACCUMULATE_PLAIN(f,t,...)                     \
423     if (this_type == TYPE_##t)                  \
424       total_##f += this_##f;
425 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
426
427       
428   }
429   closedir(di);
430
431   printf("TOTAL:\n");
432 #define T_PRINT(f,...)                                  \
433     printf(" %-30s = %20.6f\n", #f, total_##f);
434 BAT_QTYS(T_PRINT,,,)
435 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
436   }
437
438   if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
439       !total_online/*mains*/) {
440     double time_remaining =
441       -total_remaining_capacity * 3600.0 / total_present_rate;
442     if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
443     if (time_remaining < alarmlevel)
444       alarmed = 1;
445   }
446
447   if (total_design_capacity < 0.5)
448     total_design_capacity= 1.0;
449
450   if (total_last_full_capacity < total_remaining_capacity)
451     total_last_full_capacity= total_remaining_capacity;
452   if (total_design_capacity < total_last_full_capacity)
453     total_design_capacity= total_last_full_capacity;
454
455   nondegraded_norm= total_last_full_capacity / total_design_capacity;
456   fill_norm= total_remaining_capacity / total_design_capacity;
457   ratepersec_norm=  total_present_rate
458     / (3600.0 * total_design_capacity);
459 }
460
461 static void initacquire(void) {
462 }  
463
464 /*---------- argument parsing ----------*/
465
466 #define COLOURS                                 \
467   C(blue,      discharging)                     \
468   C(green,     charging)                        \
469   C(cyan,      charged)                         \
470   C(darkcyan,  notcharging)                     \
471   C(grey,      confusing)                       \
472   C(black,     normal)                          \
473   C(red,       low)                             \
474   C(dimgrey,   degraded)                        \
475   C(darkgreen, absent)                          \
476   C(yellow,    error)                           \
477   C(white,     equilibrium)                     \
478   GC(remain)                                    \
479   GC(white)                                     \
480   GC(empty)
481
482 static XrmDatabase xrm;
483 static Display *disp;
484 static int screen;
485
486 static const char defaultresources[]=
487 #define GC(g)
488 #define C(c,u)                                  \
489   "*" #u "Color: " #c "\n"
490   COLOURS
491 #undef GC
492 #undef C
493   ;
494
495 #define S(s) ((char*)(s))
496 static const XrmOptionDescRec optiontable[]= {
497   { S("-debug"),        S("*debug"),        XrmoptionIsArg },
498   { S("-warningTime"),  S("*warningTime"),  XrmoptionSepArg },
499   { S("-display"),      S("*display"),      XrmoptionSepArg },
500   { S("-geometry"),     S("*geometry"),     XrmoptionSepArg },
501 #define GC(g)
502 #define C(c,u)                                                  \
503   { S("-" #u "Color"),  S("*" #u "Color"),  XrmoptionSepArg },  \
504   { S("-" #u "Colour"), S("*" #u "Color"),  XrmoptionSepArg },
505   COLOURS
506 #undef GC
507 #undef C
508 };
509
510 static const char *getresource(const char *want) {
511   char name_buf[256], class_buf[256];
512   XrmValue val;
513   char *rep_type_dummy;
514   int r;
515
516   assert(strlen(want) < 128);
517   sprintf(name_buf,"xacpi-simple.%s",want);
518   sprintf(class_buf,"Xacpi-Simple.%s",want);
519   
520   r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
521   if (!r) return 0;
522   
523   return val.addr;
524 }
525
526 static void more_resources(const char *str, const char *why) {
527   XrmDatabase more;
528
529   if (!str) return;
530
531   more= XrmGetStringDatabase((char*)str);
532   if (!more) fail(why);
533   XrmCombineDatabase(more,&xrm,0);
534 }
535
536 static void parseargs(int argc, char **argv) {
537   Screen *screenscreen;
538   
539   XrmInitialize();
540
541   XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
542                   sizeof(optiontable)/sizeof(*optiontable),
543                   program_name, &argc, argv);
544
545   if (argc>1) badusage();
546
547   debug= !!getresource("debug");
548
549   const char *alarmlevel_string= getresource("alarmLevel");
550   alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
551
552   disp= XOpenDisplay(getresource("display"));
553   if (!disp) fail("could not open display");
554
555   screen= DefaultScreen(disp);
556
557   screenscreen= ScreenOfDisplay(disp,screen);
558   if (!screenscreen) fail("screenofdisplay");
559   more_resources(XScreenResourceString(screenscreen), "screen resources");
560   more_resources(XResourceManagerString(disp), "display resources");
561   more_resources(defaultresources, "default resources");
562
563
564 /*---------- display ----------*/
565
566 static Window win;
567 static int width, height;
568 static Colormap cmap;
569 static unsigned long lastbackground;
570
571 typedef struct {
572   GC gc;
573   unsigned long lastfg;
574 } Gcstate;
575
576 #define C(c,u) static unsigned long pix_##c;
577 #define GC(g) static Gcstate gc_##g;
578   COLOURS
579 #undef C
580 #undef GC
581
582 static void refresh(void);
583
584 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
585
586 static void failr(const char *m, int r) {
587   fprintf(stderr,"error: %s (code %d)\n", m, r);
588   exit(-1);
589 }
590
591 static void setbackground(unsigned long newbg) {
592   int r;
593   
594   if (newbg == lastbackground) return;
595   r= XSetWindowBackground(disp,win,newbg);
596   if (!r) fail("XSetWindowBackground");
597   lastbackground= newbg;
598 }
599
600 static void setforeground(Gcstate *g, unsigned long px) {
601   XGCValues gcv;
602   int r;
603   
604   if (g->lastfg == px) return;
605   
606   memset(&gcv,0,sizeof(gcv));
607   g->lastfg= gcv.foreground= px;
608   r= XChangeGC(disp,g->gc,GCForeground,&gcv);
609   if (!r) fail("XChangeGC");
610 }
611
612 static void show_solid(unsigned long px) {
613   setbackground(px);
614   XClearWindow(disp,win);
615 }
616
617 static void show(void) {
618   double elap, then;
619   int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
620
621   if (!charging_mask)
622     return show_solid(pix_darkgreen);
623
624   if (charging_mask & (1u << CHGST_ERROR))
625     return show_solid(pix_yellow);
626
627   setbackground(pix_dimgrey);
628   XClearWindow(disp,win);
629   
630   setforeground(&gc_remain,
631                 !(charging_mask & CHGMASK_CHG_DIS) ?
632                 (~charging_mask & (1u << CHGST_CHARGED) ?
633                  pix_darkcyan : pix_cyan) :
634                 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
635                 charging_mask & (1u<<CHGST_CHARGING)
636                 ? pix_green : pix_blue);
637                 
638   setforeground(&gc_empty, alarmed ? pix_red : pix_black);
639
640   for (i=0, first_beyond=1; i<height; i++) {
641     elap= !i ? 0 :
642       height==2 ? BOTTOM :
643       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
644     
645     then= fill_norm + ratepersec_norm * elap;
646
647     beyond=
648       ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
649        (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
650
651     if (then <= 0.0) then= 0.0;
652     else if (then >= nondegraded_norm) then= nondegraded_norm;
653
654     leftmost_lit= width * then;
655     leftmost_nondeg= width * nondegraded_norm;
656
657     if (beyond && first_beyond) {
658       XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
659       first_beyond= 0;
660     } else {
661       if (leftmost_lit < leftmost_nondeg)
662         XDrawLine(disp, win, gc_empty.gc,
663                   leftmost_lit,i, leftmost_nondeg,i);
664       if (leftmost_lit >= 0)
665         XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
666     }
667   }
668 }
669
670 static void initgc(Gcstate *gc_r) {
671   XGCValues gcv;
672
673   memset(&gcv,0,sizeof(gcv));
674   gcv.function= GXcopy;
675   gcv.line_width= 1;
676   gc_r->lastfg= gcv.foreground= pix_white;
677   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
678 }
679
680 static void colour(unsigned long *pix_r, const char *whichcolour) {
681   XColor xc;
682   const char *name;
683   Status st;
684
685   name= getresource(whichcolour);
686   if (!name) fail("get colour resource");
687   
688   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
689   if (!st) fail(name);
690   
691   *pix_r= xc.pixel;
692 }
693
694 static void initgraphics(int argc, char **argv) {
695   int xwmgr, r;
696   const char *geom_string;
697   XSizeHints *normal_hints;
698   XWMHints *wm_hints;
699   XClassHint *class_hint;
700   int pos_x, pos_y, gravity;
701   char *program_name_silly;
702   
703   program_name_silly= (char*)program_name;
704
705   normal_hints= XAllocSizeHints();
706   wm_hints= XAllocWMHints();
707   class_hint= XAllocClassHint();
708
709   if (!normal_hints || !wm_hints || !class_hint)
710     fail("could not alloc hint(s)");
711
712   geom_string= getresource("geometry");
713
714   xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
715                  normal_hints,
716                  &pos_x, &pos_y,
717                  &width, &height,
718                  &gravity);
719
720   win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
721                            pos_x,pos_y,width,height,0,0,0);
722   cmap= DefaultColormap(disp,screen);
723   
724 #define C(c,u) colour(&pix_##c, #u "Color");
725 #define GC(g) initgc(&gc_##g);
726   COLOURS
727 #undef C
728 #undef GC
729
730   r= XSetWindowBackground(disp,win,pix_dimgrey);
731   if (!r) fail("init set background");
732   lastbackground= pix_dimgrey;
733
734   normal_hints->flags= PWinGravity;
735   normal_hints->win_gravity= gravity;
736   normal_hints->x= pos_x;
737   normal_hints->y= pos_y;
738   normal_hints->width= width;
739   normal_hints->height= height;
740   if ((xwmgr & XValue) || (xwmgr & YValue))
741     normal_hints->flags |= USPosition;
742
743   wm_hints->flags= InputHint;
744   wm_hints->input= False;
745
746   class_hint->res_name= program_name_silly;
747   class_hint->res_class= program_name_silly;
748
749   XmbSetWMProperties(disp,win, program_name,program_name,
750                      argv,argc, normal_hints, wm_hints, class_hint);
751
752   XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
753   XMapWindow(disp,win);
754 }
755  
756 static void refresh(void) {
757   acquiredata();
758   show();
759 }
760
761 static void newgeometry(void) {
762   int dummy;
763   unsigned int udummy, gotwidth, gotheight;
764   Window dummyw;
765   
766   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
767                &udummy,&udummy);
768   assert(gotwidth < INT_MAX);
769   assert(gotheight < INT_MAX);
770   width = gotwidth;
771   height = gotheight;
772 }
773
774 static void eventloop(void) {
775   XEvent ev;
776   struct pollfd pfd;
777   int r, timeout;
778   
779   newgeometry();
780   refresh();
781
782   for (;;) {
783     XFlush(disp);
784
785     pfd.fd= ConnectionNumber(disp);
786     pfd.events= POLLIN|POLLERR;
787
788     timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
789     r= poll(&pfd,1,timeout);
790     if (r==-1 && errno!=EINTR) failr("poll",errno);
791
792     while (XPending(disp)) {
793       XNextEvent(disp,&ev);
794       if (ev.type == ConfigureNotify) {
795         XConfigureEvent *ce= (void*)&ev;
796         width= ce->width;
797         height= ce->height;
798       }
799     }
800     refresh();
801   }
802 }
803
804 int main(int argc, char **argv) {
805   parseargs(argc,argv);
806   initacquire();
807   initgraphics(argc,argv);
808   eventloop();
809   return 0;
810 }