]> git.sur5r.net Git - i3/i3/blob - libi3/get_colorpixel.c
3a62a8e4949d42e7333a6c50201422ccb868934b
[i3/i3] / libi3 / get_colorpixel.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <stdlib.h>
9 #include <stdint.h>
10 #include <string.h>
11
12 #include "libi3.h"
13
14 /*
15  * Returns the colorpixel to use for the given hex color (think of HTML). Only
16  * works for true-color (vast majority of cases) at the moment, avoiding a
17  * roundtrip to X11.
18  *
19  * The hex_color has to start with #, for example #FF00FF.
20  *
21  * NOTE that get_colorpixel() does _NOT_ check the given color code for validity.
22  * This has to be done by the caller.
23  *
24  * NOTE that this function may in the future rely on a global xcb_connection_t
25  * variable called 'conn' to be present.
26  *
27  */
28 uint32_t get_colorpixel(const char *hex) {
29     char alpha[2];
30     if (strlen(hex) == strlen("#rrggbbaa")) {
31         alpha[0] = hex[7];
32         alpha[1] = hex[8];
33     } else {
34         alpha[0] = alpha[1] = 'F';
35     }
36
37     char strgroups[4][3] = {
38         {hex[1], hex[2], '\0'},
39         {hex[3], hex[4], '\0'},
40         {hex[5], hex[6], '\0'},
41         {alpha[0], alpha[1], '\0'}};
42     uint8_t r = strtol(strgroups[0], NULL, 16);
43     uint8_t g = strtol(strgroups[1], NULL, 16);
44     uint8_t b = strtol(strgroups[2], NULL, 16);
45     uint8_t a = strtol(strgroups[3], NULL, 16);
46
47     return (a << 24) | (r << 16 | g << 8 | b);
48 }