chiark / gitweb /
mcastsoundd wip
[chiark-utils.git] / cprogs / xacpi-simple.c
index 1b80df70dd292bf648ff28e7b8656bee85a8af74..4adbfc12f91bb8da75b608756b25408de4cae6b9 100644 (file)
@@ -10,7 +10,8 @@
  *     green   |  red          |  dimgrey      charging - low
  *     cyan    |  red          |  dimgrey      charged - low [1]
  *     grey    |  red          |  dimgrey      charging&discharching, low [1]
- *       ...  darkmagenta  ...                 no batteries present
+ *       ...  darkgreen  ...                   no batteries present
+ *       ...  yellow  ...                      error
  *
  * [1] battery must be quite badly degraded
  */
 #include <unistd.h>
 #include <ctype.h>
 
+#include <sys/poll.h>
 #include <sys/types.h>
 #include <dirent.h>
 
 #include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <X11/Xresource.h>
+
+#define TOP      60
+#define BOTTOM 3600
+
+#define TIMEOUT         5000 /* milliseconds */
+#define TIMEOUT_ONERROR 3333 /* milliseconds */
+
+static const char program_name[]= "xacpi-simple";
 
 /*---------- general utility stuff and declarations ----------*/
 
@@ -40,6 +52,7 @@ static void badusage(void) { fail("bad usage"); }
 #define CHGST_DISCHARGING 0 /* Reflects order in E(state,charging_state)  */
 #define CHGST_CHARGING    1 /*  in fields table.  Also, much code assumes */
 #define CHGST_CHARGED     2 /*  exactly these three possible states.      */
+#define CHGST_ERROR       8 /* Except that this one is an extra bit.      */
 
 /*---------- structure of and results from /proc/acpi/battery/... ----------*/
 /* variables thisbat_... are the results from readbattery();
@@ -65,14 +78,15 @@ typedef struct batinfo_field {
   QUANTITY_FIELDS
 #undef QF
 
-static unsigned long thisbat_info_present, thisbat_state_present;
-static unsigned long thisbat_state_charging_state;
+static unsigned long thisbat_alarm_present, thisbat_info_present;
+static unsigned long thisbat_state_present, thisbat_state_charging_state;
 
 #define VAL_NOTFOUND (~0UL)
 
 static const batinfo_field fields[]= {
 #define E(f,l)       #f, #l, &thisbat_##f##_##l, 0
 #define QF(f,l,u)  { #f, #l, &thisbat_##f##_##l, u },
+  { E(alarm, present),           { "no", "yes" }                          },
   { E(info, present),            { "no", "yes" }                          },
   { E(state,present),            { "no", "yes" }                          },
   { E(state,charging_state),     { "discharging", "charging", "charged" } },
@@ -156,6 +170,13 @@ static int readbattery(void) { /* 0=>ok, -1=>couldn't */
        return batfailf("line without a colon");
       *colon= 0;
 
+      for (batlinevalue= colon+1;
+          *batlinevalue && isspace((unsigned char)*batlinevalue);
+          batlinevalue++);
+
+      if (!strcmp(batlinebuf,"ERROR"))
+       return batfailf("kernel reports error");
+
       for (p=batlinebuf; p<colon; p++)
        if (*p == ' ')
          *p= '_';
