dotfiles

personal configuration files and scripts
git clone https://tongong.net/git/dotfiles.git
Log | Files | Refs | README

backlight-control.c (2111B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <unistd.h>
      5 
      6 /**
      7  * A program to control the backlight brightness.
      8  *
      9  * @author: Hendrik Werner
     10  * modified by tongong
     11  */
     12 
     13 #define MIN_BRIGHTNESS 1
     14 
     15 /* is run after brightness change to update statusbar etc. */
     16 char *notify_cmd[]={"sigdsblocks", "9", NULL};
     17 
     18 #define MAX(a, b) ((a > b) ? a : b)
     19 #define MIN(a, b) ((a < b) ? a : b)
     20 
     21 void print_usage(char *name) {
     22     printf(
     23             "Usage: %1$s [+|-]<value>\n"
     24             "\n"
     25             "Examples:\n"
     26             "\t%1$s +10\n"
     27             "\t%1$s -10\n"
     28             "\t%1$s 50\n"
     29             "\t%1$s get\n",
     30             name
     31           );
     32 }
     33 
     34 FILE *open_file(char *name) {
     35     FILE *file;
     36     if (!(file = fopen(name, "r+"))) {
     37         fprintf(stderr, "failed to open %s\n", name);
     38         exit(EXIT_FAILURE);
     39     }
     40     return file;
     41 }
     42 
     43 unsigned int round_closest(unsigned int dividend, unsigned int divisor)
     44 {
     45     return (dividend + (divisor / 2)) / divisor;
     46 }
     47 
     48 int main(int argc, char **argv) {
     49     if (argc != 2) {
     50         print_usage(argv[0]);
     51         return EXIT_FAILURE;
     52     }
     53 
     54     if (!strcmp(argv[1], "get")) {
     55         int brightness_value;
     56         FILE *brightness = open_file(BRIGHTNESS_FILE);
     57         fscanf(brightness, "%d", &brightness_value);
     58         fclose(brightness);
     59 
     60         printf("%d\n", round_closest(brightness_value * 100, MAX_BRIGHTNESS));
     61         return EXIT_SUCCESS;
     62     }
     63 
     64     int value = strtol(argv[1], NULL, 10);
     65     FILE *brightness = open_file(BRIGHTNESS_FILE);
     66     int brightness_value = MIN_BRIGHTNESS;
     67     switch (argv[1][0]) {
     68         case '+':
     69         case '-':
     70             fscanf(brightness, "%d", &brightness_value);
     71             brightness_value += MAX_BRIGHTNESS * value / 100;
     72             break;
     73         default:
     74             brightness_value = MAX_BRIGHTNESS * value / 100;
     75     }
     76     brightness_value = MIN(brightness_value, MAX_BRIGHTNESS);
     77     brightness_value = MAX(brightness_value, MIN_BRIGHTNESS);
     78     fprintf(brightness, "%d", brightness_value);
     79     fclose(brightness);
     80 
     81     execvp(notify_cmd[0], notify_cmd);
     82     return EXIT_SUCCESS;
     83 }