]> git.sur5r.net Git - i3/i3/blob - libi3/font.c
Merge branch 'master' into next
[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 #if PANGO_SUPPORT
16 #include <cairo/cairo-xcb.h>
17 #include <pango/pangocairo.h>
18 #endif
19
20 #include "libi3.h"
21
22 extern xcb_connection_t *conn;
23 extern xcb_screen_t *root_screen;
24
25 static const i3Font *savedFont = NULL;
26
27 #if PANGO_SUPPORT
28 static xcb_visualtype_t *root_visual_type;
29 static double pango_font_red;
30 static double pango_font_green;
31 static double pango_font_blue;
32
33 /*
34  * Loads a Pango font description into an i3Font structure. Returns true
35  * on success, false otherwise.
36  *
37  */
38 static bool load_pango_font(i3Font *font, const char *desc) {
39     /* Load the font description */
40     font->specific.pango_desc = pango_font_description_from_string(desc);
41     if (!font->specific.pango_desc) {
42         ELOG("Could not open font %s with Pango, fallback to X font.\n", desc);
43         return false;
44     }
45
46     LOG("Using Pango font %s, size %d\n",
47         pango_font_description_get_family(font->specific.pango_desc),
48         pango_font_description_get_size(font->specific.pango_desc) / PANGO_SCALE
49         );
50
51     /* We cache root_visual_type here, since you must call
52      * load_pango_font before any other pango function
53      * that would need root_visual_type */
54     root_visual_type = get_visualtype(root_screen);
55
56     /* Create a dummy Pango layout to compute the font height */
57     cairo_surface_t *surface = cairo_xcb_surface_create(conn, root_screen->root, root_visual_type, 1, 1);
58     cairo_t *cr = cairo_create(surface);
59     PangoLayout *layout = pango_cairo_create_layout(cr);
60     pango_layout_set_font_description(layout, font->specific.pango_desc);
61
62     /* Get the font height */
63     gint height;
64     pango_layout_get_pixel_size(layout, NULL, &height);
65     font->height = height;
66
67     /* Free resources */
68     g_object_unref(layout);
69     cairo_destroy(cr);
70     cairo_surface_destroy(surface);
71
72     /* Set the font type and return successfully */
73     font->type = FONT_TYPE_PANGO;
74     return true;
75 }
76
77 /*
78  * Draws text using Pango rendering.
79  *
80  */
81 static void draw_text_pango(const char *text, size_t text_len,
82         xcb_drawable_t drawable, int x, int y, int max_width) {
83     /* Create the Pango layout */
84     /* root_visual_type is cached in load_pango_font */
85     cairo_surface_t *surface = cairo_xcb_surface_create(conn, drawable,
86             root_visual_type, x + max_width, y + savedFont->height);
87     cairo_t *cr = cairo_create(surface);
88     PangoLayout *layout = pango_cairo_create_layout(cr);
89     pango_layout_set_font_description(layout, savedFont->specific.pango_desc);
90     pango_layout_set_width(layout, max_width * PANGO_SCALE);
91     pango_layout_set_wrap(layout, PANGO_WRAP_CHAR);
92     pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
93
94     /* Do the drawing */
95     cairo_set_source_rgb(cr, pango_font_red, pango_font_green, pango_font_blue);
96     cairo_move_to(cr, x, y);
97     pango_layout_set_text(layout, text, text_len);
98     pango_cairo_update_layout(cr, layout);
99     pango_cairo_show_layout(cr, layout);
100
101     /* Free resources */
102     g_object_unref(layout);
103     cairo_destroy(cr);
104     cairo_surface_destroy(surface);
105 }
106
107 /*
108  * Calculate the text width using Pango rendering.
109  *
110  */
111 static int predict_text_width_pango(const char *text, size_t text_len) {
112     /* Create a dummy Pango layout */
113     /* root_visual_type is cached in load_pango_font */
114     cairo_surface_t *surface = cairo_xcb_surface_create(conn, root_screen->root, root_visual_type, 1, 1);
115     cairo_t *cr = cairo_create(surface);
116     PangoLayout *layout = pango_cairo_create_layout(cr);
117
118     /* Get the font width */
119     gint width;
120     pango_layout_set_font_description(layout, savedFont->specific.pango_desc);
121     pango_layout_set_text(layout, text, text_len);
122     pango_cairo_update_layout(cr, layout);
123     pango_layout_get_pixel_size(layout, &width, NULL);
124
125     /* Free resources */
126     g_object_unref(layout);
127     cairo_destroy(cr);
128     cairo_surface_destroy(surface);
129
130     return width;
131 }
132 #endif
133
134 /*
135  * Loads a font for usage, also getting its metrics. If fallback is true,
136  * the fonts 'fixed' or '-misc-*' will be loaded instead of exiting.
137  *
138  */
139 i3Font load_font(const char *pattern, const bool fallback) {
140     i3Font font;
141     font.type = FONT_TYPE_NONE;
142
143 #if PANGO_SUPPORT
144     /* Try to load a pango font if specified */
145     if (strlen(pattern) > strlen("xft:") && !strncmp(pattern, "xft:", strlen("xft:"))) {
146         pattern += strlen("xft:");
147         if (load_pango_font(&font, pattern))
148             return font;
149     }
150 #endif
151
152     /* Send all our requests first */
153     font.specific.xcb.id = xcb_generate_id(conn);
154     xcb_void_cookie_t font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
155             strlen(pattern), pattern);
156     xcb_query_font_cookie_t info_cookie = xcb_query_font(conn, font.specific.xcb.id);
157
158     /* Check for errors. If errors, fall back to default font. */
159     xcb_generic_error_t *error;
160     error = xcb_request_check(conn, font_cookie);
161
162     /* If we fail to open font, fall back to 'fixed' */
163     if (fallback && error != NULL) {
164         ELOG("Could not open font %s (X error %d). Trying fallback to 'fixed'.\n",
165              pattern, error->error_code);
166         pattern = "fixed";
167         font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
168                 strlen(pattern), pattern);
169         info_cookie = xcb_query_font(conn, font.specific.xcb.id);
170
171         /* Check if we managed to open 'fixed' */
172         error = xcb_request_check(conn, font_cookie);
173
174         /* Fall back to '-misc-*' if opening 'fixed' fails. */
175         if (error != NULL) {
176             ELOG("Could not open fallback font 'fixed', trying with '-misc-*'.\n");
177             pattern = "-misc-*";
178             font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
179                     strlen(pattern), pattern);
180             info_cookie = xcb_query_font(conn, font.specific.xcb.id);
181
182             if ((error = xcb_request_check(conn, font_cookie)) != NULL)
183                 errx(EXIT_FAILURE, "Could open neither requested font nor fallbacks "
184                      "(fixed or -misc-*): X11 error %d", error->error_code);
185         }
186     }
187
188     LOG("Using X font %s\n", pattern);
189
190     /* Get information (height/name) for this font */
191     if (!(font.specific.xcb.info = xcb_query_font_reply(conn, info_cookie, NULL)))
192         errx(EXIT_FAILURE, "Could not load font \"%s\"", pattern);
193
194     /* Get the font table, if possible */
195     if (xcb_query_font_char_infos_length(font.specific.xcb.info) == 0)
196         font.specific.xcb.table = NULL;
197     else
198         font.specific.xcb.table = xcb_query_font_char_infos(font.specific.xcb.info);
199
200     /* Calculate the font height */
201     font.height = font.specific.xcb.info->font_ascent + font.specific.xcb.info->font_descent;
202
203     /* Set the font type and return successfully */
204     font.type = FONT_TYPE_XCB;
205     return font;
206 }
207
208 /*
209  * Defines the font to be used for the forthcoming calls.
210  *
211  */
212 void set_font(i3Font *font) {
213     savedFont = font;
214 }
215
216 /*
217  * Frees the resources taken by the current font.
218  *
219  */
220 void free_font(void) {
221     switch (savedFont->type) {
222         case FONT_TYPE_NONE:
223             /* Nothing to do */
224             break;
225         case FONT_TYPE_XCB: {
226             /* Close the font and free the info */
227             xcb_close_font(conn, savedFont->specific.xcb.id);
228             if (savedFont->specific.xcb.info)
229                 free(savedFont->specific.xcb.info);
230             break;
231         }
232 #if PANGO_SUPPORT
233         case FONT_TYPE_PANGO:
234             /* Free the font description */
235             pango_font_description_free(savedFont->specific.pango_desc);
236             break;
237 #endif
238         default:
239             assert(false);
240             break;
241     }
242 }
243
244 /*
245  * Defines the colors to be used for the forthcoming draw_text calls.
246  *
247  */
248 void set_font_colors(xcb_gcontext_t gc, uint32_t foreground, uint32_t background) {
249     assert(savedFont != NULL);
250
251     switch (savedFont->type) {
252         case FONT_TYPE_NONE:
253             /* Nothing to do */
254             break;
255         case FONT_TYPE_XCB: {
256             /* Change the font and colors in the GC */
257             uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
258             uint32_t values[] = { foreground, background, savedFont->specific.xcb.id };
259             xcb_change_gc(conn, gc, mask, values);
260             break;
261         }
262 #if PANGO_SUPPORT
263         case FONT_TYPE_PANGO:
264             /* Save the foreground font */
265             pango_font_red = ((foreground >> 16) & 0xff) / 255.0;
266             pango_font_green = ((foreground >> 8) & 0xff) / 255.0;
267             pango_font_blue = (foreground & 0xff) / 255.0;
268             break;
269 #endif
270         default:
271             assert(false);
272             break;
273     }
274 }
275
276 static int predict_text_width_xcb(const xcb_char2b_t *text, size_t text_len);
277
278 static void draw_text_xcb(const xcb_char2b_t *text, size_t text_len, xcb_drawable_t drawable,
279                xcb_gcontext_t gc, int x, int y, int max_width) {
280     /* X11 coordinates for fonts start at the baseline */
281     int pos_y = y + savedFont->specific.xcb.info->font_ascent;
282
283     /* The X11 protocol limits text drawing to 255 chars, so we may need
284      * multiple calls */
285     int offset = 0;
286     for (;;) {
287         /* Calculate the size of this chunk */
288         int chunk_size = (text_len > 255 ? 255 : text_len);
289         const xcb_char2b_t *chunk = text + offset;
290
291         /* Draw it */
292         xcb_image_text_16(conn, chunk_size, drawable, gc, x, pos_y, chunk);
293
294         /* Advance the offset and length of the text to draw */
295         offset += chunk_size;
296         text_len -= chunk_size;
297
298         /* Check if we're done */
299         if (text_len == 0)
300             break;
301
302         /* Advance pos_x based on the predicted text width */
303         x += predict_text_width_xcb(chunk, chunk_size);
304     }
305 }
306
307 /*
308  * Draws text onto the specified X drawable (normally a pixmap) at the
309  * specified coordinates (from the top left corner of the leftmost, uppermost
310  * glyph) and using the provided gc.
311  *
312  * Text must be specified as an i3String.
313  *
314  */
315 void draw_text(i3String *text, xcb_drawable_t drawable,
316                xcb_gcontext_t gc, int x, int y, int max_width) {
317     assert(savedFont != NULL);
318
319     switch (savedFont->type) {
320         case FONT_TYPE_NONE:
321             /* Nothing to do */
322             return;
323         case FONT_TYPE_XCB:
324             draw_text_xcb(i3string_as_ucs2(text), i3string_get_num_glyphs(text),
325                       drawable, gc, x, y, max_width);
326             break;
327 #if PANGO_SUPPORT
328         case FONT_TYPE_PANGO:
329             /* Render the text using Pango */
330             draw_text_pango(i3string_as_utf8(text), i3string_get_num_bytes(text),
331                             drawable, x, y, max_width);
332             return;
333 #endif
334         default:
335             assert(false);
336     }
337 }
338
339 /*
340  * ASCII version of draw_text to print static strings.
341  *
342  */
343 void draw_text_ascii(const char *text, xcb_drawable_t drawable,
344                xcb_gcontext_t gc, int x, int y, int max_width) {
345     assert(savedFont != NULL);
346
347     switch (savedFont->type) {
348         case FONT_TYPE_NONE:
349             /* Nothing to do */
350             return;
351         case FONT_TYPE_XCB:
352         {
353             size_t text_len = strlen(text);
354             if (text_len > 255) {
355                 /* The text is too long to draw it directly to X */
356                 i3String *str = i3string_from_utf8(text);
357                 draw_text(str, drawable, gc, x, y, max_width);
358                 i3string_free(str);
359             } else {
360                 /* X11 coordinates for fonts start at the baseline */
361                 int pos_y = y + savedFont->specific.xcb.info->font_ascent;
362
363                 xcb_image_text_8(conn, text_len, drawable, gc, x, pos_y, text);
364             }
365             break;
366         }
367 #if PANGO_SUPPORT
368         case FONT_TYPE_PANGO:
369             /* Render the text using Pango */
370             draw_text_pango(text, strlen(text),
371                             drawable, x, y, max_width);
372             return;
373 #endif
374         default:
375             assert(false);
376     }
377 }
378
379 static int xcb_query_text_width(const xcb_char2b_t *text, size_t text_len) {
380     /* Make the user know we’re using the slow path, but only once. */
381     static bool first_invocation = true;
382     if (first_invocation) {
383         fprintf(stderr, "Using slow code path for text extents\n");
384         first_invocation = false;
385     }
386
387     /* Query the text width */
388     xcb_generic_error_t *error;
389     xcb_query_text_extents_cookie_t cookie = xcb_query_text_extents(conn,
390             savedFont->specific.xcb.id, text_len, (xcb_char2b_t*)text);
391     xcb_query_text_extents_reply_t *reply = xcb_query_text_extents_reply(conn,
392             cookie, &error);
393     if (reply == NULL) {
394         /* We return a safe estimate because a rendering error is better than
395          * a crash. Plus, the user will see the error in his log. */
396         fprintf(stderr, "Could not get text extents (X error code %d)\n",
397                 error->error_code);
398         return savedFont->specific.xcb.info->max_bounds.character_width * text_len;
399     }
400
401     int width = reply->overall_width;
402     free(reply);
403     return width;
404 }
405
406 static int predict_text_width_xcb(const xcb_char2b_t *input, size_t text_len) {
407     if (text_len == 0)
408         return 0;
409
410     int width;
411     if (savedFont->specific.xcb.table == NULL) {
412         /* If we don't have a font table, fall back to querying the server */
413         width = xcb_query_text_width(input, text_len);
414     } else {
415         /* Save some pointers for convenience */
416         xcb_query_font_reply_t *font_info = savedFont->specific.xcb.info;
417         xcb_charinfo_t *font_table = savedFont->specific.xcb.table;
418
419         /* Calculate the width using the font table */
420         width = 0;
421         for (size_t i = 0; i < text_len; i++) {
422             xcb_charinfo_t *info;
423             int row = input[i].byte1;
424             int col = input[i].byte2;
425
426             if (row < font_info->min_byte1 ||
427                 row > font_info->max_byte1 ||
428                 col < font_info->min_char_or_byte2 ||
429                 col > font_info->max_char_or_byte2)
430                 continue;
431
432             /* Don't you ask me, how this one works… (Merovius) */
433             info = &font_table[((row - font_info->min_byte1) *
434                     (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
435                 (col - font_info->min_char_or_byte2)];
436
437             if (info->character_width != 0 ||
438                     (info->right_side_bearing |
439                      info->left_side_bearing |
440                      info->ascent |
441                      info->descent) != 0) {
442                 width += info->character_width;
443             }
444         }
445     }
446
447     return width;
448 }
449
450 /*
451  * Predict the text width in pixels for the given text. Text must be
452  * specified as an i3String.
453  *
454  */
455 int predict_text_width(i3String *text) {
456     assert(savedFont != NULL);
457
458     switch (savedFont->type) {
459         case FONT_TYPE_NONE:
460             /* Nothing to do */
461             return 0;
462         case FONT_TYPE_XCB:
463             return predict_text_width_xcb(i3string_as_ucs2(text), i3string_get_num_glyphs(text));
464 #if PANGO_SUPPORT
465         case FONT_TYPE_PANGO:
466             /* Calculate extents using Pango */
467             return predict_text_width_pango(i3string_as_utf8(text), i3string_get_num_bytes(text));
468 #endif
469         default:
470             assert(false);
471             return 0;
472     }
473 }