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