]> git.sur5r.net Git - i3/i3/blob - src/x.c
Merge pull request #3563 from CyberShadow/doc-mark-todo
[i3/i3] / src / x.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  * x.c: Interface to X11, transfers our in-memory state to X11 (see also
8  *      render.c). Basically a big state machine.
9  *
10  */
11 #include "all.h"
12
13 #ifndef MAX
14 #define MAX(x, y) ((x) > (y) ? (x) : (y))
15 #endif
16
17 xcb_window_t ewmh_window;
18
19 /* Stores the X11 window ID of the currently focused window */
20 xcb_window_t focused_id = XCB_NONE;
21
22 /* Because 'focused_id' might be reset to force input focus, we separately keep
23  * track of the X11 window ID to be able to always tell whether the focused
24  * window actually changed. */
25 static xcb_window_t last_focused = XCB_NONE;
26
27 /* Stores coordinates to warp mouse pointer to if set */
28 static Rect *warp_to;
29
30 /*
31  * Describes the X11 state we may modify (map state, position, window stack).
32  * There is one entry per container. The state represents the current situation
33  * as X11 sees it (with the exception of the order in the state_head CIRCLEQ,
34  * which represents the order that will be pushed to X11, while old_state_head
35  * represents the current order). It will be updated in x_push_changes().
36  *
37  */
38 typedef struct con_state {
39     xcb_window_t id;
40     bool mapped;
41     bool unmap_now;
42     bool child_mapped;
43     bool is_hidden;
44
45     /* The con for which this state is. */
46     Con *con;
47
48     /* For reparenting, we have a flag (need_reparent) and the X ID of the old
49      * frame this window was in. The latter is necessary because we need to
50      * ignore UnmapNotify events (by changing the window event mask). */
51     bool need_reparent;
52     xcb_window_t old_frame;
53
54     /* The container was child of floating container during the previous call of
55      * x_push_node(). This is used to remove the shape when the container is no
56      * longer floating. */
57     bool was_floating;
58
59     Rect rect;
60     Rect window_rect;
61
62     bool initial;
63
64     char *name;
65
66     CIRCLEQ_ENTRY(con_state)
67     state;
68
69     CIRCLEQ_ENTRY(con_state)
70     old_state;
71
72     TAILQ_ENTRY(con_state)
73     initial_mapping_order;
74 } con_state;
75
76 CIRCLEQ_HEAD(state_head, con_state)
77 state_head =
78     CIRCLEQ_HEAD_INITIALIZER(state_head);
79
80 CIRCLEQ_HEAD(old_state_head, con_state)
81 old_state_head =
82     CIRCLEQ_HEAD_INITIALIZER(old_state_head);
83
84 TAILQ_HEAD(initial_mapping_head, con_state)
85 initial_mapping_head =
86     TAILQ_HEAD_INITIALIZER(initial_mapping_head);
87
88 /*
89  * Returns the container state for the given frame. This function always
90  * returns a container state (otherwise, there is a bug in the code and the
91  * container state of a container for which x_con_init() was not called was
92  * requested).
93  *
94  */
95 static con_state *state_for_frame(xcb_window_t window) {
96     con_state *state;
97     CIRCLEQ_FOREACH(state, &state_head, state)
98     if (state->id == window)
99         return state;
100
101     /* TODO: better error handling? */
102     ELOG("No state found for window 0x%08x\n", window);
103     assert(false);
104     return NULL;
105 }
106
107 /*
108  * Changes the atoms on the root window and the windows themselves to properly
109  * reflect the current focus for ewmh compliance.
110  *
111  */
112 static void change_ewmh_focus(xcb_window_t new_focus, xcb_window_t old_focus) {
113     if (new_focus == old_focus) {
114         return;
115     }
116
117     ewmh_update_active_window(new_focus);
118
119     if (new_focus != XCB_WINDOW_NONE) {
120         ewmh_update_focused(new_focus, true);
121     }
122
123     if (old_focus != XCB_WINDOW_NONE) {
124         ewmh_update_focused(old_focus, false);
125     }
126 }
127
128 /*
129  * Initializes the X11 part for the given container. Called exactly once for
130  * every container from con_new().
131  *
132  */
133 void x_con_init(Con *con) {
134     /* TODO: maybe create the window when rendering first? we could then even
135      * get the initial geometry right */
136
137     uint32_t mask = 0;
138     uint32_t values[5];
139
140     xcb_visualid_t visual = get_visualid_by_depth(con->depth);
141     xcb_colormap_t win_colormap;
142     if (con->depth != root_depth) {
143         /* We need to create a custom colormap. */
144         win_colormap = xcb_generate_id(conn);
145         xcb_create_colormap(conn, XCB_COLORMAP_ALLOC_NONE, win_colormap, root, visual);
146         con->colormap = win_colormap;
147     } else {
148         /* Use the default colormap. */
149         win_colormap = colormap;
150         con->colormap = XCB_NONE;
151     }
152
153     /* We explicitly set a background color and border color (even though we
154      * don’t even have a border) because the X11 server requires us to when
155      * using 32 bit color depths, see
156      * https://stackoverflow.com/questions/3645632 */
157     mask |= XCB_CW_BACK_PIXEL;
158     values[0] = root_screen->black_pixel;
159
160     mask |= XCB_CW_BORDER_PIXEL;
161     values[1] = root_screen->black_pixel;
162
163     /* our own frames should not be managed */
164     mask |= XCB_CW_OVERRIDE_REDIRECT;
165     values[2] = 1;
166
167     /* see include/xcb.h for the FRAME_EVENT_MASK */
168     mask |= XCB_CW_EVENT_MASK;
169     values[3] = FRAME_EVENT_MASK & ~XCB_EVENT_MASK_ENTER_WINDOW;
170
171     mask |= XCB_CW_COLORMAP;
172     values[4] = win_colormap;
173
174     Rect dims = {-15, -15, 10, 10};
175     xcb_window_t frame_id = create_window(conn, dims, con->depth, visual, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCURSOR_CURSOR_POINTER, false, mask, values);
176     draw_util_surface_init(conn, &(con->frame), frame_id, get_visualtype_by_id(visual), dims.width, dims.height);
177     xcb_change_property(conn,
178                         XCB_PROP_MODE_REPLACE,
179                         con->frame.id,
180                         XCB_ATOM_WM_CLASS,
181                         XCB_ATOM_STRING,
182                         8,
183                         (strlen("i3-frame") + 1) * 2,
184                         "i3-frame\0i3-frame\0");
185
186     struct con_state *state = scalloc(1, sizeof(struct con_state));
187     state->id = con->frame.id;
188     state->mapped = false;
189     state->initial = true;
190     DLOG("Adding window 0x%08x to lists\n", state->id);
191     CIRCLEQ_INSERT_HEAD(&state_head, state, state);
192     CIRCLEQ_INSERT_HEAD(&old_state_head, state, old_state);
193     TAILQ_INSERT_TAIL(&initial_mapping_head, state, initial_mapping_order);
194     DLOG("adding new state for window id 0x%08x\n", state->id);
195 }
196
197 /*
198  * Re-initializes the associated X window state for this container. You have
199  * to call this when you assign a client to an empty container to ensure that
200  * its state gets updated correctly.
201  *
202  */
203 void x_reinit(Con *con) {
204     struct con_state *state;
205
206     if ((state = state_for_frame(con->frame.id)) == NULL) {
207         ELOG("window state not found\n");
208         return;
209     }
210
211     DLOG("resetting state %p to initial\n", state);
212     state->initial = true;
213     state->child_mapped = false;
214     state->con = con;
215     memset(&(state->window_rect), 0, sizeof(Rect));
216 }
217
218 /*
219  * Reparents the child window of the given container (necessary for sticky
220  * containers). The reparenting happens in the next call of x_push_changes().
221  *
222  */
223 void x_reparent_child(Con *con, Con *old) {
224     struct con_state *state;
225     if ((state = state_for_frame(con->frame.id)) == NULL) {
226         ELOG("window state for con not found\n");
227         return;
228     }
229
230     state->need_reparent = true;
231     state->old_frame = old->frame.id;
232 }
233
234 /*
235  * Moves a child window from Container src to Container dest.
236  *
237  */
238 void x_move_win(Con *src, Con *dest) {
239     struct con_state *state_src, *state_dest;
240
241     if ((state_src = state_for_frame(src->frame.id)) == NULL) {
242         ELOG("window state for src not found\n");
243         return;
244     }
245
246     if ((state_dest = state_for_frame(dest->frame.id)) == NULL) {
247         ELOG("window state for dest not found\n");
248         return;
249     }
250
251     state_dest->con = state_src->con;
252     state_src->con = NULL;
253
254     Rect zero = {0, 0, 0, 0};
255     if (memcmp(&(state_dest->window_rect), &(zero), sizeof(Rect)) == 0) {
256         memcpy(&(state_dest->window_rect), &(state_src->window_rect), sizeof(Rect));
257         DLOG("COPYING RECT\n");
258     }
259 }
260
261 static void _x_con_kill(Con *con) {
262     con_state *state;
263
264     if (con->colormap != XCB_NONE) {
265         xcb_free_colormap(conn, con->colormap);
266     }
267
268     draw_util_surface_free(conn, &(con->frame));
269     draw_util_surface_free(conn, &(con->frame_buffer));
270     xcb_free_pixmap(conn, con->frame_buffer.id);
271     state = state_for_frame(con->frame.id);
272     CIRCLEQ_REMOVE(&state_head, state, state);
273     CIRCLEQ_REMOVE(&old_state_head, state, old_state);
274     TAILQ_REMOVE(&initial_mapping_head, state, initial_mapping_order);
275     FREE(state->name);
276     free(state);
277
278     /* Invalidate focused_id to correctly focus new windows with the same ID */
279     if (con->frame.id == focused_id) {
280         focused_id = XCB_NONE;
281     }
282     if (con->frame.id == last_focused) {
283         last_focused = XCB_NONE;
284     }
285 }
286
287 /*
288  * Kills the window decoration associated with the given container.
289  *
290  */
291 void x_con_kill(Con *con) {
292     _x_con_kill(con);
293     xcb_destroy_window(conn, con->frame.id);
294 }
295
296 /*
297  * Completely reinitializes the container's frame, without destroying the old window.
298  *
299  */
300 void x_con_reframe(Con *con) {
301     _x_con_kill(con);
302     x_con_init(con);
303 }
304
305 /*
306  * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
307  *
308  */
309 bool window_supports_protocol(xcb_window_t window, xcb_atom_t atom) {
310     xcb_get_property_cookie_t cookie;
311     xcb_icccm_get_wm_protocols_reply_t protocols;
312     bool result = false;
313
314     cookie = xcb_icccm_get_wm_protocols(conn, window, A_WM_PROTOCOLS);
315     if (xcb_icccm_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
316         return false;
317
318     /* Check if the client’s protocols have the requested atom set */
319     for (uint32_t i = 0; i < protocols.atoms_len; i++)
320         if (protocols.atoms[i] == atom)
321             result = true;
322
323     xcb_icccm_get_wm_protocols_reply_wipe(&protocols);
324
325     return result;
326 }
327
328 /*
329  * Kills the given X11 window using WM_DELETE_WINDOW (if supported).
330  *
331  */
332 void x_window_kill(xcb_window_t window, kill_window_t kill_window) {
333     /* if this window does not support WM_DELETE_WINDOW, we kill it the hard way */
334     if (!window_supports_protocol(window, A_WM_DELETE_WINDOW)) {
335         if (kill_window == KILL_WINDOW) {
336             LOG("Killing specific window 0x%08x\n", window);
337             xcb_destroy_window(conn, window);
338         } else {
339             LOG("Killing the X11 client which owns window 0x%08x\n", window);
340             xcb_kill_client(conn, window);
341         }
342         return;
343     }
344
345     /* Every X11 event is 32 bytes long. Therefore, XCB will copy 32 bytes.
346      * In order to properly initialize these bytes, we allocate 32 bytes even
347      * though we only need less for an xcb_configure_notify_event_t */
348     void *event = scalloc(32, 1);
349     xcb_client_message_event_t *ev = event;
350
351     ev->response_type = XCB_CLIENT_MESSAGE;
352     ev->window = window;
353     ev->type = A_WM_PROTOCOLS;
354     ev->format = 32;
355     ev->data.data32[0] = A_WM_DELETE_WINDOW;
356     ev->data.data32[1] = XCB_CURRENT_TIME;
357
358     LOG("Sending WM_DELETE to the client\n");
359     xcb_send_event(conn, false, window, XCB_EVENT_MASK_NO_EVENT, (char *)ev);
360     xcb_flush(conn);
361     free(event);
362 }
363
364 static void x_draw_title_border(Con *con, struct deco_render_params *p) {
365     assert(con->parent != NULL);
366
367     Rect *dr = &(con->deco_rect);
368
369     /* Left */
370     draw_util_rectangle(&(con->parent->frame_buffer), p->color->border,
371                         dr->x, dr->y, 1, dr->height);
372
373     /* Right */
374     draw_util_rectangle(&(con->parent->frame_buffer), p->color->border,
375                         dr->x + dr->width - 1, dr->y, 1, dr->height);
376
377     /* Top */
378     draw_util_rectangle(&(con->parent->frame_buffer), p->color->border,
379                         dr->x, dr->y, dr->width, 1);
380
381     /* Bottom */
382     draw_util_rectangle(&(con->parent->frame_buffer), p->color->border,
383                         dr->x, dr->y + dr->height - 1, dr->width, 1);
384 }
385
386 static void x_draw_decoration_after_title(Con *con, struct deco_render_params *p) {
387     assert(con->parent != NULL);
388
389     Rect *dr = &(con->deco_rect);
390
391     /* Redraw the right border to cut off any text that went past it.
392      * This is necessary when the text was drawn using XCB since cutting text off
393      * automatically does not work there. For pango rendering, this isn't necessary. */
394     if (!font_is_pango()) {
395         /* We actually only redraw the far right two pixels as that is the
396          * distance we keep from the edge (not the entire border width).
397          * Redrawing the entire border would cause text to be cut off. */
398         draw_util_rectangle(&(con->parent->frame_buffer), p->color->background,
399                             dr->x + dr->width - 2 * logical_px(1),
400                             dr->y,
401                             2 * logical_px(1),
402                             dr->height);
403     }
404
405     /* Redraw the border. */
406     x_draw_title_border(con, p);
407 }
408
409 /*
410  * Get rectangles representing the border around the child window. Some borders
411  * are adjacent to the screen-edge and thus not returned. Return value is the
412  * number of rectangles.
413  *
414  */
415 static size_t x_get_border_rectangles(Con *con, xcb_rectangle_t rectangles[4]) {
416     size_t count = 0;
417     int border_style = con_border_style(con);
418
419     if (border_style != BS_NONE && con_is_leaf(con)) {
420         adjacent_t borders_to_hide = con_adjacent_borders(con) & config.hide_edge_borders;
421         Rect br = con_border_style_rect(con);
422
423         if (!(borders_to_hide & ADJ_LEFT_SCREEN_EDGE)) {
424             rectangles[count++] = (xcb_rectangle_t){
425                 .x = 0,
426                 .y = 0,
427                 .width = br.x,
428                 .height = con->rect.height,
429             };
430         }
431         if (!(borders_to_hide & ADJ_RIGHT_SCREEN_EDGE)) {
432             rectangles[count++] = (xcb_rectangle_t){
433                 .x = con->rect.width + (br.width + br.x),
434                 .y = 0,
435                 .width = -(br.width + br.x),
436                 .height = con->rect.height,
437             };
438         }
439         if (!(borders_to_hide & ADJ_LOWER_SCREEN_EDGE)) {
440             rectangles[count++] = (xcb_rectangle_t){
441                 .x = br.x,
442                 .y = con->rect.height + (br.height + br.y),
443                 .width = con->rect.width + br.width,
444                 .height = -(br.height + br.y),
445             };
446         }
447         /* pixel border have an additional line at the top */
448         if (border_style == BS_PIXEL && !(borders_to_hide & ADJ_UPPER_SCREEN_EDGE)) {
449             rectangles[count++] = (xcb_rectangle_t){
450                 .x = br.x,
451                 .y = 0,
452                 .width = con->rect.width + br.width,
453                 .height = br.y,
454             };
455         }
456     }
457
458     return count;
459 }
460
461 /*
462  * Draws the decoration of the given container onto its parent.
463  *
464  */
465 void x_draw_decoration(Con *con) {
466     Con *parent = con->parent;
467     bool leaf = con_is_leaf(con);
468
469     /* This code needs to run for:
470      *  • leaf containers
471      *  • non-leaf containers which are in a stacked/tabbed container
472      *
473      * It does not need to run for:
474      *  • direct children of outputs or dockareas
475      *  • floating containers (they don’t have a decoration)
476      */
477     if ((!leaf &&
478          parent->layout != L_STACKED &&
479          parent->layout != L_TABBED) ||
480         parent->type == CT_OUTPUT ||
481         parent->type == CT_DOCKAREA ||
482         con->type == CT_FLOATING_CON)
483         return;
484
485     /* Skip containers whose height is 0 (for example empty dockareas) */
486     if (con->rect.height == 0)
487         return;
488
489     /* Skip containers whose pixmap has not yet been created (can happen when
490      * decoration rendering happens recursively for a window for which
491      * x_push_node() was not yet called) */
492     if (leaf && con->frame_buffer.id == XCB_NONE)
493         return;
494
495     /* 1: build deco_params and compare with cache */
496     struct deco_render_params *p = scalloc(1, sizeof(struct deco_render_params));
497
498     /* find out which colors to use */
499     if (con->urgent)
500         p->color = &config.client.urgent;
501     else if (con == focused || con_inside_focused(con))
502         p->color = &config.client.focused;
503     else if (con == TAILQ_FIRST(&(parent->focus_head)))
504         p->color = &config.client.focused_inactive;
505     else
506         p->color = &config.client.unfocused;
507
508     p->border_style = con_border_style(con);
509
510     Rect *r = &(con->rect);
511     Rect *w = &(con->window_rect);
512     p->con_rect = (struct width_height){r->width, r->height};
513     p->con_window_rect = (struct width_height){w->width, w->height};
514     p->con_deco_rect = con->deco_rect;
515     p->background = config.client.background;
516     p->con_is_leaf = con_is_leaf(con);
517     p->parent_layout = con->parent->layout;
518
519     if (con->deco_render_params != NULL &&
520         (con->window == NULL || !con->window->name_x_changed) &&
521         !parent->pixmap_recreated &&
522         !con->pixmap_recreated &&
523         !con->mark_changed &&
524         memcmp(p, con->deco_render_params, sizeof(struct deco_render_params)) == 0) {
525         free(p);
526         goto copy_pixmaps;
527     }
528
529     Con *next = con;
530     while ((next = TAILQ_NEXT(next, nodes))) {
531         FREE(next->deco_render_params);
532     }
533
534     FREE(con->deco_render_params);
535     con->deco_render_params = p;
536
537     if (con->window != NULL && con->window->name_x_changed)
538         con->window->name_x_changed = false;
539
540     parent->pixmap_recreated = false;
541     con->pixmap_recreated = false;
542     con->mark_changed = false;
543
544     /* 2: draw the client.background, but only for the parts around the window_rect */
545     if (con->window != NULL) {
546         /* top area */
547         draw_util_rectangle(&(con->frame_buffer), config.client.background,
548                             0, 0, r->width, w->y);
549         /* bottom area */
550         draw_util_rectangle(&(con->frame_buffer), config.client.background,
551                             0, w->y + w->height, r->width, r->height - (w->y + w->height));
552         /* left area */
553         draw_util_rectangle(&(con->frame_buffer), config.client.background,
554                             0, 0, w->x, r->height);
555         /* right area */
556         draw_util_rectangle(&(con->frame_buffer), config.client.background,
557                             w->x + w->width, 0, r->width - (w->x + w->width), r->height);
558     }
559
560     /* 3: draw a rectangle in border color around the client */
561     if (p->border_style != BS_NONE && p->con_is_leaf) {
562         /* Fill the border. We don’t just fill the whole rectangle because some
563          * children are not freely resizable and we want their background color
564          * to "shine through". */
565         xcb_rectangle_t rectangles[4];
566         size_t rectangles_count = x_get_border_rectangles(con, rectangles);
567         for (size_t i = 0; i < rectangles_count; i++) {
568             draw_util_rectangle(&(con->frame_buffer), p->color->child_border,
569                                 rectangles[i].x,
570                                 rectangles[i].y,
571                                 rectangles[i].width,
572                                 rectangles[i].height);
573         }
574
575         /* Highlight the side of the border at which the next window will be
576          * opened if we are rendering a single window within a split container
577          * (which is undistinguishable from a single window outside a split
578          * container otherwise. */
579         Rect br = con_border_style_rect(con);
580         if (TAILQ_NEXT(con, nodes) == NULL &&
581             TAILQ_PREV(con, nodes_head, nodes) == NULL &&
582             con->parent->type != CT_FLOATING_CON) {
583             if (p->parent_layout == L_SPLITH) {
584                 draw_util_rectangle(&(con->frame_buffer), p->color->indicator,
585                                     r->width + (br.width + br.x), br.y, -(br.width + br.x), r->height + br.height);
586             } else if (p->parent_layout == L_SPLITV) {
587                 draw_util_rectangle(&(con->frame_buffer), p->color->indicator,
588                                     br.x, r->height + (br.height + br.y), r->width + br.width, -(br.height + br.y));
589             }
590         }
591     }
592
593     /* if this is a borderless/1pixel window, we don’t need to render the
594      * decoration. */
595     if (p->border_style != BS_NORMAL)
596         goto copy_pixmaps;
597
598     /* If the parent hasn't been set up yet, skip the decoration rendering
599      * for now. */
600     if (parent->frame_buffer.id == XCB_NONE)
601         goto copy_pixmaps;
602
603     /* For the first child, we clear the parent pixmap to ensure there's no
604      * garbage left on there. This is important to avoid tearing when using
605      * transparency. */
606     if (con == TAILQ_FIRST(&(con->parent->nodes_head))) {
607         draw_util_clear_surface(&(con->parent->frame_buffer), COLOR_TRANSPARENT);
608         FREE(con->parent->deco_render_params);
609     }
610
611     /* 4: paint the bar */
612     draw_util_rectangle(&(parent->frame_buffer), p->color->background,
613                         con->deco_rect.x, con->deco_rect.y, con->deco_rect.width, con->deco_rect.height);
614
615     /* 5: draw title border */
616     x_draw_title_border(con, p);
617
618     /* 6: draw the title */
619     int text_offset_y = (con->deco_rect.height - config.font.height) / 2;
620
621     const int title_padding = logical_px(2);
622     const int deco_width = (int)con->deco_rect.width;
623     int mark_width = 0;
624     if (config.show_marks && !TAILQ_EMPTY(&(con->marks_head))) {
625         char *formatted_mark = sstrdup("");
626         bool had_visible_mark = false;
627
628         mark_t *mark;
629         TAILQ_FOREACH(mark, &(con->marks_head), marks) {
630             if (mark->name[0] == '_')
631                 continue;
632             had_visible_mark = true;
633
634             char *buf;
635             sasprintf(&buf, "%s[%s]", formatted_mark, mark->name);
636             free(formatted_mark);
637             formatted_mark = buf;
638         }
639
640         if (had_visible_mark) {
641             i3String *mark = i3string_from_utf8(formatted_mark);
642             mark_width = predict_text_width(mark);
643
644             int mark_offset_x = (config.title_align == ALIGN_RIGHT)
645                                     ? title_padding
646                                     : deco_width - mark_width - title_padding;
647
648             draw_util_text(mark, &(parent->frame_buffer),
649                            p->color->text, p->color->background,
650                            con->deco_rect.x + mark_offset_x,
651                            con->deco_rect.y + text_offset_y, mark_width);
652             I3STRING_FREE(mark);
653
654             mark_width += title_padding;
655         }
656
657         FREE(formatted_mark);
658     }
659
660     i3String *title = NULL;
661     struct Window *win = con->window;
662     if (win == NULL) {
663         if (con->title_format == NULL) {
664             char *_title;
665             char *tree = con_get_tree_representation(con);
666             sasprintf(&_title, "i3: %s", tree);
667             free(tree);
668
669             title = i3string_from_utf8(_title);
670             FREE(_title);
671         } else {
672             title = con_parse_title_format(con);
673         }
674     } else {
675         title = con->title_format == NULL ? win->name : con_parse_title_format(con);
676     }
677     if (title == NULL) {
678         goto copy_pixmaps;
679     }
680
681     int title_offset_x;
682     switch (config.title_align) {
683         case ALIGN_LEFT:
684             /* (pad)[text    ](pad)[mark + its pad) */
685             title_offset_x = title_padding;
686             break;
687         case ALIGN_CENTER:
688             /* (pad)[  text  ](pad)[mark + its pad)
689              * To center the text inside its allocated space, the surface
690              * between the brackets, we use the formula
691              * (surface_width - predict_text_width) / 2
692              * where surface_width = deco_width - 2 * pad - mark_width
693              * so, offset = pad + (surface_width - predict_text_width) / 2 =
694              * = … = (deco_width - mark_width - predict_text_width) / 2 */
695             title_offset_x = max(title_padding, (deco_width - mark_width - predict_text_width(title)) / 2);
696             break;
697         case ALIGN_RIGHT:
698             /* [mark + its pad](pad)[    text](pad) */
699             title_offset_x = max(title_padding + mark_width, deco_width - title_padding - predict_text_width(title));
700             break;
701     }
702
703     draw_util_text(title, &(parent->frame_buffer),
704                    p->color->text, p->color->background,
705                    con->deco_rect.x + title_offset_x,
706                    con->deco_rect.y + text_offset_y,
707                    deco_width - mark_width - 2 * title_padding);
708
709     if (win == NULL || con->title_format != NULL) {
710         I3STRING_FREE(title);
711     }
712
713     x_draw_decoration_after_title(con, p);
714 copy_pixmaps:
715     draw_util_copy_surface(&(con->frame_buffer), &(con->frame), 0, 0, 0, 0, con->rect.width, con->rect.height);
716 }
717
718 /*
719  * Recursively calls x_draw_decoration. This cannot be done in x_push_node
720  * because x_push_node uses focus order to recurse (see the comment above)
721  * while drawing the decoration needs to happen in the actual order.
722  *
723  */
724 void x_deco_recurse(Con *con) {
725     Con *current;
726     bool leaf = TAILQ_EMPTY(&(con->nodes_head)) &&
727                 TAILQ_EMPTY(&(con->floating_head));
728     con_state *state = state_for_frame(con->frame.id);
729
730     if (!leaf) {
731         TAILQ_FOREACH(current, &(con->nodes_head), nodes)
732         x_deco_recurse(current);
733
734         TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
735         x_deco_recurse(current);
736
737         if (state->mapped) {
738             draw_util_copy_surface(&(con->frame_buffer), &(con->frame), 0, 0, 0, 0, con->rect.width, con->rect.height);
739         }
740     }
741
742     if ((con->type != CT_ROOT && con->type != CT_OUTPUT) &&
743         (!leaf || con->mapped))
744         x_draw_decoration(con);
745 }
746
747 /*
748  * Sets or removes the _NET_WM_STATE_HIDDEN property on con if necessary.
749  *
750  */
751 static void set_hidden_state(Con *con) {
752     if (con->window == NULL) {
753         return;
754     }
755
756     con_state *state = state_for_frame(con->frame.id);
757     bool should_be_hidden = con_is_hidden(con);
758     if (should_be_hidden == state->is_hidden)
759         return;
760
761     if (should_be_hidden) {
762         DLOG("setting _NET_WM_STATE_HIDDEN for con = %p\n", con);
763         xcb_add_property_atom(conn, con->window->id, A__NET_WM_STATE, A__NET_WM_STATE_HIDDEN);
764     } else {
765         DLOG("removing _NET_WM_STATE_HIDDEN for con = %p\n", con);
766         xcb_remove_property_atom(conn, con->window->id, A__NET_WM_STATE, A__NET_WM_STATE_HIDDEN);
767     }
768
769     state->is_hidden = should_be_hidden;
770 }
771
772 /*
773  * Set the container frame shape as the union of the window shape and the
774  * shape of the frame borders.
775  */
776 static void x_shape_frame(Con *con, xcb_shape_sk_t shape_kind) {
777     assert(con->window);
778
779     xcb_shape_combine(conn, XCB_SHAPE_SO_SET, shape_kind, shape_kind,
780                       con->frame.id,
781                       con->window_rect.x + con->border_width,
782                       con->window_rect.y + con->border_width,
783                       con->window->id);
784     xcb_rectangle_t rectangles[4];
785     size_t rectangles_count = x_get_border_rectangles(con, rectangles);
786     if (rectangles_count) {
787         xcb_shape_rectangles(conn, XCB_SHAPE_SO_UNION, shape_kind,
788                              XCB_CLIP_ORDERING_UNSORTED, con->frame.id,
789                              0, 0, rectangles_count, rectangles);
790     }
791 }
792
793 /*
794  * Reset the container frame shape.
795  */
796 static void x_unshape_frame(Con *con, xcb_shape_sk_t shape_kind) {
797     assert(con->window);
798
799     xcb_shape_mask(conn, XCB_SHAPE_SO_SET, shape_kind, con->frame.id, 0, 0, XCB_PIXMAP_NONE);
800 }
801
802 /*
803  * Shape or unshape container frame based on the con state.
804  */
805 static void set_shape_state(Con *con, bool need_reshape) {
806     if (!shape_supported || con->window == NULL) {
807         return;
808     }
809
810     struct con_state *state;
811     if ((state = state_for_frame(con->frame.id)) == NULL) {
812         ELOG("window state for con %p not found\n", con);
813         return;
814     }
815
816     if (need_reshape && con_is_floating(con)) {
817         /* We need to reshape the window frame only if it already has shape. */
818         if (con->window->shaped) {
819             x_shape_frame(con, XCB_SHAPE_SK_BOUNDING);
820         }
821         if (con->window->input_shaped) {
822             x_shape_frame(con, XCB_SHAPE_SK_INPUT);
823         }
824     }
825
826     if (state->was_floating && !con_is_floating(con)) {
827         /* Remove the shape when container is no longer floating. */
828         if (con->window->shaped) {
829             x_unshape_frame(con, XCB_SHAPE_SK_BOUNDING);
830         }
831         if (con->window->input_shaped) {
832             x_unshape_frame(con, XCB_SHAPE_SK_INPUT);
833         }
834     }
835 }
836
837 /*
838  * This function pushes the properties of each node of the layout tree to
839  * X11 if they have changed (like the map state, position of the window, …).
840  * It recursively traverses all children of the given node.
841  *
842  */
843 void x_push_node(Con *con) {
844     Con *current;
845     con_state *state;
846     Rect rect = con->rect;
847
848     //DLOG("Pushing changes for node %p / %s\n", con, con->name);
849     state = state_for_frame(con->frame.id);
850
851     if (state->name != NULL) {
852         DLOG("pushing name %s for con %p\n", state->name, con);
853
854         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->frame.id,
855                             XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, strlen(state->name), state->name);
856         FREE(state->name);
857     }
858
859     if (con->window == NULL) {
860         /* Calculate the height of all window decorations which will be drawn on to
861          * this frame. */
862         uint32_t max_y = 0, max_height = 0;
863         TAILQ_FOREACH(current, &(con->nodes_head), nodes) {
864             Rect *dr = &(current->deco_rect);
865             if (dr->y >= max_y && dr->height >= max_height) {
866                 max_y = dr->y;
867                 max_height = dr->height;
868             }
869         }
870         rect.height = max_y + max_height;
871         if (rect.height == 0)
872             con->mapped = false;
873     }
874
875     bool need_reshape = false;
876
877     /* reparent the child window (when the window was moved due to a sticky
878      * container) */
879     if (state->need_reparent && con->window != NULL) {
880         DLOG("Reparenting child window\n");
881
882         /* Temporarily set the event masks to XCB_NONE so that we won’t get
883          * UnmapNotify events (otherwise the handler would close the container).
884          * These events are generated automatically when reparenting. */
885         uint32_t values[] = {XCB_NONE};
886         xcb_change_window_attributes(conn, state->old_frame, XCB_CW_EVENT_MASK, values);
887         xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
888
889         xcb_reparent_window(conn, con->window->id, con->frame.id, 0, 0);
890
891         values[0] = FRAME_EVENT_MASK;
892         xcb_change_window_attributes(conn, state->old_frame, XCB_CW_EVENT_MASK, values);
893         values[0] = CHILD_EVENT_MASK;
894         xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
895
896         state->old_frame = XCB_NONE;
897         state->need_reparent = false;
898
899         con->ignore_unmap++;
900         DLOG("ignore_unmap for reparenting of con %p (win 0x%08x) is now %d\n",
901              con, con->window->id, con->ignore_unmap);
902
903         need_reshape = true;
904     }
905
906     /* We need to update shape when window frame dimensions is updated. */
907     need_reshape |= state->rect.width != rect.width ||
908                     state->rect.height != rect.height ||
909                     state->window_rect.width != con->window_rect.width ||
910                     state->window_rect.height != con->window_rect.height;
911
912     /* We need to set shape when container becomes floating. */
913     need_reshape |= con_is_floating(con) && !state->was_floating;
914
915     /* The pixmap of a borderless leaf container will not be used except
916      * for the titlebar in a stack or tabs (issue #1013). */
917     bool is_pixmap_needed = (con->border_style != BS_NONE ||
918                              !con_is_leaf(con) ||
919                              con->parent->layout == L_STACKED ||
920                              con->parent->layout == L_TABBED);
921
922     /* The root con and output cons will never require a pixmap. In particular for the
923      * __i3 output, this will likely not work anyway because it might be ridiculously
924      * large, causing an XCB_ALLOC error. */
925     if (con->type == CT_ROOT || con->type == CT_OUTPUT)
926         is_pixmap_needed = false;
927
928     bool fake_notify = false;
929     /* Set new position if rect changed (and if height > 0) or if the pixmap
930      * needs to be recreated */
931     if ((is_pixmap_needed && con->frame_buffer.id == XCB_NONE) || (memcmp(&(state->rect), &rect, sizeof(Rect)) != 0 &&
932                                                                    rect.height > 0)) {
933         /* We first create the new pixmap, then render to it, set it as the
934          * background and only afterwards change the window size. This reduces
935          * flickering. */
936
937         bool has_rect_changed = (state->rect.x != rect.x || state->rect.y != rect.y ||
938                                  state->rect.width != rect.width || state->rect.height != rect.height);
939
940         /* Check if the container has an unneeded pixmap left over from
941          * previously having a border or titlebar. */
942         if (!is_pixmap_needed && con->frame_buffer.id != XCB_NONE) {
943             draw_util_surface_free(conn, &(con->frame_buffer));
944             xcb_free_pixmap(conn, con->frame_buffer.id);
945             con->frame_buffer.id = XCB_NONE;
946         }
947
948         if (is_pixmap_needed && (has_rect_changed || con->frame_buffer.id == XCB_NONE)) {
949             if (con->frame_buffer.id == XCB_NONE) {
950                 con->frame_buffer.id = xcb_generate_id(conn);
951             } else {
952                 draw_util_surface_free(conn, &(con->frame_buffer));
953                 xcb_free_pixmap(conn, con->frame_buffer.id);
954             }
955
956             uint16_t win_depth = root_depth;
957             if (con->window)
958                 win_depth = con->window->depth;
959
960             /* Ensure we have valid dimensions for our surface. */
961             // TODO This is probably a bug in the condition above as we should never enter this path
962             //      for height == 0. Also, we should probably handle width == 0 the same way.
963             int width = MAX((int32_t)rect.width, 1);
964             int height = MAX((int32_t)rect.height, 1);
965
966             xcb_create_pixmap(conn, win_depth, con->frame_buffer.id, con->frame.id, width, height);
967             draw_util_surface_init(conn, &(con->frame_buffer), con->frame_buffer.id,
968                                    get_visualtype_by_id(get_visualid_by_depth(win_depth)), width, height);
969
970             /* For the graphics context, we disable GraphicsExposure events.
971              * Those will be sent when a CopyArea request cannot be fulfilled
972              * properly due to parts of the source being unmapped or otherwise
973              * unavailable. Since we always copy from pixmaps to windows, this
974              * is not a concern for us. */
975             xcb_change_gc(conn, con->frame_buffer.gc, XCB_GC_GRAPHICS_EXPOSURES, (uint32_t[]){0});
976
977             draw_util_surface_set_size(&(con->frame), width, height);
978             con->pixmap_recreated = true;
979
980             /* Don’t render the decoration for windows inside a stack which are
981              * not visible right now */
982             // TODO Should this work the same way for L_TABBED?
983             if (!con->parent ||
984                 con->parent->layout != L_STACKED ||
985                 TAILQ_FIRST(&(con->parent->focus_head)) == con)
986                 /* Render the decoration now to make the correct decoration visible
987                  * from the very first moment. Later calls will be cached, so this
988                  * doesn’t hurt performance. */
989                 x_deco_recurse(con);
990         }
991
992         DLOG("setting rect (%d, %d, %d, %d)\n", rect.x, rect.y, rect.width, rect.height);
993         /* flush to ensure that the following commands are sent in a single
994          * buffer and will be processed directly afterwards (the contents of a
995          * window get lost when resizing it, therefore we want to provide it as
996          * fast as possible) */
997         xcb_flush(conn);
998         xcb_set_window_rect(conn, con->frame.id, rect);
999         if (con->frame_buffer.id != XCB_NONE) {
1000             draw_util_copy_surface(&(con->frame_buffer), &(con->frame), 0, 0, 0, 0, con->rect.width, con->rect.height);
1001         }
1002         xcb_flush(conn);
1003
1004         memcpy(&(state->rect), &rect, sizeof(Rect));
1005         fake_notify = true;
1006     }
1007
1008     /* dito, but for child windows */
1009     if (con->window != NULL &&
1010         memcmp(&(state->window_rect), &(con->window_rect), sizeof(Rect)) != 0) {
1011         DLOG("setting window rect (%d, %d, %d, %d)\n",
1012              con->window_rect.x, con->window_rect.y, con->window_rect.width, con->window_rect.height);
1013         xcb_set_window_rect(conn, con->window->id, con->window_rect);
1014         memcpy(&(state->window_rect), &(con->window_rect), sizeof(Rect));
1015         fake_notify = true;
1016     }
1017
1018     set_shape_state(con, need_reshape);
1019
1020     /* Map if map state changed, also ensure that the child window
1021      * is changed if we are mapped and there is a new, unmapped child window.
1022      * Unmaps are handled in x_push_node_unmaps(). */
1023     if ((state->mapped != con->mapped || (con->window != NULL && !state->child_mapped)) &&
1024         con->mapped) {
1025         xcb_void_cookie_t cookie;
1026
1027         if (con->window != NULL) {
1028             /* Set WM_STATE_NORMAL because GTK applications don’t want to
1029              * drag & drop if we don’t. Also, xprop(1) needs it. */
1030             long data[] = {XCB_ICCCM_WM_STATE_NORMAL, XCB_NONE};
1031             xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
1032                                 A_WM_STATE, A_WM_STATE, 32, 2, data);
1033         }
1034
1035         uint32_t values[1];
1036         if (!state->child_mapped && con->window != NULL) {
1037             cookie = xcb_map_window(conn, con->window->id);
1038
1039             /* We are interested in EnterNotifys as soon as the window is
1040              * mapped */
1041             values[0] = CHILD_EVENT_MASK;
1042             xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
1043             DLOG("mapping child window (serial %d)\n", cookie.sequence);
1044             state->child_mapped = true;
1045         }
1046
1047         cookie = xcb_map_window(conn, con->frame.id);
1048
1049         values[0] = FRAME_EVENT_MASK;
1050         xcb_change_window_attributes(conn, con->frame.id, XCB_CW_EVENT_MASK, values);
1051
1052         /* copy the pixmap contents to the frame window immediately after mapping */
1053         if (con->frame_buffer.id != XCB_NONE) {
1054             draw_util_copy_surface(&(con->frame_buffer), &(con->frame), 0, 0, 0, 0, con->rect.width, con->rect.height);
1055         }
1056         xcb_flush(conn);
1057
1058         DLOG("mapping container %08x (serial %d)\n", con->frame.id, cookie.sequence);
1059         state->mapped = con->mapped;
1060     }
1061
1062     state->unmap_now = (state->mapped != con->mapped) && !con->mapped;
1063     state->was_floating = con_is_floating(con);
1064
1065     if (fake_notify) {
1066         DLOG("Sending fake configure notify\n");
1067         fake_absolute_configure_notify(con);
1068     }
1069
1070     set_hidden_state(con);
1071
1072     /* Handle all children and floating windows of this node. We recurse
1073      * in focus order to display the focused client in a stack first when
1074      * switching workspaces (reduces flickering). */
1075     TAILQ_FOREACH(current, &(con->focus_head), focused) {
1076         x_push_node(current);
1077     }
1078 }
1079
1080 /*
1081  * Same idea as in x_push_node(), but this function only unmaps windows. It is
1082  * necessary to split this up to handle new fullscreen clients properly: The
1083  * new window needs to be mapped and focus needs to be set *before* the
1084  * underlying windows are unmapped. Otherwise, focus will revert to the
1085  * PointerRoot and will then be set to the new window, generating unnecessary
1086  * FocusIn/FocusOut events.
1087  *
1088  */
1089 static void x_push_node_unmaps(Con *con) {
1090     Con *current;
1091     con_state *state;
1092
1093     //DLOG("Pushing changes (with unmaps) for node %p / %s\n", con, con->name);
1094     state = state_for_frame(con->frame.id);
1095
1096     /* map/unmap if map state changed, also ensure that the child window
1097      * is changed if we are mapped *and* in initial state (meaning the
1098      * container was empty before, but now got a child) */
1099     if (state->unmap_now) {
1100         xcb_void_cookie_t cookie;
1101         if (con->window != NULL) {
1102             /* Set WM_STATE_WITHDRAWN, it seems like Java apps need it */
1103             long data[] = {XCB_ICCCM_WM_STATE_WITHDRAWN, XCB_NONE};
1104             xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
1105                                 A_WM_STATE, A_WM_STATE, 32, 2, data);
1106         }
1107
1108         cookie = xcb_unmap_window(conn, con->frame.id);
1109         DLOG("unmapping container %p / %s (serial %d)\n", con, con->name, cookie.sequence);
1110         /* we need to increase ignore_unmap for this container (if it
1111          * contains a window) and for every window "under" this one which
1112          * contains a window */
1113         if (con->window != NULL) {
1114             con->ignore_unmap++;
1115             DLOG("ignore_unmap for con %p (frame 0x%08x) now %d\n", con, con->frame.id, con->ignore_unmap);
1116         }
1117         state->mapped = con->mapped;
1118     }
1119
1120     /* handle all children and floating windows of this node */
1121     TAILQ_FOREACH(current, &(con->nodes_head), nodes)
1122     x_push_node_unmaps(current);
1123
1124     TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
1125     x_push_node_unmaps(current);
1126 }
1127
1128 /*
1129  * Returns true if the given container is currently attached to its parent.
1130  *
1131  * TODO: Remove once #1185 has been fixed
1132  */
1133 static bool is_con_attached(Con *con) {
1134     if (con->parent == NULL)
1135         return false;
1136
1137     Con *current;
1138     TAILQ_FOREACH(current, &(con->parent->nodes_head), nodes) {
1139         if (current == con)
1140             return true;
1141     }
1142
1143     return false;
1144 }
1145
1146 /*
1147  * Pushes all changes (state of each node, see x_push_node() and the window
1148  * stack) to X11.
1149  *
1150  * NOTE: We need to push the stack first so that the windows have the correct
1151  * stacking order. This is relevant for workspace switching where we map the
1152  * windows because mapping may generate EnterNotify events. When they are
1153  * generated in the wrong order, this will cause focus problems when switching
1154  * workspaces.
1155  *
1156  */
1157 void x_push_changes(Con *con) {
1158     con_state *state;
1159     xcb_query_pointer_cookie_t pointercookie;
1160
1161     /* If we need to warp later, we request the pointer position as soon as possible */
1162     if (warp_to) {
1163         pointercookie = xcb_query_pointer(conn, root);
1164     }
1165
1166     DLOG("-- PUSHING WINDOW STACK --\n");
1167     //DLOG("Disabling EnterNotify\n");
1168     /* We need to keep SubstructureRedirect around, otherwise clients can send
1169      * ConfigureWindow requests and get them applied directly instead of having
1170      * them become ConfigureRequests that i3 handles. */
1171     uint32_t values[1] = {XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT};
1172     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1173         if (state->mapped)
1174             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1175     }
1176     //DLOG("Done, EnterNotify disabled\n");
1177     bool order_changed = false;
1178     bool stacking_changed = false;
1179
1180     /* count first, necessary to (re)allocate memory for the bottom-to-top
1181      * stack afterwards */
1182     int cnt = 0;
1183     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state)
1184     if (con_has_managed_window(state->con))
1185         cnt++;
1186
1187     /* The bottom-to-top window stack of all windows which are managed by i3.
1188      * Used for x_get_window_stack(). */
1189     static xcb_window_t *client_list_windows = NULL;
1190     static int client_list_count = 0;
1191
1192     if (cnt != client_list_count) {
1193         client_list_windows = srealloc(client_list_windows, sizeof(xcb_window_t) * cnt);
1194         client_list_count = cnt;
1195     }
1196
1197     xcb_window_t *walk = client_list_windows;
1198
1199     /* X11 correctly represents the stack if we push it from bottom to top */
1200     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1201         if (con_has_managed_window(state->con))
1202             memcpy(walk++, &(state->con->window->id), sizeof(xcb_window_t));
1203
1204         //DLOG("stack: 0x%08x\n", state->id);
1205         con_state *prev = CIRCLEQ_PREV(state, state);
1206         con_state *old_prev = CIRCLEQ_PREV(state, old_state);
1207         if (prev != old_prev)
1208             order_changed = true;
1209         if ((state->initial || order_changed) && prev != CIRCLEQ_END(&state_head)) {
1210             stacking_changed = true;
1211             //DLOG("Stacking 0x%08x above 0x%08x\n", prev->id, state->id);
1212             uint32_t mask = 0;
1213             mask |= XCB_CONFIG_WINDOW_SIBLING;
1214             mask |= XCB_CONFIG_WINDOW_STACK_MODE;
1215             uint32_t values[] = {state->id, XCB_STACK_MODE_ABOVE};
1216
1217             xcb_configure_window(conn, prev->id, mask, values);
1218         }
1219         state->initial = false;
1220     }
1221
1222     /* If we re-stacked something (or a new window appeared), we need to update
1223      * the _NET_CLIENT_LIST and _NET_CLIENT_LIST_STACKING hints */
1224     if (stacking_changed) {
1225         DLOG("Client list changed (%i clients)\n", cnt);
1226         ewmh_update_client_list_stacking(client_list_windows, client_list_count);
1227
1228         walk = client_list_windows;
1229
1230         /* reorder by initial mapping */
1231         TAILQ_FOREACH(state, &initial_mapping_head, initial_mapping_order) {
1232             if (con_has_managed_window(state->con))
1233                 *walk++ = state->con->window->id;
1234         }
1235
1236         ewmh_update_client_list(client_list_windows, client_list_count);
1237     }
1238
1239     DLOG("PUSHING CHANGES\n");
1240     x_push_node(con);
1241
1242     if (warp_to) {
1243         xcb_query_pointer_reply_t *pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL);
1244         if (!pointerreply) {
1245             ELOG("Could not query pointer position, not warping pointer\n");
1246         } else {
1247             int mid_x = warp_to->x + (warp_to->width / 2);
1248             int mid_y = warp_to->y + (warp_to->height / 2);
1249
1250             Output *current = get_output_containing(pointerreply->root_x, pointerreply->root_y);
1251             Output *target = get_output_containing(mid_x, mid_y);
1252             if (current != target) {
1253                 /* Ignore MotionNotify events generated by warping */
1254                 xcb_change_window_attributes(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT});
1255                 xcb_warp_pointer(conn, XCB_NONE, root, 0, 0, 0, 0, mid_x, mid_y);
1256                 xcb_change_window_attributes(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
1257             }
1258
1259             free(pointerreply);
1260         }
1261         warp_to = NULL;
1262     }
1263
1264     //DLOG("Re-enabling EnterNotify\n");
1265     values[0] = FRAME_EVENT_MASK;
1266     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1267         if (state->mapped)
1268             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1269     }
1270     //DLOG("Done, EnterNotify re-enabled\n");
1271
1272     x_deco_recurse(con);
1273
1274     xcb_window_t to_focus = focused->frame.id;
1275     if (focused->window != NULL)
1276         to_focus = focused->window->id;
1277
1278     if (focused_id != to_focus) {
1279         if (!focused->mapped) {
1280             DLOG("Not updating focus (to %p / %s), focused window is not mapped.\n", focused, focused->name);
1281             /* Invalidate focused_id to correctly focus new windows with the same ID */
1282             focused_id = XCB_NONE;
1283         } else {
1284             if (focused->window != NULL &&
1285                 focused->window->needs_take_focus &&
1286                 focused->window->doesnt_accept_focus) {
1287                 DLOG("Updating focus by sending WM_TAKE_FOCUS to window 0x%08x (focused: %p / %s)\n",
1288                      to_focus, focused, focused->name);
1289                 send_take_focus(to_focus, last_timestamp);
1290
1291                 change_ewmh_focus((con_has_managed_window(focused) ? focused->window->id : XCB_WINDOW_NONE), last_focused);
1292
1293                 if (to_focus != last_focused && is_con_attached(focused))
1294                     ipc_send_window_event("focus", focused);
1295             } else {
1296                 DLOG("Updating focus (focused: %p / %s) to X11 window 0x%08x\n", focused, focused->name, to_focus);
1297                 /* We remove XCB_EVENT_MASK_FOCUS_CHANGE from the event mask to get
1298                  * no focus change events for our own focus changes. We only want
1299                  * these generated by the clients. */
1300                 if (focused->window != NULL) {
1301                     values[0] = CHILD_EVENT_MASK & ~(XCB_EVENT_MASK_FOCUS_CHANGE);
1302                     xcb_change_window_attributes(conn, focused->window->id, XCB_CW_EVENT_MASK, values);
1303                 }
1304                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, to_focus, last_timestamp);
1305                 if (focused->window != NULL) {
1306                     values[0] = CHILD_EVENT_MASK;
1307                     xcb_change_window_attributes(conn, focused->window->id, XCB_CW_EVENT_MASK, values);
1308                 }
1309
1310                 change_ewmh_focus((con_has_managed_window(focused) ? focused->window->id : XCB_WINDOW_NONE), last_focused);
1311
1312                 if (to_focus != XCB_NONE && to_focus != last_focused && focused->window != NULL && is_con_attached(focused))
1313                     ipc_send_window_event("focus", focused);
1314             }
1315
1316             focused_id = last_focused = to_focus;
1317         }
1318     }
1319
1320     if (focused_id == XCB_NONE) {
1321         /* If we still have no window to focus, we focus the EWMH window instead. We use this rather than the
1322          * root window in order to avoid an X11 fallback mechanism causing a ghosting effect (see #1378). */
1323         DLOG("Still no window focused, better set focus to the EWMH support window (%d)\n", ewmh_window);
1324         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, ewmh_window, last_timestamp);
1325         change_ewmh_focus(XCB_WINDOW_NONE, last_focused);
1326
1327         focused_id = ewmh_window;
1328         last_focused = XCB_NONE;
1329     }
1330
1331     xcb_flush(conn);
1332     DLOG("ENDING CHANGES\n");
1333
1334     /* Disable EnterWindow events for windows which will be unmapped in
1335      * x_push_node_unmaps() now. Unmapping windows happens when switching
1336      * workspaces. We want to avoid getting EnterNotifies during that phase
1337      * because they would screw up our focus. One of these cases is having a
1338      * stack with two windows. If the first window is focused and gets
1339      * unmapped, the second one appears under the cursor and therefore gets an
1340      * EnterNotify event. */
1341     values[0] = FRAME_EVENT_MASK & ~XCB_EVENT_MASK_ENTER_WINDOW;
1342     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1343         if (!state->unmap_now)
1344             continue;
1345         xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1346     }
1347
1348     /* Push all pending unmaps */
1349     x_push_node_unmaps(con);
1350
1351     /* save the current stack as old stack */
1352     CIRCLEQ_FOREACH(state, &state_head, state) {
1353         CIRCLEQ_REMOVE(&old_state_head, state, old_state);
1354         CIRCLEQ_INSERT_TAIL(&old_state_head, state, old_state);
1355     }
1356     //CIRCLEQ_FOREACH(state, &old_state_head, old_state) {
1357     //    DLOG("old stack: 0x%08x\n", state->id);
1358     //}
1359
1360     xcb_flush(conn);
1361 }
1362
1363 /*
1364  * Raises the specified container in the internal stack of X windows. The
1365  * next call to x_push_changes() will make the change visible in X11.
1366  *
1367  */
1368 void x_raise_con(Con *con) {
1369     con_state *state;
1370     state = state_for_frame(con->frame.id);
1371     //DLOG("raising in new stack: %p / %s / %s / xid %08x\n", con, con->name, con->window ? con->window->name_json : "", state->id);
1372
1373     CIRCLEQ_REMOVE(&state_head, state, state);
1374     CIRCLEQ_INSERT_HEAD(&state_head, state, state);
1375 }
1376
1377 /*
1378  * Sets the WM_NAME property (so, no UTF8, but used only for debugging anyways)
1379  * of the given name. Used for properly tagging the windows for easily spotting
1380  * i3 windows in xwininfo -root -all.
1381  *
1382  */
1383 void x_set_name(Con *con, const char *name) {
1384     struct con_state *state;
1385
1386     if ((state = state_for_frame(con->frame.id)) == NULL) {
1387         ELOG("window state not found\n");
1388         return;
1389     }
1390
1391     FREE(state->name);
1392     state->name = sstrdup(name);
1393 }
1394
1395 /*
1396  * Set up the I3_SHMLOG_PATH atom.
1397  *
1398  */
1399 void update_shmlog_atom(void) {
1400     if (*shmlogname == '\0') {
1401         xcb_delete_property(conn, root, A_I3_SHMLOG_PATH);
1402     } else {
1403         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
1404                             A_I3_SHMLOG_PATH, A_UTF8_STRING, 8,
1405                             strlen(shmlogname), shmlogname);
1406     }
1407 }
1408
1409 /*
1410  * Sets up i3 specific atoms (I3_SOCKET_PATH and I3_CONFIG_PATH)
1411  *
1412  */
1413 void x_set_i3_atoms(void) {
1414     pid_t pid = getpid();
1415     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_SOCKET_PATH, A_UTF8_STRING, 8,
1416                         (current_socketpath == NULL ? 0 : strlen(current_socketpath)),
1417                         current_socketpath);
1418     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_PID, XCB_ATOM_CARDINAL, 32, 1, &pid);
1419     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_CONFIG_PATH, A_UTF8_STRING, 8,
1420                         strlen(current_configpath), current_configpath);
1421     update_shmlog_atom();
1422 }
1423
1424 /*
1425  * Set warp_to coordinates.  This will trigger on the next call to
1426  * x_push_changes().
1427  *
1428  */
1429 void x_set_warp_to(Rect *rect) {
1430     if (config.mouse_warping != POINTER_WARPING_NONE)
1431         warp_to = rect;
1432 }
1433
1434 /*
1435  * Applies the given mask to the event mask of every i3 window decoration X11
1436  * window. This is useful to disable EnterNotify while resizing so that focus
1437  * is untouched.
1438  *
1439  */
1440 void x_mask_event_mask(uint32_t mask) {
1441     uint32_t values[] = {FRAME_EVENT_MASK & mask};
1442
1443     con_state *state;
1444     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1445         if (state->mapped)
1446             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1447     }
1448 }
1449
1450 /*
1451  * Enables or disables nonrectangular shape of the container frame.
1452  */
1453 void x_set_shape(Con *con, xcb_shape_sk_t kind, bool enable) {
1454     struct con_state *state;
1455     if ((state = state_for_frame(con->frame.id)) == NULL) {
1456         ELOG("window state for con %p not found\n", con);
1457         return;
1458     }
1459
1460     switch (kind) {
1461         case XCB_SHAPE_SK_BOUNDING:
1462             con->window->shaped = enable;
1463             break;
1464         case XCB_SHAPE_SK_INPUT:
1465             con->window->input_shaped = enable;
1466             break;
1467         default:
1468             ELOG("Received unknown shape event kind for con %p. This is a bug.\n",
1469                  con);
1470             return;
1471     }
1472
1473     if (con_is_floating(con)) {
1474         if (enable) {
1475             x_shape_frame(con, kind);
1476         } else {
1477             x_unshape_frame(con, kind);
1478         }
1479
1480         xcb_flush(conn);
1481     }
1482 }