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