1
0
mirror of https://github.com/Llewellynvdm/conky.git synced 2024-09-27 20:59:01 +00:00

colours: parse 3-digit colour specifications again (#1480)

Co-authored-by: bi4k8 <bi4k8@github>
This commit is contained in:
bi4k8 2023-03-31 16:52:37 +00:00 committed by GitHub
parent 9fe62be933
commit 30eda7e5d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 8 deletions

View File

@ -60,17 +60,31 @@ Colour error_colour{0xff, 0x00, 0x00, 0xff};
Colour parse_color(const char *name) {
unsigned short r, g, b;
size_t len = strlen(name);
// Parse X11 color names.
if (OsLookupColor(-1, name, len, &r, &g, &b)) {
Colour out = {(uint8_t)r, (uint8_t)g, (uint8_t)b, 0xff};
return out;
}
// Remove a leading '#' if present.
if (name[0] == '#') {
name++;
len--;
}
if (len == 6 || len == 8) {
bool skip_alpha = (len == 6);
unsigned char argb[4] = {0xff, 0, 0, 0};
if (len == 3 || len == 4) {
bool skip_alpha = (len == 3);
for (size_t i = 0; i < len; i ++) {
int nib = hex_nibble_value(name[i]);
if (nib < 0) { goto err; }
// Duplicate the nibble, so "#abc" -> 0xaa, 0xbb, 0xcc
int val = (nib << 4) + nib;
argb[skip_alpha + i] = val;
}
} else if (len == 6 || len == 8) {
bool skip_alpha = (len == 6);
for (size_t i = 0; i + 1 < len; i += 2) {
int nib1 = hex_nibble_value(name[i]);
int nib2 = hex_nibble_value(name[i + 1]);
@ -79,13 +93,17 @@ Colour parse_color(const char *name) {
argb[skip_alpha + i / 2] = val;
}
} else {
goto err;
}
Colour out;
out.alpha = argb[0];
out.red = argb[1];
out.green = argb[2];
out.blue = argb[3];
return out;
}
err:
NORM_ERR("can't parse X color '%s' (%d)", name, len);
return error_colour;

View File

@ -4,6 +4,22 @@
#include <config.h>
TEST_CASE("parse_color correctly parses colours", "[colours][parse_color]") {
SECTION("parsing abbreviated hex color") {
auto colour = parse_color("#abc");
REQUIRE(colour.alpha == 255);
REQUIRE(colour.red == 0xaa);
REQUIRE(colour.green == 0xbb);
REQUIRE(colour.blue == 0xcc);
}
SECTION("parsing abbreviated hex color with alpha") {
auto colour = parse_color("#4abc");
REQUIRE(colour.alpha == 0x44);
REQUIRE(colour.red == 0xaa);
REQUIRE(colour.green == 0xbb);
REQUIRE(colour.blue == 0xcc);
}
SECTION("parsing hex red") {
auto colour = parse_color("#ff0000");
REQUIRE(colour.alpha == 255);