@@ -168,10 +189,6 @@ static int readbattery(void) { /* 0=>ok, -1=>couldn't */
       continue;
 
     label_interesting:
-      for (batlinevalue= colon+1;
-          *batlinevalue && isspace((unsigned char)*batlinevalue);
-          batlinevalue++);
-
       if (field->unit) {
 
        *field->valuep= strtoul(batlinevalue,&ep,10);
@@ -194,21 +211,28 @@ static int readbattery(void) { /* 0=>ok, -1=>couldn't */
     batfile= 0;
   }
 
+  if (!(thisbat_alarm_present==0 ||
+       thisbat_info_present==0 ||
+       thisbat_state_present==0)) {
+    if (thisbat_alarm_present == VAL_NOTFOUND)
+      thisbat_alarm_present= 1;
+    
+    for (field=fields, missing=0;
+        field->file;
+        field++) {
+      if (*field->valuep == VAL_NOTFOUND) {
+       fprintf(stderr,"battery/%s/%s: %s: not found\n",
+               batdirname, field->file,field->label);
+       missing++;
+      }
+    }
+    if (missing) return -1;
+  }
+
   r= chdir("..");
   if (r) return batfaile("chdir","..");
   batdirname= 0;
 
-  for (field=fields, missing=0;
-       field->file;
-       field++) {
-    if (*field->valuep == VAL_NOTFOUND) {
-      fprintf(stderr,"battery/%s/%s: %s: not found\n",
-             batdirname, field->file,field->label);
-      missing++;
-    }
-  }
-  if (missing) return -1;
-
   return 0;
 }   
 
@@ -244,12 +268,10 @@ static void acquiredata(void) {
     r= readbattery();
     tidybattery();
 
-    if (r) continue;
+    if (r) { charging_state_mask |= CHGST_ERROR; continue; }
 
-    if (!thisbat_info_present || !thisbat_state_present) {
-      printf("battery/%s not present\n",de->d_name);
+    if (!thisbat_info_present || !thisbat_state_present)
       continue;
-    }
 
     charging_state_mask |= 1u << thisbat_state_charging_state;
 
@@ -287,28 +309,103 @@ static void initacquire(void) {
   chdir_base();
 }  
 
-/*---------- display ----------*/
-
-#define TOP      60
-#define BOTTOM 3600
+/*---------- argument parsing ----------*/
 
 #define COLOURS                                        \
-  C(dimgrey)                                   \
-  C(blue)                                      \
-  C(black)                                     \
-  C(red)                                       \
-  C(green)                                     \
-  C(cyan)                                      \
-  C(grey)                                      \
-  C(darkmagenta)                                       \
+  C(blue,      discharging)                    \
+  C(green,     charging)                       \
+  C(cyan,      charged)                                \
+  C(grey,      confusing)                      \
+  C(black,     normal)                         \
+  C(red,       low)                            \
+  C(dimgrey,   degraded)                       \
+  C(darkgreen, absent)                         \
+  C(yellow,    error)                          \
+  C(white,     equilibrium)                    \
   GC(remain)                                   \
+  GC(white)                                    \
   GC(empty)
 
+static XrmDatabase xrm;
 static Display *disp;
+static int screen;
+
+static const char defaultresources[]=
+#define GC(g)
+#define C(c,u)                                 \
+  "*" #u "Color: " #c "\n"
+  COLOURS
+#undef GC
+#undef C
+  ;
+
+#define S(s) ((char*)(s))
+static const XrmOptionDescRec optiontable[]= {
+  { S("-display"),      S("*display"),      XrmoptionSepArg },
+  { S("-geometry"),     S("*geometry"),     XrmoptionSepArg },
+#define GC(g)
+#define C(c,u)                                                 \
+  { S("-" #u "Color"),  S("*" #u "Color"),  XrmoptionSepArg }, \
+  { S("-" #u "Colour"), S("*" #u "Color"),  XrmoptionSepArg },
+  COLOURS
+#undef GC
+#undef C
+};
+
+static const char *getresource(const char *want) {
+  char name_buf[256], class_buf[256];
+  XrmValue val;
+  char *rep_type_dummy;
+  int r;
+
+  assert(strlen(want) < 128);
+  sprintf(name_buf,"xacpi-simple.%s",want);
+  sprintf(class_buf,"Xacpi-Simple.%s",want);
+  
+  r= XrmGetResource(xrm, name_buf,class_buf, &rep_type_dummy, &val);
+  if (!r) return 0;
+  
+  return val.addr;
+}
+
+static void more_resources(const char *str, const char *why) {
+  XrmDatabase more;
+
+  if (!str) return;
+
+  more= XrmGetStringDatabase((char*)str);
+  if (!more) fail(why);
+  XrmCombineDatabase(more,&xrm,0);
+}
+
+static void parseargs(int argc, char **argv) {
+  Screen *screenscreen;
+  
+  XrmInitialize();
+
+  XrmParseCommand(&xrm, (XrmOptionDescRec*)optiontable,
+                 sizeof(optiontable)/sizeof(*optiontable),
+                 program_name, &argc, argv);
+
+  if (argc>1) badusage();
+
+  disp= XOpenDisplay(getresource("display"));
+  if (!disp) fail("could not open display");
+
+  screen= DefaultScreen(disp);
+
+  screenscreen= ScreenOfDisplay(disp,screen);
+  if (!screenscreen) fail("screenofdisplay");
+  more_resources(XScreenResourceString(screenscreen), "screen resources");
+  more_resources(XResourceManagerString(disp), "display resources");
+  more_resources(defaultresources, "default resources");
+} 
+
+/*---------- display ----------*/
+
 static Window win;
 static int width, height;
 static Colormap cmap;
-static int screen;
 static unsigned long lastbackground;
 
 typedef struct {
@@ -316,7 +413,7 @@ typedef struct {
   unsigned long lastfg;
 } Gcstate;
 
-#define C(c) static unsigned long pix_##c;
+#define C(c,u) static unsigned long pix_##c;
 #define GC(g) static Gcstate gc_##g;
   COLOURS
 #undef C
@@ -336,7 +433,7 @@ static void setbackground(unsigned long newbg) {
   
   if (newbg == lastbackground) return;
   r= XSetWindowBackground(disp,win,newbg);
-  if (r) failr("XSetWindowBackground",r);
+  if (!r) fail("XSetWindowBackground");
   lastbackground= newbg;
 }
 
@@ -352,15 +449,20 @@ static void setforeground(Gcstate *g, unsigned long px) {
   if (!r) fail("XChangeGC");
 }
 
+static void show_solid(unsigned long px) {
+  setbackground(px);
+  XClearWindow(disp,win);
+}
+
 static void show(void) {
   double elap, then;
-  int i, leftmost_lit, leftmost_nondeg;
+  int i, leftmost_lit, leftmost_nondeg, beyond, first_beyond;
 
-  if (!charging_state_mask) {
-    setbackground(pix_darkmagenta);
-    XClearWindow(disp,win);
-    return;
-  }
+  if (!charging_state_mask)
+    return show_solid(pix_darkgreen);
+
+  if (charging_state_mask & CHGST_ERROR)
+    return show_solid(pix_yellow);
 
   setbackground(pix_dimgrey);
   XClearWindow(disp,win);
@@ -373,23 +475,33 @@ static void show(void) {
                
   setforeground(&gc_empty, alarm_level ? pix_red : pix_black);
 
-  for (i=0; i<height; i++) {
+  for (i=0, first_beyond=1; i<height; i++) {
     elap= !i ? 0 :
       height==2 ? BOTTOM :
       TOP * exp( (double)i / (height-2) * log( (double)BOTTOM/TOP ) );
     
     then= fill_norm + ratepersec_norm * elap;
+
+    beyond=
+      ((charging_state_mask & (1u<<CHGST_DISCHARGING) && then <= 0.0) ||
+       (charging_state_mask & (1u<<CHGST_CHARGING) && then>=nondegraded_norm));
+
     if (then <= 0.0) then= 0.0;
     else if (then >= nondegraded_norm) then= nondegraded_norm;
 
     leftmost_lit= width * then;
     leftmost_nondeg= width * nondegraded_norm;
 
-    if (leftmost_lit < leftmost_nondeg)
-      XDrawLine(disp, win, gc_empty.gc,
-               leftmost_lit,i, leftmost_nondeg,i);
-    if (leftmost_lit >= 0)
-      XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
+    if (beyond && first_beyond) {
+      XDrawLine(disp, win, gc_white.gc, 0,i, leftmost_nondeg,i);
+      first_beyond= 0;
+    } else {
+      if (leftmost_lit < leftmost_nondeg)
+       XDrawLine(disp, win, gc_empty.gc,
+                 leftmost_lit,i, leftmost_nondeg,i);
+      if (leftmost_lit >= 0)
+       XDrawLine(disp, win, gc_remain.gc, 0,i, leftmost_lit,i);
+    }
   }
 }
 
@@ -399,13 +511,17 @@ static void initgc(Gcstate *gc_r) {
   memset(&gcv,0,sizeof(gcv));
   gcv.function= GXcopy;
   gcv.line_width= 1;
-  gc_r->lastfg= gcv.foreground= pix_dimgrey;
+  gc_r->lastfg= gcv.foreground= pix_white;
   gc_r->gc= XCreateGC(disp,win, GCFunction|GCLineWidth|GCForeground, &gcv);
 }
 
-static void colour(unsigned long *pix_r, const char *name) {
+static void colour(unsigned long *pix_r, const char *whichcolour) {
   XColor xc;
+  const char *name;
   Status st;
+
+  name= getresource(whichcolour);
+  if (!name) fail("get colour resource");
   
   st= XAllocNamedColor(disp,cmap,name,&xc,&xc);
   if (!st) fail(name);
@@ -413,16 +529,37 @@ static void colour(unsigned long *pix_r, const char *name) {
   *pix_r= xc.pixel;
 }
 
-static void initgraphics(void) {
-  int r;
+static void initgraphics(int argc, char **argv) {
+  int xwmgr, r;
+  const char *geom_string;
+  XSizeHints *normal_hints;
+  XWMHints *wm_hints;
+  XClassHint *class_hint;
+  int pos_x, pos_y, gravity;
+  char *program_name_silly;
   
-  disp= XOpenDisplay(0); if (!disp) fail("could not open display");
+  program_name_silly= (char*)program_name;
 
-  screen= DefaultScreen(disp);
-  win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),0,0,100,20,0,0,0);
+  normal_hints= XAllocSizeHints();
+  wm_hints= XAllocWMHints();
+  class_hint= XAllocClassHint();
+
+  if (!normal_hints || !wm_hints || !class_hint)
+    fail("could not alloc hint(s)");
+
+  geom_string= getresource("geometry");
+
+  xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
+                normal_hints,
+                &pos_x, &pos_y,
+                &width, &height,
+                &gravity);
+
+  win= XCreateSimpleWindow(disp,DefaultRootWindow(disp),
+                          pos_x,pos_y,width,height,0,0,0);
   cmap= DefaultColormap(disp,screen);
   
-#define C(c) colour(&pix_##c, #c);
+#define C(c,u) colour(&pix_##c, #u "Color");
 #define GC(g) initgc(&gc_##g);
   COLOURS
 #undef C
@@ -432,7 +569,25 @@ static void initgraphics(void) {
   if (!r) fail("init set background");
   lastbackground= pix_dimgrey;
 
-  XSelectInput(disp,win, ExposureMask|VisibilityChangeMask);
+  normal_hints->flags= PWinGravity;
+  normal_hints->win_gravity= gravity;
+  normal_hints->x= pos_x;
+  normal_hints->y= pos_y;
+  normal_hints->width= width;
+  normal_hints->height= height;
+  if ((xwmgr & XValue) || (xwmgr & YValue))
+    normal_hints->flags |= USPosition;
+
+  wm_hints->flags= InputHint;
+  wm_hints->input= False;
+
+  class_hint->res_name= program_name_silly;
+  class_hint->res_class= program_name_silly;
+
+  XmbSetWMProperties(disp,win, program_name,program_name,
+                    argv,argc, normal_hints, wm_hints, class_hint);
+
+  XSelectInput(disp,win, ExposureMask|StructureNotifyMask);
   XMapWindow(disp,win);
 }
  
@@ -446,26 +601,42 @@ static void newgeometry(void) {
   Window dummyw;
   
   XGetGeometry(disp,win, &dummyw,&dummy,&dummy, &width,&height, &dummy,&dummy);
-  refresh();
 }
 
 static void eventloop(void) {
   XEvent ev;
+  struct pollfd pfd;
+  int r, timeout;
   
   newgeometry();
-  
+  refresh();
+
   for (;;) {
-    XNextEvent(disp,&ev);
-    newgeometry();
+    XFlush(disp);
+
+    pfd.fd= ConnectionNumber(disp);
+    pfd.events= POLLIN|POLLERR;
+
+    timeout= !(charging_state_mask & CHGST_ERROR) ? TIMEOUT : TIMEOUT_ONERROR;
+    r= poll(&pfd,1,timeout);
+    if (r==-1 && errno!=EINTR) failr("poll",errno);
+
+    while (XPending(disp)) {
+      XNextEvent(disp,&ev);
+      if (ev.type == ConfigureNotify) {
+       XConfigureEvent *ce= (void*)&ev;
+       width= ce->width;
+       height= ce->height;
+      }
+    }
+    refresh();
   }
 }
 
-int main(int argc, const char *const *argv) {
-  if (!argv[0] || argv[1])
-    badusage();
-
+int main(int argc, char **argv) {
+  parseargs(argc,argv);
   initacquire();
-  initgraphics();
+  initgraphics(argc,argv);
   eventloop();
   return 0;
 }