custom.c (1573B)
1 #include <fcntl.h> 2 3 #define KEYBIND_FN(name) void name(const Arg *a) 4 5 #define CLAMP(x, a, b) ((x) < (a) ? (a) : (x) > (b) ? (b) : (x)) 6 #define CLAMP01(x) CLAMP(x, 0, 1) 7 8 typedef float f32; 9 10 struct backlight_arg { 11 const char *backlight; /* /sys/class/backlight/XXX */ 12 float delta; /* [%] */ 13 }; 14 15 static long 16 read_long(int fd) 17 { 18 char buffer[64]; 19 ptrdiff_t rlen = read(fd, buffer, sizeof(buffer)); 20 close(fd); 21 if (rlen == -1) 22 return 0; 23 if (rlen >= sizeof(buffer)) 24 rlen = sizeof(buffer) - 1; 25 buffer[rlen] = 0; 26 return strtol(buffer, 0, 10); 27 } 28 29 static KEYBIND_FN(backlight) 30 { 31 const struct backlight_arg *ba = a->v; 32 static f32 max_brightness; 33 34 char path[1024]; 35 /* NOTE(rnp): this could simplified using the my stream system */ 36 if (!max_brightness) { 37 snprintf(path, sizeof(path), "/sys/class/backlight/%s/max_brightness", ba->backlight); 38 int fd = open(path, O_RDONLY); 39 if (fd != -1) 40 max_brightness = read_long(fd); 41 } 42 43 long current_brightness; 44 snprintf(path, sizeof(path), "/sys/class/backlight/%s/brightness", ba->backlight); 45 int fd = open(path, O_RDONLY); 46 if (fd != -1) { 47 current_brightness = read_long(fd); 48 close(fd); 49 fd = open(path, O_WRONLY); 50 if (fd != -1 && max_brightness) { 51 f32 current_percent = 100 * current_brightness / max_brightness; 52 current_percent += ba->delta; 53 current_percent = CLAMP(current_percent, 1, 100); 54 current_percent /= 100; 55 long len = snprintf(path, sizeof(path), "%ld\n", 56 (long)(current_percent * max_brightness)); 57 write(fd, path, len); 58 close(fd); 59 } 60 } 61 }