]> git.sur5r.net Git - i3/i3/blob - src/font.c
OK, it could still be improved ;-)
[i3/i3] / src / font.c
1 /*
2  * vim:ts=8:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  *
6  * © 2009 Michael Stapelberg and contributors
7  *
8  * See file LICENSE for license information.
9  *
10  * font.c: Handles font loading (with caching, with height information)
11  *
12  */
13 #include <string.h>
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <xcb/xcb.h>
17
18 #include "data.h"
19 #include "util.h"
20
21 TAILQ_HEAD(cached_fonts_head, Font) cached_fonts = TAILQ_HEAD_INITIALIZER(cached_fonts);
22
23 /*
24  * Loads a font for usage, getting its height. This function is used very often, so it
25  * maintains a cache.
26  *
27  */
28 i3Font *load_font(xcb_connection_t *connection, const char *pattern) {
29         /* Check if we got the font cached */
30         i3Font *font;
31         TAILQ_FOREACH(font, &cached_fonts, fonts)
32                 if (strcmp(font->pattern, pattern) == 0)
33                         return font;
34
35         i3Font *new = smalloc(sizeof(i3Font));
36         xcb_void_cookie_t font_cookie;
37         xcb_list_fonts_with_info_cookie_t info_cookie;
38
39         /* Send all our requests first */
40         new->id = xcb_generate_id(connection);
41         font_cookie = xcb_open_font_checked(connection, new->id, strlen(pattern), pattern);
42         info_cookie = xcb_list_fonts_with_info(connection, 1, strlen(pattern), pattern);
43
44         check_error(connection, font_cookie, "Could not open font");
45         check_error(connection, info_cookie, "Could not get font information");
46
47         /* Get information (height/name) for this font */
48         xcb_list_fonts_with_info_reply_t *reply = xcb_list_fonts_with_info_reply(connection, cookie, NULL);
49         exit_if_null(reply, "Could not load font \"%s\"\n", pattern);
50
51         if (asprintf(&(new->name), "%.*s", xcb_list_fonts_with_info_name_length(reply),
52                                            xcb_list_fonts_with_info_name(reply)) == -1)
53                 die("asprintf() failed\n");
54         new->pattern = sstrdup(pattern);
55         new->height = reply->font_ascent + reply->font_descent;
56
57         /* Insert into cache */
58         TAILQ_INSERT_TAIL(&cached_fonts, new, fonts);
59
60         return new;
61 }