chiark / gitweb /
remove parse_separate, which we may want to put back later
[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;
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_uevent(const fileinfo *cfile) {
264   char *equals= strchr(batlinebuf,'=');
265   if (!equals)
266     return batfailf("line without a equals");
267   *equals= 0;
268   batlinevalue = equals+1;
269
270   const batinfo_field *field;
271   for (field=cfile->extra; field->label; field++) {
272     if (!strcmp(field->label,batlinebuf))
273       goto found;
274   }
275   return 0;
276
277  found:
278   return parse_value(cfile, field);
279 }
280
281 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
282   
283   const fileinfo *cfile;
284   char *sr;
285   int r, l;
286   
287   r= chdir_base();
288   if (r) return r;
289
290   r= chdir(batdirname);
291   if (r) return batfaile("chdir",batdirname);
292
293 #define V_NOTFOUND(f,...) \
294   this_##f = VAL_NOTFOUND;
295 ALL_VARS(V_NOTFOUND)
296
297   for (cfile=files;
298        (batfilename= cfile->filename);
299        cfile++) {
300     batfile= fopen(batfilename,"r");
301     if (!batfile) {
302       if (errno == ENOENT) continue;
303       return batfaile("open",batfilename);
304     }
305
306     for (;;) {
307       batlinevalue= 0;
308       
309       sr= fgets(batlinebuf,sizeof(batlinebuf),batfile);
310       if (ferror(batfile)) return batfaile("read",batfilename);
311       if (!sr && feof(batfile)) break;
312       l= strlen(batlinebuf);
313       assert(l>0);
314       if (batlinebuf[l-1] != '\n')
315         return batfailf("line too long");
316       batlinebuf[l-1]= 0;
317
318       if (cfile->parse(cfile))
319         return -1;
320     }
321
322     fclose(batfile);
323     batfile= 0;
324   }
325
326   if (debug) {
327     printf("%s:\n",batdirname);
328 #define V_PRINT(f,...)                                  \
329     printf(" %-30s = %20"PRId64"\n", #f, (int64_t)this_##f);
330 ALL_DIRECT_VARS(V_PRINT)
331   }
332
333   int needsfields_MAINS   = this_type == TYPE_MAINS;
334   int needsfields_BATTERY = this_type == TYPE_BATTERY;
335   int needsfields_BOTH    = 1;
336
337   int missing = 0;
338
339 #define V_NEEDED(f,t,...)                               \
340   if (needsfields_##t && this_##f == VAL_NOTFOUND) {    \
341     fprintf(stderr,"%s: %s: not found\n",               \
342             batdirname, #f);                            \
343     missing++;                                          \
344   }
345 ALL_NEEDED_FIELDS(V_NEEDED)
346
347   if (missing) return -1;
348
349   return 0;
350 }   
351
352 /*---------- data collection and analysis ----------*/
353
354 /* These next three variables are the results of the charging state */
355 static unsigned charging_mask; /* 1u<<CHGST_* | ... */
356 static double nondegraded_norm, fill_norm, ratepersec_norm;
357 static int alarm_level; /* 0=ok, 1=low */
358
359 #define Q_VAR(f,t,...) \
360 static double total_##f;
361   ALL_ACCUMULATE_FIELDS(Q_VAR)
362
363 static void acquiredata(void) {
364   DIR *di;
365   struct dirent *de;
366   int r;
367   
368   charging_mask= 0;
369
370 #define Q_ZERO(f,t,...) \
371   total_##f= 0;
372 ALL_ACCUMULATE_FIELDS(Q_ZERO)
373
374   r = chdir_base();
375   if (r) goto bad;
376
377   di= opendir(".");  if (!di) { batfaile("opendir","battery"); goto bad; }
378   while ((de= readdir(di))) {
379     if (de->d_name[0]==0 || de->d_name[0]=='.') continue;
380
381     batdirname= de->d_name;
382     r= readbattery();
383     tidybattery();
384
385     if (r) {
386     bad:
387       charging_mask |= (1u << CHGST_ERROR);
388       break;
389     }
390
391     if (this_type == TYPE_BATTERY) {
392       if (!this_present)
393         continue;
394
395       charging_mask |= 1u << this_state;
396
397 #define QTY_SUPPLIED(f,...)   this_##f != VAL_NOTFOUND &&
398 #define QTY_USE_ENERGY(f,...) this_##f = this_##f##_energy;
399 #define QTY_USE_CHARGE(f,...) this_##f = this_##f##_charge;
400
401       double funky_multiplier;
402       if (BAT_QTYS(QTY_SUPPLIED,_energy,,) 1) {
403         if (debug) printf(" using energy\n");
404         BAT_QTYS(QTY_USE_ENERGY,,,);
405         funky_multiplier = 1.0;
406       } else if (BAT_QTYS(QTY_SUPPLIED,_charge,,)
407                  this_voltage != VAL_NOTFOUND) {
408         if (debug) printf(" using charge\n");
409         BAT_QTYS(QTY_USE_CHARGE,,,);
410         funky_multiplier = this_voltage * 1e-6;
411       } else {
412         batfailc("neither complete set of energy nor charge");
413         continue;
414       }
415       if (this_state == CHGST_DISCHARGING)
416         /* negate it */
417         total_present_rate -= 2.0 * this_present_rate * funky_multiplier;
418
419 #define Q_ACCUMULATE_FUNKY(f,...)                       \
420       total_##f += this_##f * funky_multiplier;
421 BAT_QTYS(Q_ACCUMULATE_FUNKY,,,)
422     }
423
424 #define Q_ACCUMULATE_PLAIN(f,t,...)                     \
425     if (this_type == TYPE_##t)                  \
426       total_##f += this_##f;
427 ALL_PLAIN_ACCUMULATE_FIELDS(Q_ACCUMULATE_PLAIN)
428
429       
430   }
431   closedir(di);
432
433   printf("TOTAL:\n");
434 #define T_PRINT(f,...)                                  \
435     printf(" %-30s = %20.6f\n", #f, total_##f);
436 BAT_QTYS(T_PRINT,,,)
437 ALL_PLAIN_ACCUMULATE_FIELDS(T_PRINT)
438
439   if (total_design_capacity < 0.5)
440     total_design_capacity= 1.0;
441
442   if (total_last_full_capacity < total_remaining_capacity)
443     total_last_full_capacity= total_remaining_capacity;
444   if (total_design_capacity < total_last_full_capacity)
445     total_design_capacity= total_last_full_capacity;
446
447   alarm_level= total_alarm && (charging_mask & 1u << CHGST_DISCHARGING);
448
449   nondegraded_norm= total_last_full_capacity / total_design_capacity;
450   fill_norm= total_remaining_capacity / total_design_capacity;
451   ratepersec_norm=  total_present_rate
452     / (3600.0 * total_design_capacity);
453 }
454
455 static void initacquire(void) {
456 }  
457
458 /*---------- argument parsing ----------*/
459
460 #define COLOURS                                 \
461   C(blue,      discharging)                     \
462   C(green,     charging)                        \
463   C(cyan,      charged)                         \
464   C(darkcyan,  notcharging)                     \
465   C(grey,      confusing)                       \
466   C(black,     normal)                          \
467   C(red,       low)                             \
468   C(dimgrey,   degraded)                        \
469   C(darkgreen, absent)                          \
470   C(yellow,    error)                           \
471   C(white,     equilibrium)                     \
472   GC(remain)                                    \
473   GC(white)                                     \
474   GC(empty)
475
476 static XrmDatabase xrm;
477 static Display *disp;
478 static int screen;
479
480 static const char defaultresources[]=
481 #define GC(g)
482 #define C(c,u)                                  \
483   "*" #u "Color: " #c "\n"
484   COLOURS
485 #undef GC
486 #undef C
487   ;
488
489 #define S(s) ((char*)(s))
490 static const XrmOptionDescRec optiontable[]= {
491   { S("-debug"),        S("*debug"),        XrmoptionIsArg },
492   { S("-display"),      S("*display"),      XrmoptionSepArg },
493   { S("-geometry"),     S("*geometry"),     XrmoptionSepArg },
494 #define GC(g)
495 #define C(c,u)                                                  \
496   { S("-" #u "Color"),  S("*" #u "Color"),  XrmoptionSepArg },  \
497   { S("-" #u "Colour"), S("*" #u "Color"),  XrmoptionSepArg },
498   COLOURS
499 #undef GC
500 #undef C
501 };
502
503 static const char *getresource(const char *want) {
504   char name_buf[256], class_buf[256];
505   XrmValue val;
506   char *rep_type_dummy;
507   int r;
508
509   assert(strlen(want) < 128);
510   sprintf(name_buf,"xacpi-simple.%s",want);
511   sprintf(class_buf,"Xacpi-Simple.%s",want);
512   
513   r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
514   if (!r) return 0;
515   
516   return val.addr;
517 }
518
519 static void more_resources(const char *str, const char *why) {
520   XrmDatabase more;
521
522   if (!str) return;
523
524   more= XrmGetStringDatabase((char*)str);
525   if (!more) fail(why);
526   XrmCombineDatabase(more,&xrm,0);
527 }
528
529 static void parseargs(int argc, char **argv) {
530   Screen *screenscreen;
531   
532   XrmInitialize();
533
534   XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
535                   sizeof(optiontable)/sizeof(*optiontable),
536                   program_name, &argc, argv);
537
538   if (argc>1) badusage();
539
540   debug= !!getresource("debug");
541
542   disp= XOpenDisplay(getresource("display"));
543   if (!disp) fail("could not open display");
544
545   screen= DefaultScreen(disp);
546
547   screenscreen= ScreenOfDisplay(disp,screen);
548   if (!screenscreen) fail("screenofdisplay");
549   more_resources(XScreenResourceString(screenscreen), "screen resources");
550   more_resources(XResourceManagerString(disp), "display resources");
551   more_resources(defaultresources, "default resources");
552
553
554 /*---------- display ----------*/
555
556 static Window win;
557 static int width, height;
558 static Colormap cmap;
559 static unsigned long lastbackground;
560
561 typedef struct {
562   GC gc;
563   unsigned long lastfg;
564 } Gcstate;
565
566 #define C(c,u) static unsigned long pix_##c;
567 #define GC(g) static Gcstate gc_##g;
568   COLOURS
569 #undef C
570 #undef GC
571
572 static void refresh(void);
573
574 #define CHGMASK_CHG_DIS ((1u<<CHGST_CHARGING) | (1u<<CHGST_DISCHARGING))
575
576 static void failr(const char *m, int r) {
577   fprintf(stderr,"error: %s (code %d)\n", m, r);
578   exit(-1);
579 }
580
581 static void setbackground(unsigned long newbg) {
582   int r;
583   
584   if (newbg == lastbackground) return;
585   r= XSetWindowBackground(disp,win,newbg);
586   if (!r) fail("XSetWindowBackground");
587   lastbackground= newbg;
588 }
589
590 static void setforeground(Gcstate *g, unsigned long px) {
591   XGCValues gcv;
592   int r;
593   
594   if (g->lastfg == px) return;
595   
596   memset(&gcv,0,sizeof(gcv));
597   g->lastfg= gcv.foreground= px;
598   r= XChangeGC(disp,g->gc,GCForeground,&gcv);
599   if (!r) fail("XChangeGC");
600 }
601
602 static void show_solid(unsigned long px) {
603   setbackground(px);
604   XClearWindow(disp,win);
605 }
606
607 static void show(void) {
608   double elap, then;
609   int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
610
611   if (!charging_mask)
612     return show_solid(pix_darkgreen);
613
614   if (charging_mask & (1u << CHGST_ERROR))
615     return show_solid(pix_yellow);
616
617   setbackground(pix_dimgrey);
618   XClearWindow(disp,win);
619   
620   setforeground(&gc_remain,
621                 !(charging_mask & CHGMASK_CHG_DIS) ?
622                 (~charging_mask & (1u << CHGST_CHARGED) ?
623                  pix_darkcyan : pix_cyan) :
624                 !(~charging_mask & CHGMASK_CHG_DIS) ? pix_grey :
625                 charging_mask & (1u<<CHGST_CHARGING)
626                 ? pix_green : pix_blue);
627                 
628   setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
629
630   for (i=0, first_beyond=1; i<height; i++) {
631     elap= !i ? 0 :
632       height==2 ? BOTTOM :
633       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
634     
635     then= fill_norm + ratepersec_norm * elap;
636
637     beyond=
638       ((charging_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
639        (charging_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
640
641     if (then <= 0.0) then= 0.0;
642     else if (then >= nondegraded_norm) then= nondegraded_norm;
643
644     leftmost_lit= width * then;
645     leftmost_nondeg= width * nondegraded_norm;
646
647     if (beyond && first_beyond) {
648       XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
649       first_beyond= 0;
650     } else {
651       if (leftmost_lit < leftmost_nondeg)
652         XDrawLine(disp, win, gc_empty.gc,
653                   leftmost_lit,i, leftmost_nondeg,i);
654       if (leftmost_lit >= 0)
655         XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
656     }
657   }
658 }
659
660 static void initgc(Gcstate *gc_r) {
661   XGCValues gcv;
662
663   memset(&gcv,0,sizeof(gcv));
664   gcv.function= GXcopy;
665   gcv.line_width= 1;
666   gc_r->lastfg= gcv.foreground= pix_white;
667   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
668 }
669
670 static void colour(unsigned long *pix_r, const char *whichcolour) {
671   XColor xc;
672   const char *name;
673   Status st;
674
675   name= getresource(whichcolour);
676   if (!name) fail("get colour resource");
677   
678   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
679   if (!st) fail(name);
680   
681   *pix_r= xc.pixel;
682 }
683
684 static void initgraphics(int argc, char **argv) {
685   int xwmgr, r;
686   const char *geom_string;
687   XSizeHints *normal_hints;
688   XWMHints *wm_hints;
689   XClassHint *class_hint;
690   int pos_x, pos_y, gravity;
691   char *program_name_silly;
692   
693   program_name_silly= (char*)program_name;
694
695   normal_hints= XAllocSizeHints();
696   wm_hints= XAllocWMHints();
697   class_hint= XAllocClassHint();
698
699   if (!normal_hints || !wm_hints || !class_hint)
700     fail("could not alloc hint(s)");
701
702   geom_string= getresource("geometry");
703
704   xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
705                  normal_hints,
706                  &pos_x, &pos_y,
707                  &width, &height,
708                  &gravity);
709
710   win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
711                            pos_x,pos_y,width,height,0,0,0);
712   cmap= DefaultColormap(disp,screen);
713   
714 #define C(c,u) colour(&pix_##c, #u "Color");
715 #define GC(g) initgc(&gc_##g);
716   COLOURS
717 #undef C
718 #undef GC
719
720   r= XSetWindowBackground(disp,win,pix_dimgrey);
721   if (!r) fail("init set background");
722   lastbackground= pix_dimgrey;
723
724   normal_hints->flags= PWinGravity;
725   normal_hints->win_gravity= gravity;
726   normal_hints->x= pos_x;
727   normal_hints->y= pos_y;
728   normal_hints->width= width;
729   normal_hints->height= height;
730   if ((xwmgr & XValue) || (xwmgr & YValue))
731     normal_hints->flags |= USPosition;
732
733   wm_hints->flags= InputHint;
734   wm_hints->input= False;
735
736   class_hint->res_name= program_name_silly;
737   class_hint->res_class= program_name_silly;
738
739   XmbSetWMProperties(disp,win, program_name,program_name,
740                      argv,argc, normal_hints, wm_hints, class_hint);
741
742   XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
743   XMapWindow(disp,win);
744 }
745  
746 static void refresh(void) {
747   acquiredata();
748   show();
749 }
750
751 static void newgeometry(void) {
752   int dummy;
753   unsigned int udummy, gotwidth, gotheight;
754   Window dummyw;
755   
756   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &gotwidth,&gotheight,
757                &udummy,&udummy);
758   assert(gotwidth < INT_MAX);
759   assert(gotheight < INT_MAX);
760   width = gotwidth;
761   height = gotheight;
762 }
763
764 static void eventloop(void) {
765   XEvent ev;
766   struct pollfd pfd;
767   int r, timeout;
768   
769   newgeometry();
770   refresh();
771
772   for (;;) {
773     XFlush(disp);
774
775     pfd.fd= ConnectionNumber(disp);
776     pfd.events= POLLIN|POLLERR;
777
778     timeout= !(charging_mask & (1u << CHGST_ERROR)) ? TIMEOUT : TIMEOUT_ONERROR;
779     r= poll(&pfd,1,timeout);
780     if (r==-1 && errno!=EINTR) failr("poll",errno);
781
782     while (XPending(disp)) {
783       XNextEvent(disp,&ev);
784       if (ev.type == ConfigureNotify) {
785         XConfigureEvent *ce= (void*)&ev;
786         width= ce->width;
787         height= ce->height;
788       }
789     }
790     refresh();
791   }
792 }
793
794 int main(int argc, char **argv) {
795   parseargs(argc,argv);
796   initacquire();
797   initgraphics(argc,argv);
798   eventloop();
799   return 0;
800 }