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