]> git.sur5r.net Git - i3/i3/blob - libi3/font.c
Document text_len in the draw_text description.
[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, const 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     if (xcb_query_font_char_infos_length(font.info) == 0)
68         font.table = NULL;
69     else
70         font.table = xcb_query_font_char_infos(font.info);
71
72     /* Calculate the font height */
73     font.height = font.info->font_ascent + font.info->font_descent;
74
75     return font;
76 }
77
78 /*
79  * Defines the font to be used for the forthcoming calls.
80  *
81  */
82 void set_font(i3Font *font) {
83     savedFont = font;
84 }
85
86 /*
87  * Frees the resources taken by the current font.
88  *
89  */
90 void free_font() {
91     /* Close the font and free the info */
92     xcb_close_font(conn, savedFont->id);
93     if (savedFont->info)
94         free(savedFont->info);
95 }
96
97 /*
98  * Defines the colors to be used for the forthcoming draw_text calls.
99  *
100  */
101 void set_font_colors(xcb_gcontext_t gc, uint32_t foreground, uint32_t background) {
102     assert(savedFont != NULL);
103     uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
104     uint32_t values[] = { foreground, background, savedFont->id };
105     xcb_change_gc(conn, gc, mask, values);
106 }
107
108 /*
109  * Draws text onto the specified X drawable (normally a pixmap) at the
110  * specified coordinates (from the top left corner of the leftmost, uppermost
111  * glyph) and using the provided gc.
112  *
113  * Text can be specified as UCS-2 or UTF-8. If it's specified as UCS-2, then
114  * text_len must be the number of glyphs in the string. If it's specified as
115  * UTF-8, then text_len must be the number of bytes in the string (not counting
116  * the null terminator).
117  *
118  */
119 void draw_text(char *text, size_t text_len, bool is_ucs2, xcb_drawable_t drawable,
120                xcb_gcontext_t gc, int x, int y, int max_width) {
121     assert(savedFont != NULL);
122     assert(text_len != 0);
123
124     /* X11 coordinates for fonts start at the baseline */
125     int pos_y = y + savedFont->info->font_ascent;
126
127     /* As an optimization, check if we can bypass conversion */
128     if (!is_ucs2 && text_len <= 255) {
129         xcb_image_text_8(conn, text_len, drawable, gc, x, pos_y, text);
130         return;
131     }
132
133     /* Convert the text into UCS-2 so we can do basic pointer math */
134     char *input = (is_ucs2 ? text : (char*)convert_utf8_to_ucs2(text, &text_len));
135
136     /* The X11 protocol limits text drawing to 255 chars, so we may need
137      * multiple calls */
138     int pos_x = x;
139     int offset = 0;
140     for (;;) {
141         /* Calculate the size of this chunk */
142         int chunk_size = (text_len > 255 ? 255 : text_len);
143         xcb_char2b_t *chunk = (xcb_char2b_t*)input + offset;
144
145         /* Draw it */
146         xcb_image_text_16(conn, chunk_size, drawable, gc, pos_x, pos_y, chunk);
147
148         /* Advance the offset and length of the text to draw */
149         offset += chunk_size;
150         text_len -= chunk_size;
151
152         /* Check if we're done */
153         if (text_len == 0)
154             break;
155
156         /* Advance pos_x based on the predicted text width */
157         pos_x += predict_text_width((char*)chunk, chunk_size, true);
158     }
159
160     /* If we had to convert, free the converted string */
161     if (!is_ucs2)
162         free(input);
163 }
164
165 static int xcb_query_text_width(xcb_char2b_t *text, size_t text_len) {
166     /* Make the user know we’re using the slow path, but only once. */
167     static bool first_invocation = true;
168     if (first_invocation) {
169         fprintf(stderr, "Using slow code path for text extents\n");
170         first_invocation = false;
171     }
172
173     /* Query the text width */
174     xcb_generic_error_t *error;
175     xcb_query_text_extents_cookie_t cookie = xcb_query_text_extents(conn,
176             savedFont->id, text_len, (xcb_char2b_t*)text);
177     xcb_query_text_extents_reply_t *reply = xcb_query_text_extents_reply(conn,
178             cookie, &error);
179     if (reply == NULL) {
180         /* We return a safe estimate because a rendering error is better than
181          * a crash. Plus, the user will see the error in his log. */
182         fprintf(stderr, "Could not get text extents (X error code %d)\n",
183                 error->error_code);
184         return savedFont->info->max_bounds.character_width * text_len;
185     }
186
187     int width = reply->overall_width;
188     free(reply);
189     return width;
190 }
191
192 /*
193  * Predict the text width in pixels for the given text. Text can be specified
194  * as UCS-2 or UTF-8.
195  *
196  */
197 int predict_text_width(char *text, size_t text_len, bool is_ucs2) {
198     /* Convert the text into UTF-16 so we can do basic pointer math */
199     xcb_char2b_t *input;
200     if (is_ucs2)
201         input = (xcb_char2b_t*)text;
202     else
203         input = convert_utf8_to_ucs2(text, &text_len);
204
205     int width;
206     if (savedFont->table == NULL) {
207         /* If we don't have a font table, fall back to querying the server */
208         width = xcb_query_text_width(input, text_len);
209     } else {
210         /* Save some pointers for convenience */
211         xcb_query_font_reply_t *font_info = savedFont->info;
212         xcb_charinfo_t *font_table = savedFont->table;
213
214         /* Calculate the width using the font table */
215         width = 0;
216         for (size_t i = 0; i < text_len; i++) {
217             xcb_charinfo_t *info;
218             int row = input[i].byte1;
219             int col = input[i].byte2;
220
221             if (row < font_info->min_byte1 ||
222                 row > font_info->max_byte1 ||
223                 col < font_info->min_char_or_byte2 ||
224                 col > font_info->max_char_or_byte2)
225                 continue;
226
227             /* Don't you ask me, how this one works… (Merovius) */
228             info = &font_table[((row - font_info->min_byte1) *
229                     (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
230                 (col - font_info->min_char_or_byte2)];
231
232             if (info->character_width != 0 ||
233                     (info->right_side_bearing |
234                      info->left_side_bearing |
235                      info->ascent |
236                      info->descent) != 0) {
237                 width += info->character_width;
238             }
239         }
240     }
241
242     /* If we had to convert, free the converted string */
243     if (!is_ucs2)
244         free(input);
245
246     return width;
247 }