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