-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathxbright.c
105 lines (88 loc) · 2.52 KB
/
xbright.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* xbright.c
* author: Alex Kozadaev (2011-Present)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "build_host.h"
#define NAME "xbright"
#define ERROR(msg) { fprintf(stderr, "ERROR: %s - %s\n", __func__, \
(msg)); exit(EXIT_FAILURE); } while(0)
#ifdef DEBUG
#define DBG(fmt, ...) fprintf(stderr, fmt "\n", __VA_ARGS__);
#else
#define DBG(fmt, ...)
#endif
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
const int STEPS = 10;
#define TOSTEPS(a) ((int)((float)a / STEPS))
const int STEP = MAX(TOSTEPS(MAXVALUE), 1);
static void bright_up(const char *);
static void bright_down(const char *);
static void bright_set(const char *);
static int get_current(void);
static void commit_change(int);
static void usage(void);
int main(int argc, char **argv) {
if (geteuid()) {
usage();
ERROR("Must be root");
return 1;
}
if (argc > 1) {
switch (*argv[1]) {
case '+': bright_up(++argv[1]); break;
case '-': bright_down(++argv[1]); break;
case '=': bright_set(++argv[1]); break;
default: usage();
}
} else {
usage();
}
return EXIT_SUCCESS;
}
void bright_up(const char *value) {
int offset_value = MAX(atoi(value), 1);
int cur_value = get_current();
int new_value = MIN(cur_value + (offset_value * STEP), MAXVALUE);
if (new_value != cur_value) {
commit_change(new_value);
}
}
void bright_down(const char *value) {
int offset_value = MAX(atoi(value), 1);
int cur_value = get_current();
int new_value = MAX(cur_value - (offset_value * STEP), 0);
if (new_value != cur_value) {
commit_change(new_value);
}
}
void bright_set(const char *value) {
int set_value = MIN(atoi(value), STEPS);
commit_change(set_value * STEP);
}
int get_current(void) {
int value = 0;
FILE *input = fopen(BRIGHTNESSFILE, "r");
if (input == NULL) {
ERROR("Cannot open kernel pipe");
}
(void)fscanf(input, "%d", &value);
DBG("current value: %d", value);
return value;
}
void commit_change(int value) {
FILE *output = fopen(BRIGHTNESSFILE, "w");
if (output == NULL) {
ERROR("Cannot open kernel pipe");
}
DBG("new value: %d", value);
fprintf(output, "%d", value);
fclose(output);
}
void usage(void) {
printf("%s v%s (works only with 2.6+ kernels).\n", NAME, VERSION);
printf("usage: %s [+-=[0-%d]]\n", NAME, STEPS);
}