2 * vim:ts=4:sw=4:expandtab
4 * i3 - an improved dynamic tiling window manager
5 * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
16 #include <cairo/cairo-xcb.h>
17 #include <pango/pangocairo.h>
22 extern xcb_connection_t *conn;
23 extern xcb_screen_t *root_screen;
25 static const i3Font *savedFont = NULL;
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;
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;
37 static PangoLayout *create_layout_with_dpi(cairo_t *cr) {
39 PangoContext *context;
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) {
46 LOG("X11 root window dictates %f DPI\n", dpi);
48 DLOG("X11 root window dictates %f DPI\n", dpi);
50 pango_cairo_context_set_resolution(context, dpi);
51 layout = pango_layout_new(context);
52 g_object_unref(context);
58 * Loads a Pango font description into an i3Font structure. Returns true
59 * on success, false otherwise.
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);
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);
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);
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);
85 /* Get the font height */
87 pango_layout_get_pixel_size(layout, NULL, &height);
88 font->height = height;
91 g_object_unref(layout);
93 cairo_surface_destroy(surface);
95 /* Set the font type and return successfully */
96 font->type = FONT_TYPE_PANGO;
101 * Draws text using Pango rendering.
104 static void draw_text_pango(const char *text, size_t text_len,
105 xcb_drawable_t drawable, int x, int y,
106 int max_width, bool is_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 root_visual_type, x + max_width, y + savedFont->height);
111 cairo_t *cr = cairo_create(surface);
112 PangoLayout *layout = create_layout_with_dpi(cr);
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);
121 pango_layout_set_markup(layout, text, text_len);
123 pango_layout_set_text(layout, text, text_len);
126 cairo_set_source_rgb(cr, pango_font_red, pango_font_green, pango_font_blue);
127 pango_cairo_update_layout(cr, layout);
128 pango_layout_get_pixel_size(layout, NULL, &height);
129 cairo_move_to(cr, x, y - (height - savedFont->height));
130 pango_cairo_show_layout(cr, layout);
133 g_object_unref(layout);
135 cairo_surface_destroy(surface);
139 * Calculate the text width using Pango rendering.
142 static int predict_text_width_pango(const char *text, size_t text_len, bool is_markup) {
143 /* Create a dummy Pango layout */
144 /* root_visual_type is cached in load_pango_font */
145 cairo_surface_t *surface = cairo_xcb_surface_create(conn, root_screen->root, root_visual_type, 1, 1);
146 cairo_t *cr = cairo_create(surface);
147 PangoLayout *layout = create_layout_with_dpi(cr);
149 /* Get the font width */
151 pango_layout_set_font_description(layout, savedFont->specific.pango_desc);
154 pango_layout_set_markup(layout, text, text_len);
156 pango_layout_set_text(layout, text, text_len);
158 pango_cairo_update_layout(cr, layout);
159 pango_layout_get_pixel_size(layout, &width, NULL);
162 g_object_unref(layout);
164 cairo_surface_destroy(surface);
171 * Loads a font for usage, also getting its metrics. If fallback is true,
172 * the fonts 'fixed' or '-misc-*' will be loaded instead of exiting. If any
173 * font was previously loaded, it will be freed.
176 i3Font load_font(const char *pattern, const bool fallback) {
177 /* if any font was previously loaded, free it now */
181 font.type = FONT_TYPE_NONE;
183 /* No XCB connction, return early because we're just validating the
184 * configuration file. */
190 /* Try to load a pango font if specified */
191 if (strlen(pattern) > strlen("pango:") && !strncmp(pattern, "pango:", strlen("pango:"))) {
192 const char *font_pattern = pattern + strlen("pango:");
193 if (load_pango_font(&font, font_pattern)) {
194 font.pattern = sstrdup(pattern);
197 } else if (strlen(pattern) > strlen("xft:") && !strncmp(pattern, "xft:", strlen("xft:"))) {
198 const char *font_pattern = pattern + strlen("xft:");
199 if (load_pango_font(&font, font_pattern)) {
200 font.pattern = sstrdup(pattern);
206 /* Send all our requests first */
207 font.specific.xcb.id = xcb_generate_id(conn);
208 xcb_void_cookie_t font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
209 strlen(pattern), pattern);
210 xcb_query_font_cookie_t info_cookie = xcb_query_font(conn, font.specific.xcb.id);
212 /* Check for errors. If errors, fall back to default font. */
213 xcb_generic_error_t *error;
214 error = xcb_request_check(conn, font_cookie);
216 /* If we fail to open font, fall back to 'fixed' */
217 if (fallback && error != NULL) {
218 ELOG("Could not open font %s (X error %d). Trying fallback to 'fixed'.\n",
219 pattern, error->error_code);
221 font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
222 strlen(pattern), pattern);
223 info_cookie = xcb_query_font(conn, font.specific.xcb.id);
225 /* Check if we managed to open 'fixed' */
226 error = xcb_request_check(conn, font_cookie);
228 /* Fall back to '-misc-*' if opening 'fixed' fails. */
230 ELOG("Could not open fallback font 'fixed', trying with '-misc-*'.\n");
232 font_cookie = xcb_open_font_checked(conn, font.specific.xcb.id,
233 strlen(pattern), pattern);
234 info_cookie = xcb_query_font(conn, font.specific.xcb.id);
236 if ((error = xcb_request_check(conn, font_cookie)) != NULL)
237 errx(EXIT_FAILURE, "Could open neither requested font nor fallbacks "
238 "(fixed or -misc-*): X11 error %d",
243 font.pattern = sstrdup(pattern);
244 LOG("Using X font %s\n", pattern);
246 /* Get information (height/name) for this font */
247 if (!(font.specific.xcb.info = xcb_query_font_reply(conn, info_cookie, NULL)))
248 errx(EXIT_FAILURE, "Could not load font \"%s\"", pattern);
250 /* Get the font table, if possible */
251 if (xcb_query_font_char_infos_length(font.specific.xcb.info) == 0)
252 font.specific.xcb.table = NULL;
254 font.specific.xcb.table = xcb_query_font_char_infos(font.specific.xcb.info);
256 /* Calculate the font height */
257 font.height = font.specific.xcb.info->font_ascent + font.specific.xcb.info->font_descent;
259 /* Set the font type and return successfully */
260 font.type = FONT_TYPE_XCB;
265 * Defines the font to be used for the forthcoming calls.
268 void set_font(i3Font *font) {
273 * Frees the resources taken by the current font. If no font was previously
274 * loaded, it simply returns.
277 void free_font(void) {
278 /* if there is no saved font, simply return */
279 if (savedFont == NULL)
282 free(savedFont->pattern);
283 switch (savedFont->type) {
287 case FONT_TYPE_XCB: {
288 /* Close the font and free the info */
289 xcb_close_font(conn, savedFont->specific.xcb.id);
290 if (savedFont->specific.xcb.info)
291 free(savedFont->specific.xcb.info);
295 case FONT_TYPE_PANGO:
296 /* Free the font description */
297 pango_font_description_free(savedFont->specific.pango_desc);
309 * Defines the colors to be used for the forthcoming draw_text calls.
312 void set_font_colors(xcb_gcontext_t gc, uint32_t foreground, uint32_t background) {
313 assert(savedFont != NULL);
315 switch (savedFont->type) {
319 case FONT_TYPE_XCB: {
320 /* Change the font and colors in the GC */
321 uint32_t mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
322 uint32_t values[] = {foreground, background, savedFont->specific.xcb.id};
323 xcb_change_gc(conn, gc, mask, values);
327 case FONT_TYPE_PANGO:
328 /* Save the foreground font */
329 pango_font_red = ((foreground >> 16) & 0xff) / 255.0;
330 pango_font_green = ((foreground >> 8) & 0xff) / 255.0;
331 pango_font_blue = (foreground & 0xff) / 255.0;
340 static int predict_text_width_xcb(const xcb_char2b_t *text, size_t text_len);
342 static void draw_text_xcb(const xcb_char2b_t *text, size_t text_len, xcb_drawable_t drawable,
343 xcb_gcontext_t gc, int x, int y, int max_width) {
344 /* X11 coordinates for fonts start at the baseline */
345 int pos_y = y + savedFont->specific.xcb.info->font_ascent;
347 /* The X11 protocol limits text drawing to 255 chars, so we may need
351 /* Calculate the size of this chunk */
352 int chunk_size = (text_len > 255 ? 255 : text_len);
353 const xcb_char2b_t *chunk = text + offset;
356 xcb_image_text_16(conn, chunk_size, drawable, gc, x, pos_y, chunk);
358 /* Advance the offset and length of the text to draw */
359 offset += chunk_size;
360 text_len -= chunk_size;
362 /* Check if we're done */
366 /* Advance pos_x based on the predicted text width */
367 x += predict_text_width_xcb(chunk, chunk_size);
372 * Draws text onto the specified X drawable (normally a pixmap) at the
373 * specified coordinates (from the top left corner of the leftmost, uppermost
374 * glyph) and using the provided gc.
376 * Text must be specified as an i3String.
379 void draw_text(i3String *text, xcb_drawable_t drawable,
380 xcb_gcontext_t gc, int x, int y, int max_width) {
381 assert(savedFont != NULL);
383 switch (savedFont->type) {
388 draw_text_xcb(i3string_as_ucs2(text), i3string_get_num_glyphs(text),
389 drawable, gc, x, y, max_width);
392 case FONT_TYPE_PANGO:
393 /* Render the text using Pango */
394 draw_text_pango(i3string_as_utf8(text), i3string_get_num_bytes(text),
395 drawable, x, y, max_width, i3string_is_markup(text));
404 * ASCII version of draw_text to print static strings.
407 void draw_text_ascii(const char *text, xcb_drawable_t drawable,
408 xcb_gcontext_t gc, int x, int y, int max_width) {
409 assert(savedFont != NULL);
411 switch (savedFont->type) {
415 case FONT_TYPE_XCB: {
416 size_t text_len = strlen(text);
417 if (text_len > 255) {
418 /* The text is too long to draw it directly to X */
419 i3String *str = i3string_from_utf8(text);
420 draw_text(str, drawable, gc, x, y, max_width);
423 /* X11 coordinates for fonts start at the baseline */
424 int pos_y = y + savedFont->specific.xcb.info->font_ascent;
426 xcb_image_text_8(conn, text_len, drawable, gc, x, pos_y, text);
431 case FONT_TYPE_PANGO:
432 /* Render the text using Pango */
433 draw_text_pango(text, strlen(text),
434 drawable, x, y, max_width, false);
442 static int xcb_query_text_width(const xcb_char2b_t *text, size_t text_len) {
443 /* Make the user know we’re using the slow path, but only once. */
444 static bool first_invocation = true;
445 if (first_invocation) {
446 fprintf(stderr, "Using slow code path for text extents\n");
447 first_invocation = false;
450 /* Query the text width */
451 xcb_generic_error_t *error;
452 xcb_query_text_extents_cookie_t cookie = xcb_query_text_extents(conn,
453 savedFont->specific.xcb.id, text_len, (xcb_char2b_t *)text);
454 xcb_query_text_extents_reply_t *reply = xcb_query_text_extents_reply(conn,
457 /* We return a safe estimate because a rendering error is better than
458 * a crash. Plus, the user will see the error in his log. */
459 fprintf(stderr, "Could not get text extents (X error code %d)\n",
461 return savedFont->specific.xcb.info->max_bounds.character_width * text_len;
464 int width = reply->overall_width;
469 static int predict_text_width_xcb(const xcb_char2b_t *input, size_t text_len) {
474 if (savedFont->specific.xcb.table == NULL) {
475 /* If we don't have a font table, fall back to querying the server */
476 width = xcb_query_text_width(input, text_len);
478 /* Save some pointers for convenience */
479 xcb_query_font_reply_t *font_info = savedFont->specific.xcb.info;
480 xcb_charinfo_t *font_table = savedFont->specific.xcb.table;
482 /* Calculate the width using the font table */
484 for (size_t i = 0; i < text_len; i++) {
485 xcb_charinfo_t *info;
486 int row = input[i].byte1;
487 int col = input[i].byte2;
489 if (row < font_info->min_byte1 ||
490 row > font_info->max_byte1 ||
491 col < font_info->min_char_or_byte2 ||
492 col > font_info->max_char_or_byte2)
495 /* Don't you ask me, how this one works… (Merovius) */
496 info = &font_table[((row - font_info->min_byte1) *
497 (font_info->max_char_or_byte2 - font_info->min_char_or_byte2 + 1)) +
498 (col - font_info->min_char_or_byte2)];
500 if (info->character_width != 0 ||
501 (info->right_side_bearing |
502 info->left_side_bearing |
504 info->descent) != 0) {
505 width += info->character_width;
514 * Predict the text width in pixels for the given text. Text must be
515 * specified as an i3String.
518 int predict_text_width(i3String *text) {
519 assert(savedFont != NULL);
521 switch (savedFont->type) {
526 return predict_text_width_xcb(i3string_as_ucs2(text), i3string_get_num_glyphs(text));
528 case FONT_TYPE_PANGO:
529 /* Calculate extents using Pango */
530 return predict_text_width_pango(i3string_as_utf8(text), i3string_get_num_bytes(text),
531 i3string_is_markup(text));