]> git.sur5r.net Git - i3/i3/blob - libi3/font.c
Implement set_font_colors.
[i3/i3] / libi3 / font.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <assert.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdbool.h>
13 #include <err.h>
14
15 #include "libi3.h"
16
17 extern xcb_connection_t *conn;
18 static const i3Font *savedFont = NULL;
19
20 /*
21  * Loads a font for usage, also getting its metrics. If fallback is true,
22  * the fonts 'fixed' or '-misc-*' will be loaded instead of exiting.
23  *
24  */
25 i3Font load_font(const char *pattern, bool fallback) {
26     i3Font font;
27
28     /* Send all our requests first */
29     font.id = xcb_generate_id(conn);
30     xcb_void_cookie_t font_cookie = xcb_open_font_checked(conn, font.id,
31             strlen(pattern), pattern);
32     xcb_query_font_cookie_t info_cookie = xcb_query_font(conn, font.id);
33
34     /* Check for errors. If errors, fall back to default font. */
35     xcb_generic_error_t *error;
36     error = xcb_request_check(conn, font_cookie);
37
38     /* If we fail to open font, fall back to 'fixed' */
39     if (fallback && error != NULL) {
40         ELOG("Could not open font %s (X error %d). Trying fallback to 'fixed'.\n",
41              pattern, error->error_code);
42         pattern = "fixed";
43         font_cookie = xcb_open_font_checked(conn, font.id, strlen(pattern), pattern);
44         info_cookie = xcb_query_font(conn, font.id);
45
46         /* Check if we managed to open 'fixed' */
47         error = xcb_request_check(conn, font_cookie);
48
49         /* Fall back to '-misc-*' if opening 'fixed' fails. */
50         if (error != NULL) {
51             ELOG("Could not open fallback font 'fixed', trying with '-misc-*'.\n");
52             pattern = "-misc-*";
53             font_cookie = xcb_open_font_checked(conn, font.id, strlen(pattern), pattern);
54             info_cookie = xcb_query_font(conn, font.id);
55
56             if ((error = xcb_request_check(conn, font_cookie)) != NULL)
57                 errx(EXIT_FAILURE, "Could open neither requested font nor fallbacks "
58                      "(fixed or -misc-*): X11 error %d", error->error_code);
59         }
60     }
61
62     /* Get information (height/name) for this font */
63     if (!(font.info = xcb_query_font_reply(conn, info_cookie, NULL)))
64         errx(EXIT_FAILURE, "Could not load font \"%s\"", pattern);
65
66     /* Get the font table, if possible */
67     font.table = xcb_query_font_char_infos(font.info);
68
69     /* Calculate the font height */
70     font.height = font.info->font_ascent + font.info->font_descent;
71
72     return font;
73 }
74
75 /*
76  * Defines the font to be used for the forthcoming draw_text and
77  * predict_text_width calls.
78  *
79  */
80 void set_font(i3Font *font) {
81     savedFont = font;
82 }
83
84 /*
85  * Defines the colors to be used for the forthcoming draw_text calls.
86  *
87  */
88 void set_font_colors(xcb_gcontext_t gc, uint32_t foreground, uint32_t background) {
89     assert(savedFont != NULL);
90     uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
91     uint32_t values[] = { foreground, background, savedFont->id };
92     xcb_change_gc(conn, gc, mask, values);
93 }
94
95 /*
96  * Draws text onto the specified X drawable (normally a pixmap) at the
97  * specified coordinates (from the top left corner of the leftmost, uppermost
98  * glyph) and using the provided gc. Text can be specified as UCS-2 or UTF-8.
99  *
100  */
101 void draw_text(char *text, size_t text_len, bool is_ucs2, xcb_drawable_t drawable,
102         xcb_gcontext_t gc, int x, int y, int max_width) {
103     assert(savedFont != NULL);
104     assert(text_len != 0);
105
106     /* X11 coordinates for fonts start at the baseline */
107     int pos_y = y + savedFont->info->font_ascent;
108
109     /* As an optimization, check if we can bypass conversion */
110     if (!is_ucs2 && text_len <= 255) {
111         xcb_image_text_8(conn, text_len, drawable, gc, x, pos_y, text);
112         return;
113     }
114
115     /* Convert the text into UCS-2 so we can do basic pointer math */
116     char *input;
117     if (is_ucs2) {
118         input = text;
119     }
120     else {
121         int real_strlen;
122         input = (char*)convert_utf8_to_ucs2(text, &real_strlen);
123         text_len = real_strlen;
124     }
125
126     /* The X11 protocol limits text drawing to 255 chars, so we may need
127      * multiple calls */
128     int pos_x = x;
129     int offset = 0;
130     for (;;) {
131         /* Calculate the size of this chunk */
132         int chunk_size = text_len > 255 ? 255 : text_len;
133         xcb_char2b_t *chunk = (xcb_char2b_t*)input + offset;
134
135         /* Draw it */
136         xcb_image_text_16(conn, chunk_size, drawable, gc, pos_x, pos_y, chunk);
137
138         /* Advance the offset and length of the text to draw */
139         offset += chunk_size;
140         text_len -= chunk_size;
141
142         /* Check if we're done */
143         if (text_len == 0)
144             break;
145
146         /* Advance pos_x based on the predicted text width */
147         pos_x += predict_text_width((char*)chunk, chunk_size, true);
148     }
149
150     /* If we had to convert, free the converted string */
151     if (!is_ucs2)
152         free(input);
153 }
154
155 static int xcb_query_text_width(xcb_char2b_t *text, size_t text_len) {
156     /* Make the user know we're using the slow path */
157     static bool first = true;
158     if (first) {
159         fprintf(stderr, "Using slow code path for text extents\n");
160         first = false;
161     }
162
163     /* Query the text width */
164     xcb_generic_error_t *error;
165     xcb_query_text_extents_cookie_t cookie = xcb_query_text_extents(conn,
166             savedFont->id, text_len, (xcb_char2b_t*)text);
167     xcb_query_text_extents_reply_t *reply = xcb_query_text_extents_reply(conn,
168             cookie, &error);
169     if (reply == NULL) {
170         /* We return a safe estimate because a rendering error is better than
171          * a crash. Plus, the user will see the error in his log. */
172         fprintf(stderr, "Could not get text extents (X error code %d)\n",
173                 error->error_code);
174         return savedFont->info->max_bounds.character_width * text_len;
175     }
176
177     int width = reply->overall_width;
178     free(reply);
179     return width;
180 }
181
182 /*
183  * Predict the text width in pixels for the given text. Text can be specified
184  * as UCS-2 or UTF-8.
185  *
186  */
187 int predict_text_width(char *text, size_t text_len, bool is_ucs2) {
188     /* Convert the text into UTF-16 so we can do basic pointer math */
189     xcb_char2b_t *input;
190     if (is_ucs2) {
191         input = (xcb_char2b_t *)text;
192     }
193     else {
194         int real_strlen;
195         input = convert_utf8_to_ucs2(text, &real_strlen);
196         text_len = real_strlen;
197     }
198
199     int width;
200     if (savedFont->table == NULL) {
201         /* If we don't have a font table, fall back to querying the server */
202         width = xcb_query_text_width(input, text_len);
203     }
204     else {
205         /* Save some pointers for convenience */
206         xcb_query_font_reply_t *font_info = savedFont->info;
207         xcb_charinfo_t *font_table = savedFont->table;
208
209         /* Calculate the width using the font table */
210         width = 0;
211         for (size_t i = 0; i < text_len; i++) {
212             xcb_charinfo_t *info;
213             int row = input[i].byte1;
214             int col = input[i].byte2;
215
216             if (row < font_info->min_byte1 || row > font_info->max_byte1 ||
217                     col < font_info->min_char_or_byte2 || col > font_info->max_char_or_byte2) {
218                 continue;
219             }
220
221             /* Don't you ask me, how this one works… (Merovius) */
222             info = &font_table[((row - font_info->min_byte1) *
223                     (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
224                 (col - font_info->min_char_or_byte2)];
225
226             if (info->character_width != 0 ||
227                     (info->right_side_bearing |
228                      info->left_side_bearing |
229                      info->ascent |
230                      info->descent) != 0) {
231                 width += info->character_width;
232             }
233         }
234     }
235
236     /* If we had to convert, free the converted string */
237     if (!is_ucs2)
238         free(input);
239
240     return width;
241 }