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