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