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