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