]> git.sur5r.net Git - i3/i3/blob - i3bar/src/cairo_util.c
Use 32-bit visuals for i3bar when possible and allow RGBA colors.
[i3/i3] / i3bar / src / cairo_util.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2015 Ingo Bürk and contributors (see also: LICENSE)
5  *
6  * cairo_util.c: Utility for operations using cairo.
7  *
8  */
9 #include <stdlib.h>
10 #include <err.h>
11 #include <string.h>
12 #include <xcb/xcb.h>
13 #include <xcb/xcb_aux.h>
14 #include <cairo/cairo-xcb.h>
15
16 #include "common.h"
17 #include "libi3.h"
18
19 xcb_connection_t *xcb_connection;
20 xcb_visualtype_t *visual_type;
21
22 /*
23  * Initialize the cairo surface to represent the given drawable.
24  *
25  */
26 void cairo_surface_init(surface_t *surface, xcb_drawable_t drawable, int width, int height) {
27     surface->id = drawable;
28
29     surface->gc = xcb_generate_id(xcb_connection);
30     xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection, surface->gc, surface->id, 0, NULL);
31     if (xcb_request_failed(gc_cookie, "Could not create graphical context"))
32         exit(EXIT_FAILURE);
33
34     surface->surface = cairo_xcb_surface_create(xcb_connection, surface->id, visual_type, width, height);
35     surface->cr = cairo_create(surface->surface);
36 }
37
38 /*
39  * Destroys the surface.
40  *
41  */
42 void cairo_surface_free(surface_t *surface) {
43     xcb_free_gc(xcb_connection, surface->gc);
44     cairo_surface_destroy(surface->surface);
45     cairo_destroy(surface->cr);
46 }
47
48 /*
49  * Parses the given color in hex format to an internal color representation.
50  * Note that the input must begin with a hash sign, e.g., "#3fbc59".
51  *
52  */
53 color_t cairo_hex_to_color(const char *color) {
54     char alpha[2];
55     if (strlen(color) == strlen("#rrggbbaa")) {
56         alpha[0] = color[7];
57         alpha[1] = color[8];
58     } else {
59         alpha[0] = alpha[1] = 'F';
60     }
61
62     char groups[4][3] = {
63         {color[1], color[2], '\0'},
64         {color[3], color[4], '\0'},
65         {color[5], color[6], '\0'},
66         {alpha[0], alpha[1], '\0'}};
67
68     return (color_t){
69         .red = strtol(groups[0], NULL, 16) / 255.0,
70         .green = strtol(groups[1], NULL, 16) / 255.0,
71         .blue = strtol(groups[2], NULL, 16) / 255.0,
72         .alpha = strtol(groups[3], NULL, 16) / 255.0,
73         .colorpixel = get_colorpixel(color)};
74 }
75
76 /*
77  * Set the given color as the source color on the surface.
78  *
79  */
80 void cairo_set_source_color(surface_t *surface, color_t color) {
81     cairo_set_source_rgba(surface->cr, color.red, color.green, color.blue, color.alpha);
82 }