]> git.sur5r.net Git - i3/i3/blob - i3bar/src/cairo_util.c
aff763c3fbc9e7a6004be9e951952ab95b992032
[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 <xcb/xcb.h>
12 #include <xcb/xcb_aux.h>
13 #include <cairo/cairo-xcb.h>
14
15 #include "common.h"
16 #include "libi3.h"
17
18 xcb_connection_t *xcb_connection;
19 xcb_screen_t *root_screen;
20
21 /*
22  * Initialize the cairo surface to represent the given drawable.
23  *
24  */
25 void cairo_surface_init(surface_t *surface, xcb_drawable_t drawable, int width, int height) {
26     surface->id = drawable;
27
28     surface->gc = xcb_generate_id(xcb_connection);
29     xcb_void_cookie_t gc_cookie = xcb_create_gc_checked(xcb_connection, surface->gc, surface->id, 0, NULL);
30     if (xcb_request_failed(gc_cookie, "Could not create graphical context"))
31         exit(EXIT_FAILURE);
32
33     surface->surface = cairo_xcb_surface_create(xcb_connection, surface->id, get_visualtype(root_screen), width, height);
34     surface->cr = cairo_create(surface->surface);
35 }
36
37 /*
38  * Destroys the surface.
39  *
40  */
41 void cairo_surface_free(surface_t *surface) {
42     xcb_free_gc(xcb_connection, surface->gc);
43     cairo_surface_destroy(surface->surface);
44     cairo_destroy(surface->cr);
45 }
46
47 /*
48  * Parses the given color in hex format to an internal color representation.
49  * Note that the input must begin with a hash sign, e.g., "#3fbc59".
50  *
51  */
52 color_t cairo_hex_to_color(const char *color) {
53     char groups[3][3] = {
54         {color[1], color[2], '\0'},
55         {color[3], color[4], '\0'},
56         {color[5], color[6], '\0'}};
57
58     return (color_t){
59         .red = strtol(groups[0], NULL, 16) / 255.0,
60         .green = strtol(groups[1], NULL, 16) / 255.0,
61         .blue = strtol(groups[2], NULL, 16) / 255.0,
62         .colorpixel = get_colorpixel(color)};
63 }
64
65 /*
66  * Set the given color as the source color on the surface.
67  *
68  */
69 void cairo_set_source_color(surface_t *surface, color_t color) {
70     cairo_set_source_rgb(surface->cr, color.red, color.green, color.blue);
71 }