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