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