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