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