chiark / gitweb /
wip
[chiark-utils.git] / cprogs / xacpi-simple.c
index 157ed59356d46b6b08bbba65c60312a6cfbc9d24..cd2a1c7f37f34a8633b211aae674eea68485991a 100644 (file)
  *     cyan    |  red          |  dimgrey      charged - low [1]
  *     grey    |  red          |  dimgrey      charging&discharching, low [1]
  *       ...  darkgreen  ...                   no batteries present
+ *       ...  yellow  ...                      error
  *
  * [1] battery must be quite badly degraded
  */
+/*
+ * Copyright (C) 2004 Ian Jackson <ian@davenant.greenend.org.uk>
+ *
+ * This is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation; either version 3,
+ * or (at your option) any later version.
+ *
+ * This is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public
+ * License along with this file; if not, consult the Free Software
+ * Foundation's website at www.fsf.org, or the GNU Project website at
+ * www.gnu.org.
+ */
 
 #include <stdio.h>
 #include <assert.h>
@@ -23,6 +42,7 @@
 #include <errno.h>
 #include <unistd.h>
 #include <ctype.h>
+#include <stdint.h>
 
 #include <sys/poll.h>
 #include <sys/types.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         5000 /* milliseconds */
+#define TIMEOUT_ONERROR 3333 /* milliseconds */
 
 static const char program_name[]= "xacpi-simple";
 
@@ -46,54 +68,66 @@ static void fail(const char *m) {
 }
 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.      */
+typedef struct fileinfo fileinfo;
+struct fileinfo {
+  const char *filename;
+  void (*parse)(const fileinfo*);
+  const void *extra;
+};
 
-/*---------- structure of and results from /proc/acpi/battery/... ----------*/
+/*---------- structure of and results from /sys/class/power/... ----------*/
 /* variables thisbat_... are the results from readbattery();
  * if readbattery() succeeds they are all valid and not VAL_NOTFOUND
  */
 
 typedef struct batinfo_field {
-  const char *file;
   const char *label;
-  unsigned long *valuep;
-  const char *unit;
+  uint64_t *valuep;
   const char *enumarray[10];
 } batinfo_field;
 
-#define QUANTITY_FIELDS                                \
-  QF(info,  design_capacity,    "mWh")         \
-  QF(info,  last_full_capacity, "mWh")         \
-  QF(state, present_rate,       "mW")          \
-  QF(state, remaining_capacity, "mWh")         \
-  QF(alarm, alarm,              "mWh")
-
-#define QF(f,l,u) static unsigned long thisbat_##f##_##l;
-  QUANTITY_FIELDS
-#undef QF
-
-static unsigned long thisbat_alarm_present, thisbat_info_present;
-static unsigned long thisbat_state_present, thisbat_state_charging_state;
+#define UEVENT_QUANTITY_FIELDS(q)                              \
+  q(design_capacity,    CHARGE_FULL_DESIGN ) /* uAh */         \
+  q(last_full_capacity, CHARGE_FULL        ) /* uAh */         \
+  q(present_rate,       CURRENT_NOW        ) /* uA  */         \
+  q(remaining_capacity, CHARGE_NOW         ) /* uAh */         \
+  q(present,            PRESENT            ) /* boolean */     \
+  q(online,             ONLINE             ) /* boolean */
+
+#define UEVENT_ENUM_FIELDS(e)                                  \
+  e(type,    TYPE,    "Battery",     "Mains"                 ) \
+  e(state,   STATUS,  "Discharging", "Charging", "Charged"   )
+
+#define CHGST_DISCHARGING 0 /* Reflects order in e(state,...) above     */
+#define CHGST_CHARGING    1 /*  Also, much code assumes exadtly         */
+#define CHGST_CHARGED     2 /*  these three possible states.            */
+#define CHGST_ERROR       8 /* Except that this one is an extra bit.    */
+
+#define Q_FLD(f,l)        { "POWER_SUPPLY_" #l, &thisbat_##f },
+#define E_FLD(f,l,vl...)  { "POWER_SUPPLY_" #l, &thisbat_##f, { vl } },
+
+#define ALL_FIELDS(i)                          \
+  UEVENT_QUANTITY_FIELDS(i)                    \
+  UEVENT_ENUM_FIELDS(i)                                \
+  i(thisbat_alarm)
+
+#define F_VAR(f,...) static uint64_t thisbat_##f;
+  ALL_FIELDS(F_VAR)
+
+static const batinfo_field uevent_fields[]= {
+  UEVENT_QUANTITY_FIELDS(Q_FLD)
+  UEVENT_ENUM_FIELDS(E_FLD)
+  { 0 }
+};
 
 #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" } },
