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