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