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