From 60739263729e36f99b4c9279447c622acd3bd04c Mon Sep 17 00:00:00 2001 From: Federico Angelilli Date: Thu, 11 Jul 2024 16:28:28 +0200 Subject: Add color config type --- src/config.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/config.c b/src/config.c index 07f5743..93b4f53 100644 --- a/src/config.c +++ b/src/config.c @@ -17,6 +17,7 @@ typedef enum { CONFIG_UINT, CONFIG_DOUBLE, CONFIG_BOOL, + CONFIG_COLOR, } config_type_t; typedef struct { @@ -73,6 +74,13 @@ static bool config_read_uint(const char *value, unsigned int *result) return *end == '\0' && n != ULONG_MAX; } +static bool config_read_double(const char *value, double *result) +{ + char *end; + *result = strtod(value, &end); + return *end == '\0'; +} + static bool config_read_bool(const char *value, bool *result) { size_t lenght = strlen(value); @@ -91,11 +99,53 @@ static bool config_read_bool(const char *value, bool *result) return false; } -static bool config_read_double(const char *value, double *result) +static bool config_read_color(const char *value, color_t *result) { - char *end; - *result = strtod(value, &end); - return *end == '\0'; + if (!strcmp(value, "rgb")) { + log_panic("TODO"); + } + + if (value[0] == '#') { + char *end; + unsigned long n = strtoul(value + 1, &end, 16); + + if (end[0] != '\0') + return false; + + int bpc = 0; + switch (end - (value + 1)) { + case 3: + bpc = 4; + n = (n << 4) | 0x0f; + break; + + case 6: + bpc = 8; + n = (n << 8) | 0xff; + break; + + case 4: + bpc = 4; + break; + + case 8: + bpc = 8; + break; + + default: + return false; + } + + const unsigned int single_max = (1 << bpc) - 1; + result->r = ((n >> 3 * bpc) & single_max) / (double)single_max; + result->g = ((n >> 2 * bpc) & single_max) / (double)single_max; + result->b = ((n >> 1 * bpc) & single_max) / (double)single_max; + result->a = ((n >> 0 * bpc) & single_max) / (double)single_max; + return true; + } + + log_debug("Invalid color '%s'", value); + return false; } static bool config_entry(config_t *config, int line, const char *section, const char *key, const char *value) @@ -160,6 +210,13 @@ static bool config_entry(config_t *config, int line, const char *section, const } break; + case CONFIG_COLOR: + if (config_read_color(value, (color_t *)result)) { + log_debug("Config '%s' set to '%s'", key, value); + return true; + } + break; + default: log_panic("Unreachable"); } -- cgit v1.2.3