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