-  QUANTITY_FIELDS           /* take care re charging_state values order -  */
-  { 0 }                     /* if you must change it, search for CHGST_... */
-#undef E
-#undef QF
+static const fileinfo files[]= {
+  { "uevent",  parse_fields,  uevent_fields },
+  { "alarm",   parse_boolean, &thisbat_alarm },
+  { 0 }
 };
 
-static const char *files[]= { "info", "state", "alarm" };
-
 /*---------- parsing of one battery in /proc/acpi/battery/... ----------*/
 
 /* variables private to the parser and its error handlers */
@@ -123,8 +157,8 @@ static int batfaile(const char *syscall, const char *target) {
 static void chdir_base(void) {
   int r;
   
-  r= chdir("/proc/acpi/battery");
-  if (r) batfaile("chdir","/proc/acpi/battery");
+  r= chdir("/sys/class/power_supply");
+  if (r) batfaile("chdir","/sys/class/power_supply");
 }
 
 static void tidybattery(void) {
@@ -132,21 +166,55 @@ static void tidybattery(void) {
   if (batdirname) { chdir_base(); batdirname=0; }
 }
 
+static void parse_fields(const fileinfo *cfile, char *batlinebuf) {
+  equals= strchr(batlinebuf,'=');
+  if (!equals)
+    return batfailf("line without a equals");
+  *equals++= 0;
+
+  for (field=fields; field->file; field++) {
+    if (!strcmp(field->label,batlinebuf))
+      goto found;
+  }
+  return;
+
+ found:
+  if (!field->enumarray[0]) {
+
+    *field->valuep= strtoull(equals,&ep,10);
+    if (*ep)
+      batfailf("value number syntax incorrect");
+
+  } else {
+       
+    for (*field->valuep=0, enumsearch=field->enumarray;
+        *enumsearch && strcmp(*enumsearch,equals);
+        (*field->valuep)++, enumsearch++);
+    if (!*enumsearch)
+      batfailf("unknown enum value");
+
+  }
+}
+
 static int readbattery(void) { /* 0=>ok, -1=>couldn't */
   const batinfo_field *field;
-  const char *const *cfilename, *const *enumsearch;
+  const fileinfo *cfile;
+  const char *const *enumsearch;
   char *colon, *ep, *sr, *p;
   int r, l, missing;
   
   r= chdir(batdirname);
   if (r) return batfaile("chdir",batdirname);
 
+#define V_NOTFOUND(f,...) thisbat_##f = VAL_NOTFOUND;
+  ALL_FIELDS(V_NOTFOUND)
+  
   for (field=fields; field->file; field++)
     *field->valuep= VAL_NOTFOUND;
 
-  for (cfilename=files;
-       (batfilename= *cfilename);
-       cfilename++) {
+  for (cfile=files;
+       (batfilename= cfile->filename);
+       cfile++++) {
     batfile= fopen(batfilename,"r");
     if (!batfile) return batfaile("open",batfilename);
 
@@ -161,43 +229,8 @@ static int readbattery(void) { /* 0=>ok, -1=>couldn't */
       if (batlinebuf[l-1] != '\n')
        return batfailf("line too long");
       batlinebuf[l-1]= 0;
-      colon= strchr(batlinebuf,':');
-      if (!colon)
-       return batfailf("line without a colon");
-      *colon= 0;
-
-      for (p=batlinebuf; p<colon; p++)
-       if (*p == ' ')
-         *p= '_';
-
-      for (field=fields; field->file; field++) {
-       if (!strcmp(field->file,batfilename) &&
-           !strcmp(field->label,batlinebuf))
-         goto label_interesting;
-      }
-      continue;
-
-    label_interesting:
-      for (batlinevalue= colon+1;
-          *batlinevalue && isspace((unsigned char)*batlinevalue);
-          batlinevalue++);
-
-      if (field->unit) {
-
-       *field->valuep= strtoul(batlinevalue,&ep,10);
-       if (ep==batlinevalue || *ep!=' ')
-         batfailf("value number syntax incorrect");
-       if (strcmp(ep+1,field->unit)) batfailf("incorrect unit");
 
-      } else {
-       
-       for (*field->valuep=0, enumsearch=field->enumarray;
-            *enumsearch && strcmp(*enumsearch,batlinevalue);
-            (*field->valuep)++, enumsearch++);
-       if (!*enumsearch)
-         batfailf("unknown enum value");
-
-      }
+      cfile->parse(cfile, batlinebuf);
     }
 
     fclose(batfile);
@@ -205,8 +238,7 @@ static int readbattery(void) { /* 0=>ok, -1=>couldn't */
   }
 
   if (!(thisbat_alarm_present==0 ||
-       thisbat_info_present==0 ||
-       thisbat_state_present==0)) {
+       thisbat_state_present==0 || thisbat_info_present==0)) {
     if (thisbat_alarm_present == VAL_NOTFOUND)
       thisbat_alarm_present= 1;
     
@@ -261,7 +293,7 @@ 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)
       continue;
@@ -302,27 +334,103 @@ static void initacquire(void) {
   chdir_base();
 }  
 
-/*---------- display ----------*/
+/*---------- argument parsing ----------*/
 
 #define COLOURS                                        \
-  C(dimgrey)                                   \
-  C(blue)                                      \
-  C(black)                                     \
-  C(red)                                       \
-  C(green)                                     \
-  C(cyan)                                      \
-  C(grey)                                      \
-  C(darkgreen)                                 \
-  C(white)                                     \
+  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 {
@@ -330,7 +438,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
@@ -366,15 +474,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, beyond, first_beyond;
 
-  if (!charging_state_mask) {
-    setbackground(pix_darkgreen);
-    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);
@@ -427,9 +540,13 @@ static void initgc(Gcstate *gc_r) {
   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);
@@ -438,8 +555,7 @@ static void colour(unsigned long *pix_r, const char *name) {
 }
 
 static void initgraphics(int argc, char **argv) {
-  int r;
-  XTextProperty tp;
+  int xwmgr, r;
   const char *geom_string;
   XSizeHints *normal_hints;
   XWMHints *wm_hints;
@@ -449,11 +565,6 @@ static void initgraphics(int argc, char **argv) {
   
   program_name_silly= (char*)program_name;
 
-  disp= XOpenDisplay(0);
-  if (!disp) fail("could not open display");
-
-  screen= DefaultScreen(disp);
-
   normal_hints= XAllocSizeHints();
   wm_hints= XAllocWMHints();
   class_hint= XAllocClassHint();
@@ -461,9 +572,9 @@ static void initgraphics(int argc, char **argv) {
   if (!normal_hints || !wm_hints || !class_hint)
     fail("could not alloc hint(s)");
 
-  geom_string= argc>=2 ? argv[1] : 0;
+  geom_string= getresource("geometry");
 
-  r= XWMGeometry(disp,screen, geom_string,"128x32", 0,
+  xwmgr= XWMGeometry(disp,screen, geom_string,"128x32", 0,
                 normal_hints,
                 &pos_x, &pos_y,
                 &width, &height,
@@ -473,7 +584,7 @@ static void initgraphics(int argc, char **argv) {
                           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
@@ -485,6 +596,12 @@ static void initgraphics(int argc, char **argv) {
 
   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;
@@ -492,9 +609,6 @@ static void initgraphics(int argc, char **argv) {
   class_hint->res_name= program_name_silly;
   class_hint->res_class= program_name_silly;
 
-  /*r= XStringListToTextProperty(&program_name_silly, 1, &tp);
-    if (!r) fail("XStringListtoTextProperty");*/
-
   XmbSetWMProperties(disp,win, program_name,program_name,
                     argv,argc, normal_hints, wm_hints, class_hint);
 
@@ -517,7 +631,7 @@ static void newgeometry(void) {
 static void eventloop(void) {
   XEvent ev;
   struct pollfd pfd;
-  int r;
+  int r, timeout;
   
   newgeometry();
   refresh();
@@ -528,7 +642,8 @@ static void eventloop(void) {
     pfd.fd= ConnectionNumber(disp);
     pfd.events= POLLIN|POLLERR;
 
-    r= poll(&pfd,1,TIMEOUT);
+    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)) {
@@ -544,9 +659,7 @@ static void eventloop(void) {
 }
 
 int main(int argc, char **argv) {
-  if (argc<1 || argc>2)
-    badusage();
-
+  parseargs(argc,argv);
   initacquire();
   initgraphics(argc,argv);
   eventloop();