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