system76-tools

collection of utilities for system76 laptops
git clone https://git.parazyd.org/system76-tools
Log | Files | Refs | README | LICENSE

brightness.c (1778B)


      1 /* suid tool for setting screen brightness in increments
      2  * GPL-3
      3  */
      4 #include <stdio.h>
      5 #include <string.h>
      6 #include <stdlib.h>
      7 
      8 #include "arg.h"
      9 #include "common.h"
     10 
     11 static const char *BRIGHT_MAX = "/sys/class/backlight/intel_backlight/max_brightness";
     12 static const char *BRIGHT_CUR = "/sys/class/backlight/intel_backlight/brightness";
     13 
     14 char *argv0;
     15 
     16 static void usage(void)
     17 {
     18 	die("usage: %s [-u] [-d] [-z] [-x]\n\n"
     19 	"    -u: brightness up by one increment\n"
     20 	"    -d: brightness down by one increment\n"
     21 	"    -z: brightness to lowest increment\n"
     22 	"    -x: brightness to maximum possible", argv0);
     23 }
     24 
     25 enum Op {
     26 	UP,
     27 	DN,
     28 	MN,
     29 	MX,
     30 };
     31 
     32 int main(int argc, char *argv[])
     33 {
     34 	enum Op op = 0;
     35 	int max, cur, inc;
     36 	int uflag = 0, dflag = 0, minflag = 0, maxflag = 0;
     37 	char buf[10];
     38 	FILE *fd;
     39 
     40 	ARGBEGIN {
     41 	case 'u':
     42 		uflag =1;
     43 		op = UP;
     44 		break;
     45 	case 'd':
     46 		dflag = 1;
     47 		op = DN;
     48 		break;
     49 	case 'z':
     50 		minflag = 1;
     51 		op = MN;
     52 		break;
     53 	case 'x':
     54 		maxflag = 1;
     55 		op = MX;
     56 		break;
     57 	default:
     58 		usage();
     59 	} ARGEND;
     60 
     61 	if ((uflag && dflag) || (maxflag && minflag))
     62 		usage();
     63 
     64 	/* Find out max brightness */
     65 	if ((fd = fopen(BRIGHT_MAX, "r")) == NULL)
     66 		die("Couldn't read %s:", BRIGHT_MAX);
     67 
     68 	max = atoi(fgets(buf, 10, fd));
     69 	fclose(fd);
     70 	fd = NULL;
     71 
     72 	/* Here the number of available increments can be configured */
     73 	inc = max / 20;
     74 
     75 	/* Find out current brightness */
     76 	if ((fd = fopen(BRIGHT_CUR, "w+")) == NULL)
     77 		die("Couldn't open %s for r/w:", BRIGHT_CUR);
     78 
     79 	cur = atoi(fgets(buf, 10, fd));
     80 
     81 	switch(op) {
     82 	case UP:
     83 		fprintf(fd, "%d", cur + inc > max ? max : cur + inc);
     84 		break;
     85 	case DN:
     86 		fprintf(fd, "%d", cur - inc < 1 ? 1 : cur - inc);
     87 		break;
     88 	case MN:
     89 		fprintf(fd, "%d", inc);
     90 		break;
     91 	case MX:
     92 		fprintf(fd, "%d", max);
     93 		break;
     94 	}
     95 
     96 	fclose(fd);
     97 	return 0;
     98 }