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