]> git.sur5r.net Git - i3/i3/blob - src/x.c
Merge branch 'master' into next
[i3/i3] / src / x.c
1 #undef I3__FILE__
2 #define I3__FILE__ "x.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * x.c: Interface to X11, transfers our in-memory state to X11 (see also
10  *      render.c). Basically a big state machine.
11  *
12  */
13 #include "all.h"
14
15 /* Stores the X11 window ID of the currently focused window */
16 xcb_window_t focused_id = XCB_NONE;
17
18 /* The bottom-to-top window stack of all windows which are managed by i3.
19  * Used for x_get_window_stack(). */
20 static xcb_window_t *btt_stack;
21 static int btt_stack_num;
22
23 /* Stores coordinates to warp mouse pointer to if set */
24 static Rect *warp_to;
25
26 /*
27  * Describes the X11 state we may modify (map state, position, window stack).
28  * There is one entry per container. The state represents the current situation
29  * as X11 sees it (with the exception of the order in the state_head CIRCLEQ,
30  * which represents the order that will be pushed to X11, while old_state_head
31  * represents the current order). It will be updated in x_push_changes().
32  *
33  */
34 typedef struct con_state {
35     xcb_window_t id;
36     bool mapped;
37     bool unmap_now;
38     bool child_mapped;
39     bool above_all;
40
41     /** The con for which this state is. */
42     Con *con;
43
44     /* For reparenting, we have a flag (need_reparent) and the X ID of the old
45      * frame this window was in. The latter is necessary because we need to
46      * ignore UnmapNotify events (by changing the window event mask). */
47     bool need_reparent;
48     xcb_window_t old_frame;
49
50     Rect rect;
51     Rect window_rect;
52
53     bool initial;
54
55     char *name;
56
57     CIRCLEQ_ENTRY(con_state) state;
58     CIRCLEQ_ENTRY(con_state) old_state;
59 } con_state;
60
61 CIRCLEQ_HEAD(state_head, con_state) state_head =
62     CIRCLEQ_HEAD_INITIALIZER(state_head);
63
64 CIRCLEQ_HEAD(old_state_head, con_state) old_state_head =
65     CIRCLEQ_HEAD_INITIALIZER(old_state_head);
66
67 /*
68  * Returns the container state for the given frame. This function always
69  * returns a container state (otherwise, there is a bug in the code and the
70  * container state of a container for which x_con_init() was not called was
71  * requested).
72  *
73  */
74 static con_state *state_for_frame(xcb_window_t window) {
75     con_state *state;
76     CIRCLEQ_FOREACH(state, &state_head, state)
77         if (state->id == window)
78             return state;
79
80     /* TODO: better error handling? */
81     ELOG("No state found\n");
82     assert(false);
83     return NULL;
84 }
85
86 /*
87  * Initializes the X11 part for the given container. Called exactly once for
88  * every container from con_new().
89  *
90  */
91 void x_con_init(Con *con, uint16_t depth) {
92     /* TODO: maybe create the window when rendering first? we could then even
93      * get the initial geometry right */
94
95     uint32_t mask = 0;
96     uint32_t values[5];
97
98     xcb_visualid_t visual = XCB_COPY_FROM_PARENT;
99     xcb_colormap_t win_colormap = XCB_NONE;
100     if (depth != root_depth && depth != XCB_COPY_FROM_PARENT) {
101         /* For custom visuals, we need to create a colormap before creating
102          * this window. It will be freed directly after creating the window. */
103         visual = get_visualid_by_depth(depth);
104         win_colormap = xcb_generate_id(conn);
105         xcb_create_colormap_checked(conn, XCB_COLORMAP_ALLOC_NONE, win_colormap, root, visual);
106
107         /* We explicitly set a background color and border color (even though we
108          * don’t even have a border) because the X11 server requires us to when
109          * using 32 bit color depths, see
110          * http://stackoverflow.com/questions/3645632 */
111         mask |= XCB_CW_BACK_PIXEL;
112         values[0] = root_screen->black_pixel;
113
114         mask |= XCB_CW_BORDER_PIXEL;
115         values[1] = root_screen->black_pixel;
116
117         /* our own frames should not be managed */
118         mask |= XCB_CW_OVERRIDE_REDIRECT;
119         values[2] = 1;
120
121         /* see include/xcb.h for the FRAME_EVENT_MASK */
122         mask |= XCB_CW_EVENT_MASK;
123         values[3] = FRAME_EVENT_MASK & ~XCB_EVENT_MASK_ENTER_WINDOW;
124
125         mask |= XCB_CW_COLORMAP;
126         values[4] = win_colormap;
127     } else {
128         /* our own frames should not be managed */
129         mask = XCB_CW_OVERRIDE_REDIRECT;
130         values[0] = 1;
131
132         /* see include/xcb.h for the FRAME_EVENT_MASK */
133         mask |= XCB_CW_EVENT_MASK;
134         values[1] = FRAME_EVENT_MASK & ~XCB_EVENT_MASK_ENTER_WINDOW;
135
136         mask |= XCB_CW_COLORMAP;
137         values[2] = colormap;
138     }
139
140     Rect dims = { -15, -15, 10, 10 };
141     con->frame = create_window(conn, dims, depth, visual, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCURSOR_CURSOR_POINTER, false, mask, values);
142
143     if (win_colormap != XCB_NONE)
144         xcb_free_colormap(conn, win_colormap);
145
146     struct con_state *state = scalloc(sizeof(struct con_state));
147     state->id = con->frame;
148     state->mapped = false;
149     state->initial = true;
150     CIRCLEQ_INSERT_HEAD(&state_head, state, state);
151     CIRCLEQ_INSERT_HEAD(&old_state_head, state, old_state);
152     DLOG("adding new state for window id 0x%08x\n", state->id);
153 }
154
155 /*
156  * Re-initializes the associated X window state for this container. You have
157  * to call this when you assign a client to an empty container to ensure that
158  * its state gets updated correctly.
159  *
160  */
161 void x_reinit(Con *con) {
162     struct con_state *state;
163
164     if ((state = state_for_frame(con->frame)) == NULL) {
165         ELOG("window state not found\n");
166         return;
167     }
168
169     DLOG("resetting state %p to initial\n", state);
170     state->initial = true;
171     state->child_mapped = false;
172     state->con = con;
173     memset(&(state->window_rect), 0, sizeof(Rect));
174 }
175
176 /*
177  * Reparents the child window of the given container (necessary for sticky
178  * containers). The reparenting happens in the next call of x_push_changes().
179  *
180  */
181 void x_reparent_child(Con *con, Con *old) {
182     struct con_state *state;
183     if ((state = state_for_frame(con->frame)) == NULL) {
184         ELOG("window state for con not found\n");
185         return;
186     }
187
188     state->need_reparent = true;
189     state->old_frame = old->frame;
190 }
191
192 /*
193  * Moves a child window from Container src to Container dest.
194  *
195  */
196 void x_move_win(Con *src, Con *dest) {
197     struct con_state *state_src, *state_dest;
198
199     if ((state_src = state_for_frame(src->frame)) == NULL) {
200         ELOG("window state for src not found\n");
201         return;
202     }
203
204     if ((state_dest = state_for_frame(dest->frame)) == NULL) {
205         ELOG("window state for dest not found\n");
206         return;
207     }
208
209     state_dest->con = state_src->con;
210     state_src->con = NULL;
211
212     Rect zero = { 0, 0, 0, 0 };
213     if (memcmp(&(state_dest->window_rect), &(zero), sizeof(Rect)) == 0) {
214         memcpy(&(state_dest->window_rect), &(state_src->window_rect), sizeof(Rect));
215         DLOG("COPYING RECT\n");
216     }
217 }
218
219 /*
220  * Kills the window decoration associated with the given container.
221  *
222  */
223 void x_con_kill(Con *con) {
224     con_state *state;
225
226     xcb_destroy_window(conn, con->frame);
227     xcb_free_pixmap(conn, con->pixmap);
228     xcb_free_gc(conn, con->pm_gc);
229     state = state_for_frame(con->frame);
230     CIRCLEQ_REMOVE(&state_head, state, state);
231     CIRCLEQ_REMOVE(&old_state_head, state, old_state);
232     FREE(state->name);
233     free(state);
234
235     /* Invalidate focused_id to correctly focus new windows with the same ID */
236     focused_id = XCB_NONE;
237 }
238
239 /*
240  * Returns true if the client supports the given protocol atom (like WM_DELETE_WINDOW)
241  *
242  */
243 bool window_supports_protocol(xcb_window_t window, xcb_atom_t atom) {
244     xcb_get_property_cookie_t cookie;
245     xcb_icccm_get_wm_protocols_reply_t protocols;
246     bool result = false;
247
248     cookie = xcb_icccm_get_wm_protocols(conn, window, A_WM_PROTOCOLS);
249     if (xcb_icccm_get_wm_protocols_reply(conn, cookie, &protocols, NULL) != 1)
250         return false;
251
252     /* Check if the client’s protocols have the requested atom set */
253     for (uint32_t i = 0; i < protocols.atoms_len; i++)
254         if (protocols.atoms[i] == atom)
255             result = true;
256
257     xcb_icccm_get_wm_protocols_reply_wipe(&protocols);
258
259     return result;
260 }
261
262 /*
263  * Kills the given X11 window using WM_DELETE_WINDOW (if supported).
264  *
265  */
266 void x_window_kill(xcb_window_t window, kill_window_t kill_window) {
267     /* if this window does not support WM_DELETE_WINDOW, we kill it the hard way */
268     if (!window_supports_protocol(window, A_WM_DELETE_WINDOW)) {
269         if (kill_window == KILL_WINDOW) {
270             LOG("Killing specific window 0x%08x\n", window);
271             xcb_destroy_window(conn, window);
272         } else {
273             LOG("Killing the X11 client which owns window 0x%08x\n", window);
274             xcb_kill_client(conn, window);
275         }
276         return;
277     }
278
279     /* Every X11 event is 32 bytes long. Therefore, XCB will copy 32 bytes.
280      * In order to properly initialize these bytes, we allocate 32 bytes even
281      * though we only need less for an xcb_configure_notify_event_t */
282     void *event = scalloc(32);
283     xcb_client_message_event_t *ev = event;
284
285     ev->response_type = XCB_CLIENT_MESSAGE;
286     ev->window = window;
287     ev->type = A_WM_PROTOCOLS;
288     ev->format = 32;
289     ev->data.data32[0] = A_WM_DELETE_WINDOW;
290     ev->data.data32[1] = XCB_CURRENT_TIME;
291
292     LOG("Sending WM_DELETE to the client\n");
293     xcb_send_event(conn, false, window, XCB_EVENT_MASK_NO_EVENT, (char*)ev);
294     xcb_flush(conn);
295     free(event);
296 }
297
298 /*
299  * Draws the decoration of the given container onto its parent.
300  *
301  */
302 void x_draw_decoration(Con *con) {
303     Con *parent = con->parent;
304     bool leaf = con_is_leaf(con);
305
306     /* This code needs to run for:
307      *  • leaf containers
308      *  • non-leaf containers which are in a stacked/tabbed container
309      *
310      * It does not need to run for:
311      *  • direct children of outputs or dockareas
312      *  • floating containers (they don’t have a decoration)
313      */
314     if ((!leaf &&
315          parent->layout != L_STACKED &&
316          parent->layout != L_TABBED) ||
317         parent->type == CT_OUTPUT ||
318         parent->type == CT_DOCKAREA ||
319         con->type == CT_FLOATING_CON)
320         return;
321
322     /* Skip containers whose height is 0 (for example empty dockareas) */
323     if (con->rect.height == 0)
324         return;
325
326     /* Skip containers whose pixmap has not yet been created (can happen when
327      * decoration rendering happens recursively for a window for which
328      * x_push_node() was not yet called) */
329     if (leaf && con->pixmap == XCB_NONE)
330         return;
331
332     /* 1: build deco_params and compare with cache */
333     struct deco_render_params *p = scalloc(sizeof(struct deco_render_params));
334
335     /* find out which colors to use */
336     if (con->urgent)
337         p->color = &config.client.urgent;
338     else if (con == focused || con_inside_focused(con))
339         p->color = &config.client.focused;
340     else if (con == TAILQ_FIRST(&(parent->focus_head)))
341         p->color = &config.client.focused_inactive;
342     else
343         p->color = &config.client.unfocused;
344
345     p->border_style = con_border_style(con);
346
347     Rect *r = &(con->rect);
348     Rect *w = &(con->window_rect);
349     p->con_rect = (struct width_height){ r->width, r->height };
350     p->con_window_rect = (struct width_height){ w->width, w->height };
351     p->con_deco_rect = con->deco_rect;
352     p->background = config.client.background;
353     p->con_is_leaf = con_is_leaf(con);
354     p->parent_layout = con->parent->layout;
355
356     if (con->deco_render_params != NULL &&
357         (con->window == NULL || !con->window->name_x_changed) &&
358         !parent->pixmap_recreated &&
359         !con->pixmap_recreated &&
360         memcmp(p, con->deco_render_params, sizeof(struct deco_render_params)) == 0) {
361         free(p);
362         goto copy_pixmaps;
363     }
364
365     Con *next = con;
366     while ((next = TAILQ_NEXT(next, nodes))) {
367         FREE(next->deco_render_params);
368     }
369
370     FREE(con->deco_render_params);
371     con->deco_render_params = p;
372
373     if (con->window != NULL && con->window->name_x_changed)
374         con->window->name_x_changed = false;
375
376     parent->pixmap_recreated = false;
377     con->pixmap_recreated = false;
378
379     /* 2: draw the client.background, but only for the parts around the client_rect */
380     if (con->window != NULL) {
381         xcb_rectangle_t background[] = {
382             /* top area */
383             { 0, 0, r->width, w->y },
384             /* bottom area */
385             { 0, (w->y + w->height), r->width, r->height - (w->y + w->height) },
386             /* left area */
387             { 0, 0, w->x, r->height },
388             /* right area */
389             { w->x + w->width, 0, r->width - (w->x + w->width), r->height }
390         };
391 #if 0
392         for (int i = 0; i < 4; i++)
393             DLOG("rect is (%d, %d) with %d x %d\n",
394                     background[i].x,
395                     background[i].y,
396                     background[i].width,
397                     background[i].height
398                 );
399 #endif
400
401         xcb_change_gc(conn, con->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]) { config.client.background });
402         xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, sizeof(background) / sizeof(xcb_rectangle_t), background);
403     }
404
405     /* 3: draw a rectangle in border color around the client */
406     if (p->border_style != BS_NONE && p->con_is_leaf) {
407         /* We might hide some borders adjacent to the screen-edge */
408         adjacent_t borders_to_hide = ADJ_NONE;
409         borders_to_hide = con_adjacent_borders(con) & config.hide_edge_borders;
410
411         Rect br = con_border_style_rect(con);
412 #if 0
413         DLOG("con->rect spans %d x %d\n", con->rect.width, con->rect.height);
414         DLOG("border_rect spans (%d, %d) with %d x %d\n", br.x, br.y, br.width, br.height);
415         DLOG("window_rect spans (%d, %d) with %d x %d\n", con->window_rect.x, con->window_rect.y, con->window_rect.width, con->window_rect.height);
416 #endif
417
418         /* These rectangles represents the border around the child window
419          * (left, bottom and right part). We don’t just fill the whole
420          * rectangle because some childs are not freely resizable and we want
421          * their background color to "shine through". */
422         xcb_change_gc(conn, con->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->background });
423         if (!(borders_to_hide & ADJ_LEFT_SCREEN_EDGE)) {
424             xcb_rectangle_t leftline = { 0, 0, br.x, r->height };
425             xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, &leftline);
426         }
427         if (!(borders_to_hide & ADJ_RIGHT_SCREEN_EDGE)) {
428             xcb_rectangle_t rightline = { r->width + br.width + br.x, 0, r->width, r->height };
429             xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, &rightline);
430         }
431         if (!(borders_to_hide & ADJ_LOWER_SCREEN_EDGE)) {
432             xcb_rectangle_t bottomline = { 0, r->height + br.height + br.y, r->width, r->height };
433             xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, &bottomline);
434         }
435         /* 1pixel border needs an additional line at the top */
436         if (p->border_style == BS_PIXEL && !(borders_to_hide & ADJ_UPPER_SCREEN_EDGE)) {
437             xcb_rectangle_t topline = { br.x, 0, con->rect.width + br.width + br.x, br.y };
438             xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, &topline);
439         }
440
441         /* Highlight the side of the border at which the next window will be
442          * opened if we are rendering a single window within a split container
443          * (which is undistinguishable from a single window outside a split
444          * container otherwise. */
445         if (TAILQ_NEXT(con, nodes) == NULL &&
446             TAILQ_PREV(con, nodes_head, nodes) == NULL &&
447             con->parent->type != CT_FLOATING_CON) {
448             xcb_change_gc(conn, con->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->indicator });
449             if (p->parent_layout == L_SPLITH)
450                 xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, (xcb_rectangle_t[]){
451                         { r->width + br.width + br.x, br.y, r->width, r->height + br.height } });
452             else if (p->parent_layout == L_SPLITV)
453                 xcb_poly_fill_rectangle(conn, con->pixmap, con->pm_gc, 1, (xcb_rectangle_t[]){
454                         { br.x, r->height + br.height + br.y, r->width - (2 * br.x), r->height } });
455         }
456
457     }
458
459     /* if this is a borderless/1pixel window, we don’t need to render the
460      * decoration. */
461     if (p->border_style != BS_NORMAL)
462         goto copy_pixmaps;
463
464     /* 4: paint the bar */
465     xcb_change_gc(conn, parent->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->background });
466     xcb_rectangle_t drect = { con->deco_rect.x, con->deco_rect.y, con->deco_rect.width, con->deco_rect.height };
467     xcb_poly_fill_rectangle(conn, parent->pixmap, parent->pm_gc, 1, &drect);
468
469     /* 5: draw two unconnected horizontal lines in border color */
470     xcb_change_gc(conn, parent->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->border });
471     Rect *dr = &(con->deco_rect);
472     int deco_diff_l = 2;
473     int deco_diff_r = 2;
474     if (parent->layout == L_TABBED) {
475         if (TAILQ_PREV(con, nodes_head, nodes) != NULL)
476             deco_diff_l = 0;
477         if (TAILQ_NEXT(con, nodes) != NULL)
478             deco_diff_r = 0;
479     }
480     xcb_segment_t segments[] = {
481         { dr->x,                 dr->y,
482           dr->x + dr->width - 1, dr->y },
483
484         { dr->x + deco_diff_l,                 dr->y + dr->height - 1,
485           dr->x - deco_diff_r + dr->width - 1, dr->y + dr->height - 1 }
486     };
487     xcb_poly_segment(conn, parent->pixmap, parent->pm_gc, 2, segments);
488
489     /* 6: draw the title */
490     set_font_colors(parent->pm_gc, p->color->text, p->color->background);
491     int text_offset_y = (con->deco_rect.height - config.font.height) / 2;
492
493     struct Window *win = con->window;
494     if (win == NULL) {
495         /* we have a split container which gets a representation
496          * of its children as title
497          */
498         char *title;
499         char *tree = con_get_tree_representation(con);
500         sasprintf(&title, "i3: %s", tree);
501         free(tree);
502
503         draw_text_ascii(title,
504                 parent->pixmap, parent->pm_gc,
505                 con->deco_rect.x + 2, con->deco_rect.y + text_offset_y,
506                 con->deco_rect.width - 2);
507         free(title);
508
509         goto after_title;
510     }
511
512     if (win->name == NULL)
513         goto copy_pixmaps;
514
515     int indent_level = 0,
516         indent_mult = 0;
517     Con *il_parent = parent;
518     if (il_parent->layout != L_STACKED) {
519         while (1) {
520             //DLOG("il_parent = %p, layout = %d\n", il_parent, il_parent->layout);
521             if (il_parent->layout == L_STACKED)
522                 indent_level++;
523             if (il_parent->type == CT_WORKSPACE || il_parent->type == CT_DOCKAREA || il_parent->type == CT_OUTPUT)
524                 break;
525             il_parent = il_parent->parent;
526             indent_mult++;
527         }
528     }
529     //DLOG("indent_level = %d, indent_mult = %d\n", indent_level, indent_mult);
530     int indent_px = (indent_level * 5) * indent_mult;
531
532     draw_text(win->name,
533             parent->pixmap, parent->pm_gc,
534             con->deco_rect.x + 2 + indent_px, con->deco_rect.y + text_offset_y,
535             con->deco_rect.width - 2 - indent_px);
536
537 after_title:
538     /* Since we don’t clip the text at all, it might in some cases be painted
539      * on the border pixels on the right side of a window. Therefore, we draw
540      * the right border again after rendering the text (and the unconnected
541      * lines in border color). */
542
543     /* Draw a 1px separator line before and after every tab, so that tabs can
544      * be easily distinguished. */
545     if (parent->layout == L_TABBED) {
546         xcb_change_gc(conn, parent->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->border });
547     } else {
548         xcb_change_gc(conn, parent->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->background });
549     }
550     xcb_poly_line(conn, XCB_COORD_MODE_ORIGIN, parent->pixmap, parent->pm_gc, 6,
551                   (xcb_point_t[]){
552                       { dr->x + dr->width, dr->y },
553                       { dr->x + dr->width, dr->y + dr->height },
554                       { dr->x + dr->width - 1, dr->y },
555                       { dr->x + dr->width - 1, dr->y + dr->height },
556                       { dr->x, dr->y + dr->height },
557                       { dr->x, dr->y },
558                   });
559
560     xcb_change_gc(conn, parent->pm_gc, XCB_GC_FOREGROUND, (uint32_t[]){ p->color->border });
561     xcb_poly_segment(conn, parent->pixmap, parent->pm_gc, 2, segments);
562
563 copy_pixmaps:
564     xcb_copy_area(conn, con->pixmap, con->frame, con->pm_gc, 0, 0, 0, 0, con->rect.width, con->rect.height);
565 }
566
567 /*
568  * Recursively calls x_draw_decoration. This cannot be done in x_push_node
569  * because x_push_node uses focus order to recurse (see the comment above)
570  * while drawing the decoration needs to happen in the actual order.
571  *
572  */
573 void x_deco_recurse(Con *con) {
574     Con *current;
575     bool leaf = TAILQ_EMPTY(&(con->nodes_head)) &&
576                 TAILQ_EMPTY(&(con->floating_head));
577     con_state *state = state_for_frame(con->frame);
578
579     if (!leaf) {
580         TAILQ_FOREACH(current, &(con->nodes_head), nodes)
581             x_deco_recurse(current);
582
583         TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
584             x_deco_recurse(current);
585
586         if (state->mapped)
587             xcb_copy_area(conn, con->pixmap, con->frame, con->pm_gc, 0, 0, 0, 0, con->rect.width, con->rect.height);
588     }
589
590     if ((con->type != CT_ROOT && con->type != CT_OUTPUT) &&
591         (!leaf || con->mapped))
592         x_draw_decoration(con);
593 }
594
595 /*
596  * This function pushes the properties of each node of the layout tree to
597  * X11 if they have changed (like the map state, position of the window, …).
598  * It recursively traverses all children of the given node.
599  *
600  */
601 void x_push_node(Con *con) {
602     Con *current;
603     con_state *state;
604     Rect rect = con->rect;
605
606     //DLOG("Pushing changes for node %p / %s\n", con, con->name);
607     state = state_for_frame(con->frame);
608
609     if (state->name != NULL) {
610         DLOG("pushing name %s for con %p\n", state->name, con);
611
612         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->frame,
613                             XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, strlen(state->name), state->name);
614         FREE(state->name);
615     }
616
617     if (con->window == NULL) {
618         /* Calculate the height of all window decorations which will be drawn on to
619          * this frame. */
620         uint32_t max_y = 0, max_height = 0;
621         TAILQ_FOREACH(current, &(con->nodes_head), nodes) {
622             Rect *dr = &(current->deco_rect);
623             if (dr->y >= max_y && dr->height >= max_height) {
624                 max_y = dr->y;
625                 max_height = dr->height;
626             }
627         }
628         rect.height = max_y + max_height;
629         if (rect.height == 0)
630             con->mapped = false;
631     }
632
633     /* reparent the child window (when the window was moved due to a sticky
634      * container) */
635     if (state->need_reparent && con->window != NULL) {
636         DLOG("Reparenting child window\n");
637
638         /* Temporarily set the event masks to XCB_NONE so that we won’t get
639          * UnmapNotify events (otherwise the handler would close the container).
640          * These events are generated automatically when reparenting. */
641         uint32_t values[] = { XCB_NONE };
642         xcb_change_window_attributes(conn, state->old_frame, XCB_CW_EVENT_MASK, values);
643         xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
644
645         xcb_reparent_window(conn, con->window->id, con->frame, 0, 0);
646
647         values[0] = FRAME_EVENT_MASK;
648         xcb_change_window_attributes(conn, state->old_frame, XCB_CW_EVENT_MASK, values);
649         values[0] = CHILD_EVENT_MASK;
650         xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
651
652         state->old_frame = XCB_NONE;
653         state->need_reparent = false;
654
655         con->ignore_unmap++;
656         DLOG("ignore_unmap for reparenting of con %p (win 0x%08x) is now %d\n",
657                 con, con->window->id, con->ignore_unmap);
658     }
659
660     bool fake_notify = false;
661     /* Set new position if rect changed (and if height > 0) */
662     if (memcmp(&(state->rect), &rect, sizeof(Rect)) != 0 &&
663         rect.height > 0) {
664         /* We first create the new pixmap, then render to it, set it as the
665          * background and only afterwards change the window size. This reduces
666          * flickering. */
667
668         /* As the pixmap only depends on the size and not on the position, it
669          * is enough to check if width/height have changed. Also, we don’t
670          * create a pixmap at all when the window is actually not visible
671          * (height == 0). */
672         if ((state->rect.width != rect.width ||
673             state->rect.height != rect.height)) {
674             if (con->pixmap == 0) {
675                 con->pixmap = xcb_generate_id(conn);
676                 con->pm_gc = xcb_generate_id(conn);
677             } else {
678                 xcb_free_pixmap(conn, con->pixmap);
679                 xcb_free_gc(conn, con->pm_gc);
680             }
681
682             uint16_t win_depth = root_depth;
683             if (con->window)
684                 win_depth = con->window->depth;
685
686             xcb_create_pixmap(conn, win_depth, con->pixmap, con->frame, rect.width, rect.height);
687
688             /* For the graphics context, we disable GraphicsExposure events.
689              * Those will be sent when a CopyArea request cannot be fulfilled
690              * properly due to parts of the source being unmapped or otherwise
691              * unavailable. Since we always copy from pixmaps to windows, this
692              * is not a concern for us. */
693             uint32_t values[] = { 0 };
694             xcb_create_gc(conn, con->pm_gc, con->pixmap, XCB_GC_GRAPHICS_EXPOSURES, values);
695
696             con->pixmap_recreated = true;
697
698             /* Don’t render the decoration for windows inside a stack which are
699              * not visible right now */
700             if (!con->parent ||
701                 con->parent->layout != L_STACKED ||
702                 TAILQ_FIRST(&(con->parent->focus_head)) == con)
703                 /* Render the decoration now to make the correct decoration visible
704                  * from the very first moment. Later calls will be cached, so this
705                  * doesn’t hurt performance. */
706                 x_deco_recurse(con);
707         }
708
709         DLOG("setting rect (%d, %d, %d, %d)\n", rect.x, rect.y, rect.width, rect.height);
710         /* flush to ensure that the following commands are sent in a single
711          * buffer and will be processed directly afterwards (the contents of a
712          * window get lost when resizing it, therefore we want to provide it as
713          * fast as possible) */
714         xcb_flush(conn);
715         xcb_set_window_rect(conn, con->frame, rect);
716         if (con->pixmap != XCB_NONE)
717             xcb_copy_area(conn, con->pixmap, con->frame, con->pm_gc, 0, 0, 0, 0, con->rect.width, con->rect.height);
718         xcb_flush(conn);
719
720         memcpy(&(state->rect), &rect, sizeof(Rect));
721         fake_notify = true;
722     }
723
724     /* dito, but for child windows */
725     if (con->window != NULL &&
726         memcmp(&(state->window_rect), &(con->window_rect), sizeof(Rect)) != 0) {
727         DLOG("setting window rect (%d, %d, %d, %d)\n",
728             con->window_rect.x, con->window_rect.y, con->window_rect.width, con->window_rect.height);
729         xcb_set_window_rect(conn, con->window->id, con->window_rect);
730         memcpy(&(state->window_rect), &(con->window_rect), sizeof(Rect));
731         fake_notify = true;
732     }
733
734     /* Map if map state changed, also ensure that the child window
735      * is changed if we are mapped *and* in initial state (meaning the
736      * container was empty before, but now got a child). Unmaps are handled in
737      * x_push_node_unmaps(). */
738     if ((state->mapped != con->mapped || (con->mapped && state->initial)) &&
739         con->mapped) {
740         xcb_void_cookie_t cookie;
741
742         if (con->window != NULL) {
743             /* Set WM_STATE_NORMAL because GTK applications don’t want to
744              * drag & drop if we don’t. Also, xprop(1) needs it. */
745             long data[] = { XCB_ICCCM_WM_STATE_NORMAL, XCB_NONE };
746             xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
747                                 A_WM_STATE, A_WM_STATE, 32, 2, data);
748         }
749
750         uint32_t values[1];
751         if (!state->child_mapped && con->window != NULL) {
752             cookie = xcb_map_window(conn, con->window->id);
753
754             /* We are interested in EnterNotifys as soon as the window is
755              * mapped */
756             values[0] = CHILD_EVENT_MASK;
757             xcb_change_window_attributes(conn, con->window->id, XCB_CW_EVENT_MASK, values);
758             DLOG("mapping child window (serial %d)\n", cookie.sequence);
759             state->child_mapped = true;
760         }
761
762         cookie = xcb_map_window(conn, con->frame);
763
764         values[0] = FRAME_EVENT_MASK;
765         xcb_change_window_attributes(conn, con->frame, XCB_CW_EVENT_MASK, values);
766
767         /* copy the pixmap contents to the frame window immediately after mapping */
768         if (con->pixmap != XCB_NONE)
769             xcb_copy_area(conn, con->pixmap, con->frame, con->pm_gc, 0, 0, 0, 0, con->rect.width, con->rect.height);
770         xcb_flush(conn);
771
772         DLOG("mapping container %08x (serial %d)\n", con->frame, cookie.sequence);
773         state->mapped = con->mapped;
774     }
775
776     state->unmap_now = (state->mapped != con->mapped) && !con->mapped;
777
778     if (fake_notify) {
779         DLOG("Sending fake configure notify\n");
780         fake_absolute_configure_notify(con);
781     }
782
783     /* Handle all children and floating windows of this node. We recurse
784      * in focus order to display the focused client in a stack first when
785      * switching workspaces (reduces flickering). */
786     TAILQ_FOREACH(current, &(con->focus_head), focused)
787         x_push_node(current);
788 }
789
790 /*
791  * Same idea as in x_push_node(), but this function only unmaps windows. It is
792  * necessary to split this up to handle new fullscreen clients properly: The
793  * new window needs to be mapped and focus needs to be set *before* the
794  * underlying windows are unmapped. Otherwise, focus will revert to the
795  * PointerRoot and will then be set to the new window, generating unnecessary
796  * FocusIn/FocusOut events.
797  *
798  */
799 static void x_push_node_unmaps(Con *con) {
800     Con *current;
801     con_state *state;
802
803     //DLOG("Pushing changes (with unmaps) for node %p / %s\n", con, con->name);
804     state = state_for_frame(con->frame);
805
806     /* map/unmap if map state changed, also ensure that the child window
807      * is changed if we are mapped *and* in initial state (meaning the
808      * container was empty before, but now got a child) */
809     if (state->unmap_now) {
810         xcb_void_cookie_t cookie;
811         if (con->window != NULL) {
812             /* Set WM_STATE_WITHDRAWN, it seems like Java apps need it */
813             long data[] = { XCB_ICCCM_WM_STATE_WITHDRAWN, XCB_NONE };
814             xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
815                                 A_WM_STATE, A_WM_STATE, 32, 2, data);
816         }
817
818         cookie = xcb_unmap_window(conn, con->frame);
819         DLOG("unmapping container %p / %s (serial %d)\n", con, con->name, cookie.sequence);
820         /* we need to increase ignore_unmap for this container (if it
821          * contains a window) and for every window "under" this one which
822          * contains a window */
823         if (con->window != NULL) {
824             con->ignore_unmap++;
825             DLOG("ignore_unmap for con %p (frame 0x%08x) now %d\n", con, con->frame, con->ignore_unmap);
826         }
827         state->mapped = con->mapped;
828     }
829
830     /* handle all children and floating windows of this node */
831     TAILQ_FOREACH(current, &(con->nodes_head), nodes)
832         x_push_node_unmaps(current);
833
834     TAILQ_FOREACH(current, &(con->floating_head), floating_windows)
835         x_push_node_unmaps(current);
836 }
837
838 /*
839  * Pushes all changes (state of each node, see x_push_node() and the window
840  * stack) to X11.
841  *
842  * NOTE: We need to push the stack first so that the windows have the correct
843  * stacking order. This is relevant for workspace switching where we map the
844  * windows because mapping may generate EnterNotify events. When they are
845  * generated in the wrong order, this will cause focus problems when switching
846  * workspaces.
847  *
848  */
849 void x_push_changes(Con *con) {
850     con_state *state;
851     xcb_query_pointer_cookie_t pointercookie;
852
853     /* If we need to warp later, we request the pointer position as soon as possible */
854     if (warp_to) {
855         pointercookie = xcb_query_pointer(conn, root);
856     }
857
858     DLOG("-- PUSHING WINDOW STACK --\n");
859     //DLOG("Disabling EnterNotify\n");
860     uint32_t values[1] = { XCB_NONE };
861     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
862         if (state->mapped)
863             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
864     }
865     //DLOG("Done, EnterNotify disabled\n");
866     bool order_changed = false;
867     bool stacking_changed = false;
868
869     /* count first, necessary to (re)allocate memory for the bottom-to-top
870      * stack afterwards */
871     int cnt = 0;
872     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state)
873         if (state->con && state->con->window)
874             cnt++;
875
876     if (cnt != btt_stack_num) {
877         btt_stack = srealloc(btt_stack, sizeof(xcb_window_t) * cnt);
878         btt_stack_num = cnt;
879     }
880
881     xcb_window_t *walk = btt_stack;
882
883     /* X11 correctly represents the stack if we push it from bottom to top */
884     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
885         if (state->con && state->con->window)
886             memcpy(walk++, &(state->con->window->id), sizeof(xcb_window_t));
887
888         //DLOG("stack: 0x%08x\n", state->id);
889         con_state *prev = CIRCLEQ_PREV(state, state);
890         con_state *old_prev = CIRCLEQ_PREV(state, old_state);
891         if (prev != old_prev)
892             order_changed = true;
893         if ((state->initial || order_changed) && prev != CIRCLEQ_END(&state_head)) {
894             stacking_changed = true;
895             //DLOG("Stacking 0x%08x above 0x%08x\n", prev->id, state->id);
896             uint32_t mask = 0;
897             mask |= XCB_CONFIG_WINDOW_SIBLING;
898             mask |= XCB_CONFIG_WINDOW_STACK_MODE;
899             uint32_t values[] = {state->id, XCB_STACK_MODE_ABOVE};
900
901             xcb_configure_window(conn, prev->id, mask, values);
902         }
903         if (state->above_all) {
904             DLOG("above all: 0x%08x\n", state->id);
905             xcb_configure_window(conn, state->id, XCB_CONFIG_WINDOW_STACK_MODE, (uint32_t[]){ XCB_STACK_MODE_ABOVE });
906         }
907         state->initial = false;
908     }
909
910     /* If we re-stacked something (or a new window appeared), we need to update
911      * the _NET_CLIENT_LIST_STACKING hint */
912     if (stacking_changed)
913         ewmh_update_client_list_stacking(btt_stack, btt_stack_num);
914
915     DLOG("PUSHING CHANGES\n");
916     x_push_node(con);
917
918     if (warp_to) {
919         xcb_query_pointer_reply_t *pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL);
920         if (!pointerreply) {
921             ELOG("Could not query pointer position, not warping pointer\n");
922         } else {
923             int mid_x = warp_to->x + (warp_to->width / 2);
924             int mid_y = warp_to->y + (warp_to->height / 2);
925
926             Output *current = get_output_containing(pointerreply->root_x, pointerreply->root_y);
927             Output *target = get_output_containing(mid_x, mid_y);
928             if (current != target) {
929                 /* Ignore MotionNotify events generated by warping */
930                 xcb_change_window_attributes(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT });
931                 xcb_warp_pointer(conn, XCB_NONE, root, 0, 0, 0, 0, mid_x, mid_y);
932                 xcb_change_window_attributes(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ ROOT_EVENT_MASK });
933             }
934         }
935         warp_to = NULL;
936     }
937
938     //DLOG("Re-enabling EnterNotify\n");
939     values[0] = FRAME_EVENT_MASK;
940     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
941         if (state->mapped)
942             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
943     }
944     //DLOG("Done, EnterNotify re-enabled\n");
945
946     x_deco_recurse(con);
947
948     xcb_window_t to_focus = focused->frame;
949     if (focused->window != NULL)
950         to_focus = focused->window->id;
951
952     if (focused_id != to_focus) {
953         if (!focused->mapped) {
954             DLOG("Not updating focus (to %p / %s), focused window is not mapped.\n", focused, focused->name);
955             /* Invalidate focused_id to correctly focus new windows with the same ID */
956             focused_id = XCB_NONE;
957         } else {
958             bool set_focus = true;
959             if (focused->window != NULL &&
960                 focused->window->needs_take_focus) {
961                 DLOG("Updating focus by sending WM_TAKE_FOCUS to window 0x%08x (focused: %p / %s)\n",
962                      to_focus, focused, focused->name);
963                 send_take_focus(to_focus);
964                 set_focus = !focused->window->doesnt_accept_focus;
965                 DLOG("set_focus = %d\n", set_focus);
966             }
967
968             if (set_focus) {
969                 DLOG("Updating focus (focused: %p / %s) to X11 window 0x%08x\n", focused, focused->name, to_focus);
970                 /* We remove XCB_EVENT_MASK_FOCUS_CHANGE from the event mask to get
971                  * no focus change events for our own focus changes. We only want
972                  * these generated by the clients. */
973                 if (focused->window != NULL) {
974                     values[0] = CHILD_EVENT_MASK & ~(XCB_EVENT_MASK_FOCUS_CHANGE);
975                     xcb_change_window_attributes(conn, focused->window->id, XCB_CW_EVENT_MASK, values);
976                 }
977                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, to_focus, XCB_CURRENT_TIME);
978                 if (focused->window != NULL) {
979                     values[0] = CHILD_EVENT_MASK;
980                     xcb_change_window_attributes(conn, focused->window->id, XCB_CW_EVENT_MASK, values);
981                 }
982
983                 ewmh_update_active_window(to_focus);
984             }
985
986             focused_id = to_focus;
987         }
988     }
989
990     if (focused_id == XCB_NONE) {
991         DLOG("Still no window focused, better set focus to the root window\n");
992         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT, root, XCB_CURRENT_TIME);
993         focused_id = root;
994     }
995
996     xcb_flush(conn);
997     DLOG("ENDING CHANGES\n");
998
999     /* Disable EnterWindow events for windows which will be unmapped in
1000      * x_push_node_unmaps() now. Unmapping windows happens when switching
1001      * workspaces. We want to avoid getting EnterNotifies during that phase
1002      * because they would screw up our focus. One of these cases is having a
1003      * stack with two windows. If the first window is focused and gets
1004      * unmapped, the second one appears under the cursor and therefore gets an
1005      * EnterNotify event. */
1006     values[0] = FRAME_EVENT_MASK & ~XCB_EVENT_MASK_ENTER_WINDOW;
1007     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1008         if (!state->unmap_now)
1009             continue;
1010         xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1011     }
1012
1013     /* Push all pending unmaps */
1014     x_push_node_unmaps(con);
1015
1016     /* save the current stack as old stack */
1017     CIRCLEQ_FOREACH(state, &state_head, state) {
1018         CIRCLEQ_REMOVE(&old_state_head, state, old_state);
1019         CIRCLEQ_INSERT_TAIL(&old_state_head, state, old_state);
1020     }
1021     //CIRCLEQ_FOREACH(state, &old_state_head, old_state) {
1022     //    DLOG("old stack: 0x%08x\n", state->id);
1023     //}
1024
1025     xcb_flush(conn);
1026 }
1027
1028 /*
1029  * Raises the specified container in the internal stack of X windows. The
1030  * next call to x_push_changes() will make the change visible in X11.
1031  *
1032  * If above_all is true, the X11 window will be raised to the top
1033  * of the stack. This should only be used for precisely one fullscreen
1034  * window per output.
1035  *
1036  */
1037 void x_raise_con(Con *con, bool above_all) {
1038     con_state *state;
1039     state = state_for_frame(con->frame);
1040     //DLOG("raising in new stack: %p / %s / %s / xid %08x\n", con, con->name, con->window ? con->window->name_json : "", state->id);
1041
1042     state->above_all = above_all;
1043
1044     CIRCLEQ_REMOVE(&state_head, state, state);
1045     CIRCLEQ_INSERT_HEAD(&state_head, state, state);
1046 }
1047
1048 /*
1049  * Sets the WM_NAME property (so, no UTF8, but used only for debugging anyways)
1050  * of the given name. Used for properly tagging the windows for easily spotting
1051  * i3 windows in xwininfo -root -all.
1052  *
1053  */
1054 void x_set_name(Con *con, const char *name) {
1055     struct con_state *state;
1056
1057     if ((state = state_for_frame(con->frame)) == NULL) {
1058         ELOG("window state not found\n");
1059         return;
1060     }
1061
1062     FREE(state->name);
1063     state->name = sstrdup(name);
1064 }
1065
1066 /*
1067  * Set up the I3_SHMLOG_PATH atom.
1068  *
1069  */
1070 void update_shmlog_atom() {
1071     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
1072             A_I3_SHMLOG_PATH, A_UTF8_STRING, 8,
1073             strlen(shmlogname), shmlogname);
1074 }
1075
1076 /*
1077  * Sets up i3 specific atoms (I3_SOCKET_PATH and I3_CONFIG_PATH)
1078  *
1079  */
1080 void x_set_i3_atoms(void) {
1081     pid_t pid = getpid();
1082     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_SOCKET_PATH, A_UTF8_STRING, 8,
1083                         (current_socketpath == NULL ? 0 : strlen(current_socketpath)),
1084                         current_socketpath);
1085     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_PID, XCB_ATOM_CARDINAL, 32, 1, &pid);
1086     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root, A_I3_CONFIG_PATH, A_UTF8_STRING, 8,
1087                         strlen(current_configpath), current_configpath);
1088     update_shmlog_atom();
1089 }
1090
1091 /*
1092  * Set warp_to coordinates.  This will trigger on the next call to
1093  * x_push_changes().
1094  *
1095  */
1096 void x_set_warp_to(Rect *rect)
1097 {
1098     warp_to = rect;
1099 }
1100
1101 /*
1102  * Applies the given mask to the event mask of every i3 window decoration X11
1103  * window. This is useful to disable EnterNotify while resizing so that focus
1104  * is untouched.
1105  *
1106  */
1107 void x_mask_event_mask(uint32_t mask) {
1108     uint32_t values[] = { FRAME_EVENT_MASK & mask };
1109
1110     con_state *state;
1111     CIRCLEQ_FOREACH_REVERSE(state, &state_head, state) {
1112         if (state->mapped)
1113             xcb_change_window_attributes(conn, state->id, XCB_CW_EVENT_MASK, values);
1114     }
1115 }