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