chiark / gitweb /
Make xbatmon-simple tolerate the lack of "type" in power supply uevent fields, by...
[chiark-utils.git] / cprogs / xbatmon-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  *     lightgrey |  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[]= "xbatmon-simple";
65 static int debug=-1, 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   SEPARATE_QUANTITY_FIELDS(_)
157
158 #define ALL_ACCUMULATE_FIELDS(_)                \
159   ALL_PLAIN_ACCUMULATE_FIELDS(_)                \
160   BAT_QTYS(_,,,)
161
162
163 #define F_VAR(f,...) \
164 static value this_##f;
165 ALL_VARS(F_VAR)
166
167 #define Q_FLD(f,t,l)        { "POWER_SUPPLY_" #l, &this_##f },
168 #define E_FLD(f,t,l,vl...)  { "POWER_SUPPLY_" #l, &this_##f, { vl } },
169
170 static const batinfo_field uevent_fields[]= {
171   UEVENT_ESSENTIAL_QUANTITY_FIELDS(Q_FLD)
172   UEVENT_FUNKY_QUANTITY_FIELDS(Q_FLD)
173   UEVENT_OPTIONAL_QUANTITY_FIELDS(Q_FLD)
174   UEVENT_ENUM_FIELDS(E_FLD)
175   { 0 }
176 };
177
178 #define S_FLD(f,t,fn,vl...)                                             \
179 static const batinfo_field bif_##f = { 0, &this_##f, { vl } };
180   SEPARATE_QUANTITY_FIELDS(S_FLD)
181
182 #define S_FILE(f,t,fn,vl...) { fn, parse_separate, &bif_##f },
183
184 static const fileinfo files[]= {
185   { "uevent",  parse_uevent,  uevent_fields },
186   SEPARATE_QUANTITY_FIELDS(S_FILE)
187   { 0 }
188 };
189
190 /*---------- parsing of one thingx in /sys/class/power/... ----------*/
191
192 /* variables private to the parser and its error handlers */
193 static char batlinebuf[1000];
194 static FILE *batfile;
195 static const char *batdirname;
196 static const char *batfilename;
197 static const char *batlinevalue;
198
199 static int batfailf(const char *why) {
200   if (batlinevalue) {
201     fprintf(stderr,"%s/%s: %s value `%s': %s\n",
202             batdirname,batfilename, batlinebuf,batlinevalue,why);
203   } else {
204     fprintf(stderr,"%s/%s: %s: `%s'\n",
205             batdirname,batfilename, why, batlinebuf);
206   }
207   return -1;
208 }
209
210 static int batfailc(const char *why) {
211   fprintf(stderr,"%s/%s: %s\n",
212           batdirname,batfilename, why);
213   return -1;
214 }
215
216 static int batfaile(const char *syscall, const char *target) {
217   fprintf(stderr,"%s: failed to %s %s: %s\n",
218           batdirname ? batdirname : "*", syscall, target, strerror(errno));
219   return -1;
220 }
221
222 static int chdir_base(void) {
223   int r;
224   
225   r= chdir("/sys/class/power_supply");
226   if (r) return batfaile("chdir","/sys/class/power_supply");
227
228   return 0;
229 }
230
231 static void tidybattery(void) {
232   if (batfile) { fclose(batfile); batfile=0; }
233 }
234
235 static int parse_value(const fileinfo *cfile, const batinfo_field *field) {
236   if (*field->valuep != VAL_NOTFOUND)
237     return batfailf("value specified multiple times");
238
239   if (!field->enumarray[0]) {
240
241     char *ep;
242     *field->valuep= strtoull(batlinevalue,&ep,10);
243     if (*ep)
244       batfailf("value number syntax incorrect");
245
246   } else {
247         
248     const char *const *enumsearch;
249     for (*field->valuep=0, enumsearch=field->enumarray;
250          *enumsearch && strcmp(*enumsearch,batlinevalue);
251          (*field->valuep)++, enumsearch++);
252     if (!*enumsearch)
253       batfailf("unknown enum value");
254
255   }
256   return 0;
257 }
258
259 static int parse_uevent(const fileinfo *cfile) {
260   char *equals= strchr(batlinebuf,'=');
261   if (!equals)
262     return batfailf("line without a equals");
263   *equals= 0;
264   batlinevalue = equals+1;
265
266   const batinfo_field *field;
267   for (field=cfile->extra; field->label; field++) {
268     if (!strcmp(field->label,batlinebuf))
269       goto found;
270   }
271   return 0;
272
273  found:
274   return parse_value(cfile, field);
275 }
276
277 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
278   
279   const fileinfo *cfile;
280   char *sr;
281   int r, l;
282   
283   r= chdir_base();
284   if (r) return r;
285
286   r= chdir(batdirname);
287   if (r) return batfaile("chdir",batdirname);
288
289 #define V_NOTFOUND(f,...) \
290   this_##f = VAL_NOTFOUND;
291 ALL_VARS(V_NOTFOUND)
292
293   for (cfile=files;
294        (batfilename= cfile->filename);
295        cfile++) {
296     batfile= fopen(batfilename,"r");
297     if (!batfile) {
298       if (errno == ENOENT) continue;
299       return batfaile("open",batfilename);
300     }
301
302     for (;;) {
303       batlinevalue= 0;
304       
305       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
306       if (ferror(batfile)) return batfaile("read",batfilename);
307       if (!sr && feof(batfile)) break;
308       l= strlen(batlinebuf);
309       assert(l>0);
310       if (batlinebuf[l-1] != '\n')
311         return batfailf("line too long");
312       batlinebuf[l-1]= 0;
313
314       if (cfile->parse(cfile))
315         return -1;
316     }
317
318     fclose(batfile);
319     batfile= 0;
320   }
321
322   if (debug) {
323     printf("%s:\n",batdirname);
324 #define V_PRINT(f,...)                                  \
325     printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
326 ALL_DIRECT_VARS(V_PRINT)
327   }
328
329   if (this_type == -1) {
330     /* some kernels don't seem to provide TYPE in the uevent
331      * guess the type from whether we see "present" or "online" */
332     if (this_online >= 0 && this_present == -1) this_type = TYPE_MAINS;
333     if (this_online == -1 && this_present >= 0) this_type = TYPE_BATTERY;
334     if (debug)
335       printf(" type absent from uevent %6s guessed %12s %"PRId64"\n",
336              "", "", this_type);
337   }
338
339   int needsfields_MAINS   = this_type == TYPE_MAINS;
340   int needsfields_BATTERY = this_type == TYPE_BATTERY;
341   int needsfields_BOTH    = 1;
342
343   int missing = 0;
344
345 #define V_NEEDED(f,t,...)                               \
346   if (needsfields_##t && this_##f == VAL_NOTFOUND) {    \
347     fprintf(stderr,"%s: %s: not found\n",               \
348             batdirname, #f);                            \
349     missing++;                                          \
350   }
351 ALL_NEEDED_FIELDS(V_NEEDED)
352
353   if (missing) return -1;
354
355   return 0;
356 }   
357
358 /*---------- data collection and analysis ----------*/
359
360 /* These next three variables are the results of the charging state */
361 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
362 static double nondegraded_norm, fill_norm, ratepersec_norm;
363 static int alarmed;
364
365 #define Q_VAR(f,t,...) \
366 static double total_##f;
367   ALL_ACCUMULATE_FIELDS(Q_VAR)
368
369 static void acquiredata(void) {
370   DIR *di = 0;
371   struct dirent *de;
372   int r;
373   
374   charging_mask= 0;
375   alarmed = 0;
376
377   if (debug) printf("\n");
378
379 #define Q_ZERO(f,t,...) \
380   total_##f= 0;
381 ALL_ACCUMULATE_FIELDS(Q_ZERO)
382
383   r = chdir_base();
384   if (r) goto bad;
385
386   di= opendir(".");  if (!di) { batfaile("opendir","battery"); goto bad; }
387   while ((de= readdir(di))) {
388     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
389
390     batdirname= de->d_name;
391     r= readbattery();
392     tidybattery();
393
394     if (r) {
395     bad:
396       charging_mask |= (1u << CHGST_ERROR);
397       break;
398     }
399
400     if (this_type == TYPE_BATTERY) {
401       if (!this_present)
402         continue;
403
404       charging_mask |= 1u << this_state;
405
406 #define QTY_SUPPLIED(f,...)   this_##f != VAL_NOTFOUND &&
407 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
408 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
409
410       double funky_multiplier;
411       if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
412         if (debug) printf(" using energy\n");
413         BAT_QTYS(QTY_USE_ENERGY,,,);
414         funky_multiplier = 1.0;
415       } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
416                  this_voltage != VAL_NOTFOUND) {
417         if (debug) printf(" using charge\n");
418         BAT_QTYS(QTY_USE_CHARGE,,,);
419         funky_multiplier = this_voltage * 1e-6;
420       } else {
421         batfailc("neither complete set of energy nor charge");
422         continue;
423       }
424       if (this_state == CHGST_DISCHARGING)
425         /* negate it */
426         total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
427
428 #define Q_ACCUMULATE_FUNKY(f,...)                       \
429       total_##f += this_##f * funky_multiplier;
430 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
431     }
432
433 #define Q_ACCUMULATE_PLAIN(f,t,...)                     \
434     if (this_type == TYPE_##t)                  \
435       total_##f += this_##f;
436 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
437
438       
439   }
440   if (di) closedir(di);
441
442   if (debug) {
443     printf("TOTAL:\n");
444     printf(" %-30s = %#20x\n", "mask", charging_mask);
445 #define T_PRINT(f,...)                                  \
446     printf(" %-30s = %20.6f\n", #f, total_##f);
447 BAT_QTYS(T_PRINT,,,)
448 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
449   }
450
451   if ((charging_mask & (1u<<CHGST_DISCHARGING)) &&
452       !total_online/*mains*/) {
453     double time_remaining =
454       -total_remaining_capacity * 3600.0 / total_present_rate;
455     if (debug) printf(" %-30s = %20.6f\n", "time remaining", time_remaining);
456     if (time_remaining < alarmlevel)
457       alarmed = 1;
458   }
459
460   if (total_design_capacity < 0.5)
461     total_design_capacity= 1.0;
462
463   if (total_last_full_capacity < total_remaining_capacity)
464     total_last_full_capacity= total_remaining_capacity;
465   if (total_design_capacity < total_last_full_capacity)
466     total_design_capacity= total_last_full_capacity;
467
468   nondegraded_norm= total_last_full_capacity / total_design_capacity;
469   fill_norm= total_remaining_capacity / total_design_capacity;
470   ratepersec_norm=  total_present_rate
471     / (3600.0 * total_design_capacity);
472 }
473
474 static void initacquire(void) {
475 }  
476
477 /*---------- argument parsing ----------*/
478
479 #define COLOURS                                 \
480   C(blue,           discharging)                \
481   C(green,         charging)                    \
482   C(cyan,           charged)                    \
483   C(lightgrey,      notcharging)                \
484   C(grey,           confusing)                  \
485   C(black,          normal)                     \
486   C(red,            low)                        \
487   C(dimgrey,        degraded)                   \
488   C(darkgreen,      absent)                     \
489   C(yellow,         error)                      \
490   C(white,          equilibrium)                \
491   GC(remain)                                    \
492   GC(white)                                     \
493   GC(empty)
494
495 static XrmDatabase xrm;
496 static Display *disp;
497 static int screen;
498 static const char *parentwindow;
499
500 static const char defaultresources[]=
501 #define GC(g)
502 #define C(c,u)                                  \
503   "*" #u "Color: " #c "\n"
504   COLOURS
505 #undef GC
506 #undef C
507   ;
508
509 #define S(s) ((char*)(s))
510 static const XrmOptionDescRec optiontable[]= {
511   { S("-debug"),        S("*debug"),        XrmoptionIsArg },
512   { S("-warningTime"),  S("*warningTime"),  XrmoptionSepArg },
513   { S("-display"),      S("*display"),      XrmoptionSepArg },
514   { S("-geometry"),     S("*geometry"),     XrmoptionSepArg },
515   { S("-into"),         S("*parentWindow"), XrmoptionSepArg },
516   { S("-iconic"),       S("*iconic"),       XrmoptionIsArg },
517   { S("-withdrawn"),    S("*withdrawn"),    XrmoptionIsArg },
518 #define GC(g)
519 #define C(c,u)                                                  \
520   { S("-" #u "Color"),  S("*" #u "Color"),  XrmoptionSepArg },  \
521   { S("-" #u "Colour"), S("*" #u "Color"),  XrmoptionSepArg },
522   COLOURS
523 #undef GC
524 #undef C
525 };
526
527 static const char *getresource(const char *want) {
528   char name_buf[256], class_buf[256];
529   XrmValue val;
530   char *rep_type_dummy;
531   int r;
532
533   assert(strlen(want) < 128);
534
535   sprintf(name_buf,"xbatmon-simple.%s",want);
536   sprintf(class_buf,"Xbatmon-Simple.%s",want);
537   
538   r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
539   if (r) return val.addr;
540
541   sprintf(name_buf,"xacpi-simple.%s",want);
542   sprintf(class_buf,"Xacpi-Simple.%s",want);
543   
544   r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
545   if (r) return val.addr;
546   
547   return 0;
548 }
549
550 static int getresource_bool(const char *want, int def, int *cache) {
551   /* *cache should be initialised to -1 and will be set to !!value
552    * alternatively cache==0 is allowed */
553
554   if (cache && *cache >= 0) return *cache;
555
556   const char *str= getresource(want);
557   int result = def;
558   if (str && str[0]) {
559     char *ep;
560     long l= strtol(str,&ep,0);
561     if (!*ep) {
562       result = l > 0;
563     } else {
564       switch (str[0]) {
565       case 't': case 'T': case 'y': case 'Y':         result= 1;  break;
566       case 'f': case 'F': case 'n': case 'N':         result= 0;  break;
567       case '-': /* option name from XrmoptionIsArg */ result= 1;  break;
568       }
569     }
570   }
571
572   if (cache) *cache= result;
573   return result;
574 }
575
576 static void more_resources(const char *str, const char *why) {
577   XrmDatabase more;
578
579   if (!str) return;
580
581   more= XrmGetStringDatabase((char*)str);
582   if (!more) fail(why);
583   XrmCombineDatabase(more,&xrm,0);
584 }
585
586 static void parseargs(int argc, char **argv) {
587   Screen *screenscreen;
588   
589   XrmInitialize();
590
591   XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
592                   sizeof(optiontable)/sizeof(*optiontable),
593                   program_name, &argc, argv);
594
595   if (argc>1) badusage();
596
597   getresource_bool("debug",0,&debug);
598
599   const char *alarmlevel_string= getresource("alarmLevel");
600   alarmlevel = alarmlevel_string ? atoi(alarmlevel_string) : 300;
601
602   parentwindow = getresource("parentWindow");
603
604   disp= XOpenDisplay(getresource("display"));
605   if (!disp) fail("could not open display");
606
607   screen= DefaultScreen(disp);
608
609   screenscreen= ScreenOfDisplay(disp,screen);
610   if (!screenscreen) fail("screenofdisplay");
611   more_resources(XScreenResourceString(screenscreen), "screen resources");
612   more_resources(XResourceManagerString(disp), "display resources");
613   more_resources(defaultresources, "default resources");
614
615
616 /*---------- display ----------*/
617
618 static Window win;
619 static int width, height;
620 static Colormap cmap;
621 static unsigned long lastbackground;
622
623 typedef struct {
624   GC gc;
625   unsigned long lastfg;
626 } Gcstate;
627
628 #define C(c,u) static unsigned long pix_##u;
629 #define GC(g) static Gcstate gc_##g;
630   COLOURS
631 #undef C
632 #undef GC
633
634 static void refresh(void);
635
636 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
637
638 static void failr(const char *m, int r) {
639   fprintf(stderr,"error: %s (code %d)\n", m, r);
640   exit(-1);
641 }
642
643 static void setbackground(unsigned long newbg) {
644   int r;
645   
646   if (newbg == lastbackground) return;
647   r= XSetWindowBackground(disp,win,newbg);
648   if (!r) fail("XSetWindowBackground");
649   lastbackground= newbg;
650 }
651
652 static void setforeground(Gcstate *g, unsigned long px) {
653   XGCValues gcv;
654   int r;
655   
656   if (g->lastfg == px) return;
657   
658   memset(&gcv,0,sizeof(gcv));
659   g->lastfg= gcv.foreground= px;
660   r= XChangeGC(disp,g->gc,GCForeground,&gcv);
661   if (!r) fail("XChangeGC");
662 }
663
664 static void show_solid(unsigned long px) {
665   setbackground(px);
666   XClearWindow(disp,win);
667 }
668
669 static void show(void) {
670   double elap, then;
671   int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
672
673   if (!charging_mask)
674     return show_solid(pix_absent);
675
676   if (charging_mask & (1u << CHGST_ERROR))
677     return show_solid(pix_error);
678
679   setbackground(pix_degraded);
680   XClearWindow(disp,win);
681   
682   setforeground(&gc_remain,
683                 !(charging_mask & CHGMASK_CHG_DIS) ?
684                 (~charging_mask & (1u << CHGST_CHARGED) ?
685                  pix_notcharging : pix_charged) :
686                 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_confusing :
687                 charging_mask & (1u<<CHGST_CHARGING)
688                 ? pix_charging : pix_discharging);
689                 
690   setforeground(&gc_empty, alarmed ? pix_low : pix_normal);
691
692   for (i=0, first_beyond=1; i<height; i++) {
693     elap= !i ? 0 :
694       height==2 ? BOTTOM :
695       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
696     
697     then= fill_norm + ratepersec_norm * elap;
698
699     beyond=
700       ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
701        (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
702
703     if (then <= 0.0) then= 0.0;
704     else if (then >= nondegraded_norm) then= nondegraded_norm;
705
706     leftmost_lit= width * then;
707     leftmost_nondeg= width * nondegraded_norm;
708
709     if (beyond && first_beyond) {
710       XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
711       first_beyond= 0;
712     } else {
713       if (leftmost_lit < leftmost_nondeg)
714         XDrawLine(disp, win, gc_empty.gc,
715                   leftmost_lit,i, leftmost_nondeg,i);
716       if (leftmost_lit >= 0)
717         XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
718     }
719   }
720 }
721
722 static void initgc(Gcstate *gc_r) {
723   XGCValues gcv;
724
725   memset(&gcv,0,sizeof(gcv));
726   gcv.function= GXcopy;
727   gcv.line_width= 1;
728   gc_r->lastfg= gcv.foreground= pix_equilibrium;
729   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
730 }
731
732 static void colour(unsigned long *pix_r, const char *whichcolour) {
733   XColor xc;
734   const char *name;
735   Status st;
736
737   name= getresource(whichcolour);
738   if (!name) fail("get colour resource");
739   
740   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
741   if (!st) fail(name);
742   
743   *pix_r= xc.pixel;
744 }
745
746 static void initgraphics(int argc, char **argv) {
747   int xwmgr, r;
748   const char *geom_string;
749   XSizeHints *normal_hints;
750   XWMHints *wm_hints;
751   XClassHint *class_hint;
752   int pos_x, pos_y, gravity;
753   char *program_name_silly;
754   
755   program_name_silly= (char*)program_name;
756
757   normal_hints= XAllocSizeHints();
758   wm_hints= XAllocWMHints();
759   class_hint= XAllocClassHint();
760
761   if (!normal_hints || !wm_hints || !class_hint)
762     fail("could not alloc hint(s)");
763
764   geom_string= getresource("geometry");
765
766   xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
767                  normal_hints,
768                  &pos_x, &pos_y,
769                  &width, &height,
770                  &gravity);
771
772   unsigned long parentwindowid;
773   if (parentwindow)
774     parentwindowid = strtoul(parentwindow,0,0);
775   else
776     parentwindowid = DefaultRootWindow(disp);
777
778   win= XCreateSimpleWindow(disp,parentwindowid,
779                            pos_x,pos_y,width,height,0,0,0);
780   cmap= DefaultColormap(disp,screen);
781   
782 #define C(c,u) colour(&pix_##u, #u "Color");
783 #define GC(g) initgc(&gc_##g);
784   COLOURS
785 #undef C
786 #undef GC
787
788   r= XSetWindowBackground(disp,win,pix_degraded);
789   if (!r) fail("init set background");
790   lastbackground= pix_degraded;
791
792   normal_hints->flags= PWinGravity;
793   normal_hints->win_gravity= gravity;
794   normal_hints->x= pos_x;
795   normal_hints->y= pos_y;
796   normal_hints->width= width;
797   normal_hints->height= height;
798   if ((xwmgr & XValue) || (xwmgr & YValue))
799     normal_hints->flags |= USPosition;
800
801   wm_hints->flags= InputHint;
802   wm_hints->input= False;
803   wm_hints->initial_state=
804     (getresource_bool("withdrawn",0,0) ? WithdrawnState :
805      getresource_bool("iconic",0,0) ? IconicState
806      : NormalState);
807
808   class_hint->res_name= program_name_silly;
809   class_hint->res_class= program_name_silly;
810
811   XmbSetWMProperties(disp,win, program_name,program_name,
812                      argv,argc, normal_hints, wm_hints, class_hint);
813
814   XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
815   XMapWindow(disp,win);
816 }
817  
818 static void refresh(void) {
819   acquiredata();
820   show();
821 }
822
823 static void newgeometry(void) {
824   int dummy;
825   Window dummyw;
826   
827   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
828 }
829
830 static void eventloop(void) {
831   XEvent ev;
832   struct pollfd pfd;
833   int r, timeout;
834   
835   newgeometry();
836   refresh();
837
838   for (;;) {
839     XFlush(disp);
840
841     pfd.fd= ConnectionNumber(disp);
842     pfd.events= POLLIN|POLLERR;
843
844     timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
845     r= poll(&pfd,1,timeout);
846     if (r==-1 && errno!=EINTR) failr("poll",errno);
847
848     while (XPending(disp)) {
849       XNextEvent(disp,&ev);
850       if (ev.type == ConfigureNotify) {
851         XConfigureEvent *ce= (void*)&ev;
852         width= ce->width;
853         height= ce->height;
854       }
855     }
856     refresh();
857   }
858 }
859
860 int main(int argc, char **argv) {
861   parseargs(argc,argv);
862   initacquire();
863   initgraphics(argc,argv);
864   eventloop();
865   return 0;
866 }