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