Skip to content

Commit 97e0c4c

Browse files
committed
Support parsing fractional percentages
1 parent e70bc55 commit 97e0c4c

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

brightnessctl.c

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,10 @@ enum delta_type { DIRECT, DELTA };
8080
enum sign { PLUS, MINUS };
8181

8282
struct value {
83-
unsigned long val;
83+
union {
84+
unsigned long val;
85+
float percentage;
86+
};
8487
enum value_type v_type;
8588
enum delta_type d_type;
8689
enum sign sign;
@@ -311,7 +314,7 @@ int apply_operation(struct device *dev, enum operation operation, struct value *
311314
}
312315

313316
bool parse_value(struct value *val, char *str) {
314-
long n;
317+
double n;
315318
char c;
316319
char *buf;
317320
errno = 0;
@@ -325,10 +328,9 @@ bool parse_value(struct value *val, char *str) {
325328
val->d_type = DELTA;
326329
str++;
327330
}
328-
n = strtol(str, &buf, 10);
331+
n = strtod(str, &buf);
329332
if (errno || buf == str)
330333
return false;
331-
val->val = labs(n) % LONG_MAX;
332334
while ((c = *(buf++))) switch(c) {
333335
case '+':
334336
val->sign = PLUS;
@@ -342,6 +344,11 @@ bool parse_value(struct value *val, char *str) {
342344
val->v_type = RELATIVE;
343345
break;
344346
}
347+
if (val->v_type == RELATIVE) {
348+
val->percentage = n;
349+
} else {
350+
val->val = labs((long) n) % LONG_MAX;
351+
}
345352
return true;
346353
}
347354

@@ -386,21 +393,22 @@ void print_device(struct device *dev) {
386393
unsigned int calc_value(struct device *d, struct value *val) {
387394
long new = d->curr_brightness;
388395
if (val->d_type == DIRECT) {
389-
new = val->v_type == ABSOLUTE ? val->val : percent_to_val(val->val, d);
396+
new = val->v_type == ABSOLUTE ? val->val : percent_to_val(val->percentage, d);
390397
goto apply;
391398
}
392-
long mod = val->val;
393-
if (val->sign == MINUS)
394-
mod *= -1;
399+
int sign_mod = val->sign == MINUS ? -1 : 1;
400+
long mod;
395401
if (val->v_type == RELATIVE) {
396-
mod = percent_to_val(val_to_percent(d->curr_brightness, d, false) + mod, d) - d->curr_brightness;
397-
if (val->val != 0 && mod == 0)
402+
mod = percent_to_val(val_to_percent(d->curr_brightness, d, false) + val->percentage * sign_mod, d) - d->curr_brightness;
403+
if (val->percentage != 0 && mod == 0)
398404
mod = val->sign == PLUS ? 1 : -1;
405+
} else {
406+
mod = val->val * sign_mod;
399407
}
400408
new += mod;
401409
apply:
402410
if (p.min.v_type == RELATIVE) {
403-
p.min.val = percent_to_val(p.min.val, d);
411+
p.min.val = percent_to_val(p.min.percentage, d);
404412
p.min.v_type = ABSOLUTE;
405413
}
406414
if (new < (long)p.min.val)

0 commit comments

Comments
 (0)