]> git.sur5r.net Git - i3/i3/blob - src/floating.c
Merge branch 'release-4.16.1'
[i3/i3] / src / floating.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  * floating.c: Floating windows.
8  *
9  */
10 #include "all.h"
11
12 #ifndef MAX
13 #define MAX(x, y) ((x) > (y) ? (x) : (y))
14 #endif
15
16 /*
17  * Calculates sum of heights and sum of widths of all currently active outputs
18  *
19  */
20 static Rect total_outputs_dimensions(void) {
21     if (TAILQ_EMPTY(&outputs))
22         return (Rect){0, 0, root_screen->width_in_pixels, root_screen->height_in_pixels};
23
24     Output *output;
25     /* Use Rect to encapsulate dimensions, ignoring x/y */
26     Rect outputs_dimensions = {0, 0, 0, 0};
27     TAILQ_FOREACH(output, &outputs, outputs) {
28         outputs_dimensions.height += output->rect.height;
29         outputs_dimensions.width += output->rect.width;
30     }
31     return outputs_dimensions;
32 }
33
34 /*
35  * Updates I3_FLOATING_WINDOW by either setting or removing it on the con and
36  * all its children.
37  *
38  */
39 static void floating_set_hint_atom(Con *con, bool floating) {
40     if (!con_is_leaf(con)) {
41         Con *child;
42         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
43             floating_set_hint_atom(child, floating);
44         }
45     }
46
47     if (con->window == NULL) {
48         return;
49     }
50
51     if (floating) {
52         uint32_t val = 1;
53         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
54                             A_I3_FLOATING_WINDOW, XCB_ATOM_CARDINAL, 32, 1, &val);
55     } else {
56         xcb_delete_property(conn, con->window->id, A_I3_FLOATING_WINDOW);
57     }
58
59     xcb_flush(conn);
60 }
61
62 /*
63  * Called when a floating window is created or resized.
64  * This function resizes the window if its size is higher or lower than the
65  * configured maximum/minimum size, respectively.
66  *
67  */
68 void floating_check_size(Con *floating_con) {
69     /* Define reasonable minimal and maximal sizes for floating windows */
70     const int floating_sane_min_height = 50;
71     const int floating_sane_min_width = 75;
72     Rect floating_sane_max_dimensions;
73     Con *focused_con = con_descend_focused(floating_con);
74
75     Rect border_rect = con_border_style_rect(focused_con);
76     /* We have to do the opposite calculations that render_con() do
77      * to get the exact size we want. */
78     border_rect.width = -border_rect.width;
79     border_rect.width += 2 * focused_con->border_width;
80     border_rect.height = -border_rect.height;
81     border_rect.height += 2 * focused_con->border_width;
82     if (con_border_style(focused_con) == BS_NORMAL) {
83         border_rect.height += render_deco_height();
84     }
85
86     if (focused_con->window != NULL) {
87         if (focused_con->window->min_width) {
88             floating_con->rect.width -= border_rect.width;
89             floating_con->rect.width = max(floating_con->rect.width, focused_con->window->min_width);
90             floating_con->rect.width += border_rect.width;
91         }
92
93         if (focused_con->window->min_height) {
94             floating_con->rect.height -= border_rect.height;
95             floating_con->rect.height = max(floating_con->rect.height, focused_con->window->min_height);
96             floating_con->rect.height += border_rect.height;
97         }
98
99         if (focused_con->window->max_width) {
100             floating_con->rect.width -= border_rect.width;
101             floating_con->rect.width = min(floating_con->rect.width, focused_con->window->max_width);
102             floating_con->rect.width += border_rect.width;
103         }
104
105         if (focused_con->window->max_height) {
106             floating_con->rect.height -= border_rect.height;
107             floating_con->rect.height = min(floating_con->rect.height, focused_con->window->max_height);
108             floating_con->rect.height += border_rect.height;
109         }
110
111         if (focused_con->window->height_increment &&
112             floating_con->rect.height >= focused_con->window->base_height + border_rect.height) {
113             floating_con->rect.height -= focused_con->window->base_height + border_rect.height;
114             floating_con->rect.height -= floating_con->rect.height % focused_con->window->height_increment;
115             floating_con->rect.height += focused_con->window->base_height + border_rect.height;
116         }
117
118         if (focused_con->window->width_increment &&
119             floating_con->rect.width >= focused_con->window->base_width + border_rect.width) {
120             floating_con->rect.width -= focused_con->window->base_width + border_rect.width;
121             floating_con->rect.width -= floating_con->rect.width % focused_con->window->width_increment;
122             floating_con->rect.width += focused_con->window->base_width + border_rect.width;
123         }
124     }
125
126     /* Unless user requests otherwise (-1), raise the width/height to
127      * reasonable minimum dimensions */
128     if (config.floating_minimum_height != -1) {
129         floating_con->rect.height -= border_rect.height;
130         if (config.floating_minimum_height == 0) {
131             floating_con->rect.height = max(floating_con->rect.height, floating_sane_min_height);
132         } else {
133             floating_con->rect.height = max(floating_con->rect.height, config.floating_minimum_height);
134         }
135         floating_con->rect.height += border_rect.height;
136     }
137
138     if (config.floating_minimum_width != -1) {
139         floating_con->rect.width -= border_rect.width;
140         if (config.floating_minimum_width == 0) {
141             floating_con->rect.width = max(floating_con->rect.width, floating_sane_min_width);
142         } else {
143             floating_con->rect.width = max(floating_con->rect.width, config.floating_minimum_width);
144         }
145         floating_con->rect.width += border_rect.width;
146     }
147
148     /* Unless user requests otherwise (-1), ensure width/height do not exceed
149      * configured maxima or, if unconfigured, limit to combined width of all
150      * outputs */
151     floating_sane_max_dimensions = total_outputs_dimensions();
152     if (config.floating_maximum_height != -1) {
153         floating_con->rect.height -= border_rect.height;
154         if (config.floating_maximum_height == 0) {
155             floating_con->rect.height = min(floating_con->rect.height, floating_sane_max_dimensions.height);
156         } else {
157             floating_con->rect.height = min(floating_con->rect.height, config.floating_maximum_height);
158         }
159         floating_con->rect.height += border_rect.height;
160     }
161
162     if (config.floating_maximum_width != -1) {
163         floating_con->rect.width -= border_rect.width;
164         if (config.floating_maximum_width == 0) {
165             floating_con->rect.width = min(floating_con->rect.width, floating_sane_max_dimensions.width);
166         } else {
167             floating_con->rect.width = min(floating_con->rect.width, config.floating_maximum_width);
168         }
169         floating_con->rect.width += border_rect.width;
170     }
171 }
172
173 void floating_enable(Con *con, bool automatic) {
174     bool set_focus = (con == focused);
175
176     if (con_is_docked(con)) {
177         LOG("Container is a dock window, not enabling floating mode.\n");
178         return;
179     }
180
181     if (con_is_floating(con)) {
182         LOG("Container is already in floating mode, not doing anything.\n");
183         return;
184     }
185
186     if (con->type == CT_WORKSPACE) {
187         LOG("Container is a workspace, not enabling floating mode.\n");
188         return;
189     }
190
191     Con *focus_head_placeholder = NULL;
192     bool focus_before_parent = true;
193     if (!set_focus) {
194         /* Find recursively the ancestor container which is a child of our workspace.
195          * We need to reuse its focus position later. */
196         Con *ancestor = con;
197         while (ancestor->parent->type != CT_WORKSPACE) {
198             focus_before_parent &= TAILQ_FIRST(&(ancestor->parent->focus_head)) == ancestor;
199             ancestor = ancestor->parent;
200         }
201         /* Consider the part of the focus stack of our current workspace:
202          * [ ... S_{i-1} S_{i} S_{i+1} ... ]
203          * Where S_{x} is a container tree and the container 'con' that is beeing switched to
204          * floating belongs in S_{i}. The new floating container, 'nc', will have the
205          * workspace as its parent so it needs to be placed in this stack. If C was focused
206          * we just need to call con_focus(). Otherwise, nc must be placed before or after S_{i}.
207          * We should avoid using the S_{i} container for our operations since it might get
208          * killed if it has no other children. So, the two possible positions are after S_{i-1}
209          * or before S_{i+1}.
210          */
211         if (focus_before_parent) {
212             focus_head_placeholder = TAILQ_PREV(ancestor, focus_head, focused);
213         } else {
214             focus_head_placeholder = TAILQ_NEXT(ancestor, focused);
215         }
216     }
217
218     /* 1: detach the container from its parent */
219     /* TODO: refactor this with tree_close_internal() */
220     con_detach(con);
221     con_fix_percent(con->parent);
222
223     /* 2: create a new container to render the decoration on, add
224      * it as a floating window to the workspace */
225     Con *nc = con_new(NULL, NULL);
226     /* we need to set the parent afterwards instead of passing it as an
227      * argument to con_new() because nc would be inserted into the tiling layer
228      * otherwise. */
229     Con *ws = con_get_workspace(con);
230     nc->parent = ws;
231     nc->type = CT_FLOATING_CON;
232     nc->layout = L_SPLITH;
233     /* We insert nc already, even though its rect is not yet calculated. This
234      * is necessary because otherwise the workspace might be empty (and get
235      * closed in tree_close_internal()) even though it’s not. */
236     TAILQ_INSERT_HEAD(&(ws->floating_head), nc, floating_windows);
237
238     struct focus_head *fh = &(ws->focus_head);
239     if (focus_before_parent) {
240         if (focus_head_placeholder) {
241             TAILQ_INSERT_AFTER(fh, focus_head_placeholder, nc, focused);
242         } else {
243             TAILQ_INSERT_HEAD(fh, nc, focused);
244         }
245     } else {
246         if (focus_head_placeholder) {
247             TAILQ_INSERT_BEFORE(focus_head_placeholder, nc, focused);
248         } else {
249             /* Also used for the set_focus case */
250             TAILQ_INSERT_TAIL(fh, nc, focused);
251         }
252     }
253
254     /* check if the parent container is empty and close it if so */
255     if ((con->parent->type == CT_CON || con->parent->type == CT_FLOATING_CON) &&
256         con_num_children(con->parent) == 0) {
257         DLOG("Old container empty after setting this child to floating, closing\n");
258         Con *parent = con->parent;
259         /* clear the pointer before calling tree_close_internal in which the memory is freed */
260         con->parent = NULL;
261         tree_close_internal(parent, DONT_KILL_WINDOW, false);
262     }
263
264     char *name;
265     sasprintf(&name, "[i3 con] floatingcon around %p", con);
266     x_set_name(nc, name);
267     free(name);
268
269     /* find the height for the decorations */
270     int deco_height = render_deco_height();
271
272     DLOG("Original rect: (%d, %d) with %d x %d\n", con->rect.x, con->rect.y, con->rect.width, con->rect.height);
273     DLOG("Geometry = (%d, %d) with %d x %d\n", con->geometry.x, con->geometry.y, con->geometry.width, con->geometry.height);
274     Rect zero = {0, 0, 0, 0};
275     nc->rect = con->geometry;
276     /* If the geometry was not set (split containers), we need to determine a
277      * sensible one by combining the geometry of all children */
278     if (memcmp(&(nc->rect), &zero, sizeof(Rect)) == 0) {
279         DLOG("Geometry not set, combining children\n");
280         Con *child;
281         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
282             DLOG("child geometry: %d x %d\n", child->geometry.width, child->geometry.height);
283             nc->rect.width += child->geometry.width;
284             nc->rect.height = max(nc->rect.height, child->geometry.height);
285         }
286     }
287
288     TAILQ_INSERT_TAIL(&(nc->nodes_head), con, nodes);
289     TAILQ_INSERT_TAIL(&(nc->focus_head), con, focused);
290
291     /* 3: attach the child to the new parent container. We need to do this
292      * because con_border_style_rect() needs to access con->parent. */
293     con->parent = nc;
294     con->percent = 1.0;
295     con->floating = FLOATING_USER_ON;
296
297     /* 4: set the border style as specified with new_float */
298     if (automatic)
299         con->border_style = config.default_floating_border;
300
301     /* Add pixels for the decoration. */
302     Rect border_style_rect = con_border_style_rect(con);
303
304     nc->rect.height -= border_style_rect.height;
305     nc->rect.width -= border_style_rect.width;
306
307     /* Add some more pixels for the title bar */
308     if (con_border_style(con) == BS_NORMAL) {
309         nc->rect.height += deco_height;
310     }
311
312     /* Honor the X11 border */
313     nc->rect.height += con->border_width * 2;
314     nc->rect.width += con->border_width * 2;
315
316     floating_check_size(nc);
317
318     /* Some clients (like GIMP’s color picker window) get mapped
319      * to (0, 0), so we push them to a reasonable position
320      * (centered over their leader) */
321     if (nc->rect.x == 0 && nc->rect.y == 0) {
322         Con *leader;
323         if (con->window && con->window->leader != XCB_NONE &&
324             (leader = con_by_window_id(con->window->leader)) != NULL) {
325             DLOG("Centering above leader\n");
326             floating_center(nc, leader->rect);
327         } else {
328             /* center the window on workspace as fallback */
329             floating_center(nc, ws->rect);
330         }
331     }
332
333     /* Sanity check: Are the coordinates on the appropriate output? If not, we
334      * need to change them */
335     Output *current_output = get_output_from_rect(nc->rect);
336     Con *correct_output = con_get_output(ws);
337     if (!current_output || current_output->con != correct_output) {
338         DLOG("This floating window is on the wrong output, fixing coordinates (currently (%d, %d))\n",
339              nc->rect.x, nc->rect.y);
340
341         /* If moving from one output to another, keep the relative position
342          * consistent (e.g. a centered dialog will remain centered). */
343         if (current_output) {
344             floating_fix_coordinates(nc, &current_output->con->rect, &correct_output->rect);
345             /* Make sure that the result is in the correct output. */
346             current_output = get_output_from_rect(nc->rect);
347         }
348         if (!current_output || current_output->con != correct_output) {
349             floating_center(nc, ws->rect);
350         }
351     }
352
353     DLOG("Floating rect: (%d, %d) with %d x %d\n", nc->rect.x, nc->rect.y, nc->rect.width, nc->rect.height);
354
355     /* 5: Subtract the deco_height in order to make the floating window appear
356      * at precisely the position it specified in its original geometry (which
357      * is what applications might remember). */
358     deco_height = (con->border_style == BS_NORMAL ? render_deco_height() : 0);
359     nc->rect.y -= deco_height;
360
361     DLOG("Corrected y = %d (deco_height = %d)\n", nc->rect.y, deco_height);
362
363     /* render the cons to get initial window_rect correct */
364     render_con(nc, false);
365     render_con(con, false);
366
367     if (set_focus)
368         con_activate(con);
369
370     floating_set_hint_atom(nc, true);
371     ipc_send_window_event("floating", con);
372 }
373
374 void floating_disable(Con *con, bool automatic) {
375     if (!con_is_floating(con)) {
376         LOG("Container isn't floating, not doing anything.\n");
377         return;
378     }
379
380     Con *ws = con_get_workspace(con);
381     if (con_is_internal(ws)) {
382         LOG("Can't disable floating for container in internal workspace.\n");
383         return;
384     }
385     Con *tiling_focused = con_descend_tiling_focused(ws);
386
387     if (tiling_focused->type == CT_WORKSPACE) {
388         Con *parent = con->parent;
389         con_detach(con);
390         con->parent = NULL;
391         tree_close_internal(parent, DONT_KILL_WINDOW, true);
392         con_attach(con, tiling_focused, false);
393         con->percent = 0.0;
394         con_fix_percent(con->parent);
395     } else {
396         insert_con_into(con, tiling_focused, AFTER);
397     }
398
399     con->floating = FLOATING_USER_OFF;
400     floating_set_hint_atom(con, false);
401     ipc_send_window_event("floating", con);
402 }
403
404 /*
405  * Toggles floating mode for the given container.
406  *
407  * If the automatic flag is set to true, this was an automatic update by a change of the
408  * window class from the application which can be overwritten by the user.
409  *
410  */
411 void toggle_floating_mode(Con *con, bool automatic) {
412     /* forbid the command to toggle floating on a CT_FLOATING_CON */
413     if (con->type == CT_FLOATING_CON) {
414         ELOG("Cannot toggle floating mode on con = %p because it is of type CT_FLOATING_CON.\n", con);
415         return;
416     }
417
418     /* see if the client is already floating */
419     if (con_is_floating(con)) {
420         LOG("already floating, re-setting to tiling\n");
421
422         floating_disable(con, automatic);
423         return;
424     }
425
426     floating_enable(con, automatic);
427 }
428
429 /*
430  * Raises the given container in the list of floating containers
431  *
432  */
433 void floating_raise_con(Con *con) {
434     DLOG("Raising floating con %p / %s\n", con, con->name);
435     TAILQ_REMOVE(&(con->parent->floating_head), con, floating_windows);
436     TAILQ_INSERT_TAIL(&(con->parent->floating_head), con, floating_windows);
437 }
438
439 /*
440  * Checks if con’s coordinates are within its workspace and re-assigns it to
441  * the actual workspace if not.
442  *
443  */
444 bool floating_maybe_reassign_ws(Con *con) {
445     Output *output = get_output_from_rect(con->rect);
446
447     if (!output) {
448         ELOG("No output found at destination coordinates?\n");
449         return false;
450     }
451
452     if (con_get_output(con) == output->con) {
453         DLOG("still the same ws\n");
454         return false;
455     }
456
457     DLOG("Need to re-assign!\n");
458
459     Con *content = output_get_content(output->con);
460     Con *ws = TAILQ_FIRST(&(content->focus_head));
461     DLOG("Moving con %p / %s to workspace %p / %s\n", con, con->name, ws, ws->name);
462     con_move_to_workspace(con, ws, false, true, false);
463     workspace_show(ws);
464     con_activate(con_descend_focused(con));
465     return true;
466 }
467
468 /*
469  * Centers a floating con above the specified rect.
470  *
471  */
472 void floating_center(Con *con, Rect rect) {
473     con->rect.x = rect.x + (rect.width / 2) - (con->rect.width / 2);
474     con->rect.y = rect.y + (rect.height / 2) - (con->rect.height / 2);
475 }
476
477 /*
478  * Moves the given floating con to the current pointer position.
479  *
480  */
481 void floating_move_to_pointer(Con *con) {
482     assert(con->type == CT_FLOATING_CON);
483
484     xcb_query_pointer_reply_t *reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL);
485     if (reply == NULL) {
486         ELOG("could not query pointer position, not moving this container\n");
487         return;
488     }
489
490     Output *output = get_output_containing(reply->root_x, reply->root_y);
491     if (output == NULL) {
492         ELOG("The pointer is not on any output, cannot move the container here.\n");
493         return;
494     }
495
496     /* Determine where to put the window. */
497     int32_t x = reply->root_x - con->rect.width / 2;
498     int32_t y = reply->root_y - con->rect.height / 2;
499     FREE(reply);
500
501     /* Correct target coordinates to be in-bounds. */
502     x = MAX(x, (int32_t)output->rect.x);
503     y = MAX(y, (int32_t)output->rect.y);
504     if (x + con->rect.width > output->rect.x + output->rect.width)
505         x = output->rect.x + output->rect.width - con->rect.width;
506     if (y + con->rect.height > output->rect.y + output->rect.height)
507         y = output->rect.y + output->rect.height - con->rect.height;
508
509     /* Update container's coordinates to position it correctly. */
510     floating_reposition(con, (Rect){x, y, con->rect.width, con->rect.height});
511 }
512
513 DRAGGING_CB(drag_window_callback) {
514     const struct xcb_button_press_event_t *event = extra;
515
516     /* Reposition the client correctly while moving */
517     con->rect.x = old_rect->x + (new_x - event->root_x);
518     con->rect.y = old_rect->y + (new_y - event->root_y);
519
520     render_con(con, false);
521     x_push_node(con);
522     xcb_flush(conn);
523
524     /* Check if we cross workspace boundaries while moving */
525     if (!floating_maybe_reassign_ws(con))
526         return;
527     /* Ensure not to warp the pointer while dragging */
528     x_set_warp_to(NULL);
529     tree_render();
530 }
531
532 /*
533  * Called when the user clicked on the titlebar of a floating window.
534  * Calls the drag_pointer function with the drag_window callback
535  *
536  */
537 void floating_drag_window(Con *con, const xcb_button_press_event_t *event) {
538     DLOG("floating_drag_window\n");
539
540     /* Push changes before dragging, so that the window gets raised now and not
541      * after the user releases the mouse button */
542     tree_render();
543
544     /* Store the initial rect in case of user revert/cancel */
545     Rect initial_rect = con->rect;
546
547     /* Drag the window */
548     drag_result_t drag_result = drag_pointer(con, event, XCB_NONE, BORDER_TOP /* irrelevant */, XCURSOR_CURSOR_MOVE, drag_window_callback, event);
549
550     if (!con_exists(con)) {
551         DLOG("The container has been closed in the meantime.\n");
552         return;
553     }
554
555     /* If the user cancelled, undo the changes. */
556     if (drag_result == DRAG_REVERT) {
557         floating_reposition(con, initial_rect);
558         return;
559     }
560
561     /* If this is a scratchpad window, don't auto center it from now on. */
562     if (con->scratchpad_state == SCRATCHPAD_FRESH)
563         con->scratchpad_state = SCRATCHPAD_CHANGED;
564
565     tree_render();
566 }
567
568 /*
569  * This is an ugly data structure which we need because there is no standard
570  * way of having nested functions (only available as a gcc extension at the
571  * moment, clang doesn’t support it) or blocks (only available as a clang
572  * extension and only on Mac OS X systems at the moment).
573  *
574  */
575 struct resize_window_callback_params {
576     const border_t corner;
577     const bool proportional;
578     const xcb_button_press_event_t *event;
579 };
580
581 DRAGGING_CB(resize_window_callback) {
582     const struct resize_window_callback_params *params = extra;
583     const xcb_button_press_event_t *event = params->event;
584     border_t corner = params->corner;
585
586     int32_t dest_x = con->rect.x;
587     int32_t dest_y = con->rect.y;
588     uint32_t dest_width;
589     uint32_t dest_height;
590
591     double ratio = (double)old_rect->width / old_rect->height;
592
593     /* First guess: We resize by exactly the amount the mouse moved,
594      * taking into account in which corner the client was grabbed */
595     if (corner & BORDER_LEFT)
596         dest_width = old_rect->width - (new_x - event->root_x);
597     else
598         dest_width = old_rect->width + (new_x - event->root_x);
599
600     if (corner & BORDER_TOP)
601         dest_height = old_rect->height - (new_y - event->root_y);
602     else
603         dest_height = old_rect->height + (new_y - event->root_y);
604
605     /* User wants to keep proportions, so we may have to adjust our values */
606     if (params->proportional) {
607         dest_width = max(dest_width, (int)(dest_height * ratio));
608         dest_height = max(dest_height, (int)(dest_width / ratio));
609     }
610
611     con->rect = (Rect){dest_x, dest_y, dest_width, dest_height};
612
613     /* Obey window size */
614     floating_check_size(con);
615
616     /* If not the lower right corner is grabbed, we must also reposition
617      * the client by exactly the amount we resized it */
618     if (corner & BORDER_LEFT)
619         dest_x = old_rect->x + (old_rect->width - con->rect.width);
620
621     if (corner & BORDER_TOP)
622         dest_y = old_rect->y + (old_rect->height - con->rect.height);
623
624     con->rect.x = dest_x;
625     con->rect.y = dest_y;
626
627     /* TODO: don’t re-render the whole tree just because we change
628      * coordinates of a floating window */
629     tree_render();
630     x_push_changes(croot);
631 }
632
633 /*
634  * Called when the user clicked on a floating window while holding the
635  * floating_modifier and the right mouse button.
636  * Calls the drag_pointer function with the resize_window callback
637  *
638  */
639 void floating_resize_window(Con *con, const bool proportional,
640                             const xcb_button_press_event_t *event) {
641     DLOG("floating_resize_window\n");
642
643     /* corner saves the nearest corner to the original click. It contains
644      * a bitmask of the nearest borders (BORDER_LEFT, BORDER_RIGHT, …) */
645     border_t corner = 0;
646
647     if (event->event_x <= (int16_t)(con->rect.width / 2))
648         corner |= BORDER_LEFT;
649     else
650         corner |= BORDER_RIGHT;
651
652     int cursor = 0;
653     if (event->event_y <= (int16_t)(con->rect.height / 2)) {
654         corner |= BORDER_TOP;
655         cursor = (corner & BORDER_LEFT) ? XCURSOR_CURSOR_TOP_LEFT_CORNER : XCURSOR_CURSOR_TOP_RIGHT_CORNER;
656     } else {
657         corner |= BORDER_BOTTOM;
658         cursor = (corner & BORDER_LEFT) ? XCURSOR_CURSOR_BOTTOM_LEFT_CORNER : XCURSOR_CURSOR_BOTTOM_RIGHT_CORNER;
659     }
660
661     struct resize_window_callback_params params = {corner, proportional, event};
662
663     /* get the initial rect in case of revert/cancel */
664     Rect initial_rect = con->rect;
665
666     drag_result_t drag_result = drag_pointer(con, event, XCB_NONE, BORDER_TOP /* irrelevant */, cursor, resize_window_callback, &params);
667
668     if (!con_exists(con)) {
669         DLOG("The container has been closed in the meantime.\n");
670         return;
671     }
672
673     /* If the user cancels, undo the resize */
674     if (drag_result == DRAG_REVERT)
675         floating_reposition(con, initial_rect);
676
677     /* If this is a scratchpad window, don't auto center it from now on. */
678     if (con->scratchpad_state == SCRATCHPAD_FRESH)
679         con->scratchpad_state = SCRATCHPAD_CHANGED;
680 }
681
682 /* Custom data structure used to track dragging-related events. */
683 struct drag_x11_cb {
684     ev_prepare prepare;
685
686     /* Whether this modal event loop should be exited and with which result. */
687     drag_result_t result;
688
689     /* The container that is being dragged or resized, or NULL if this is a
690      * drag of the resize handle. */
691     Con *con;
692
693     /* The dimensions of con when the loop was started. */
694     Rect old_rect;
695
696     /* The callback to invoke after every pointer movement. */
697     callback_t callback;
698
699     /* User data pointer for callback. */
700     const void *extra;
701 };
702
703 static bool drain_drag_events(EV_P, struct drag_x11_cb *dragloop) {
704     xcb_motion_notify_event_t *last_motion_notify = NULL;
705     xcb_generic_event_t *event;
706
707     while ((event = xcb_poll_for_event(conn)) != NULL) {
708         if (event->response_type == 0) {
709             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
710             DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
711                  error->sequence, error->error_code);
712             free(event);
713             continue;
714         }
715
716         /* Strip off the highest bit (set if the event is generated) */
717         int type = (event->response_type & 0x7F);
718
719         switch (type) {
720             case XCB_BUTTON_RELEASE:
721                 dragloop->result = DRAG_SUCCESS;
722                 break;
723
724             case XCB_KEY_PRESS:
725                 DLOG("A key was pressed during drag, reverting changes.\n");
726                 dragloop->result = DRAG_REVERT;
727                 handle_event(type, event);
728                 break;
729
730             case XCB_UNMAP_NOTIFY: {
731                 xcb_unmap_notify_event_t *unmap_event = (xcb_unmap_notify_event_t *)event;
732                 Con *con = con_by_window_id(unmap_event->window);
733
734                 if (con != NULL) {
735                     DLOG("UnmapNotify for window 0x%08x (container %p)\n", unmap_event->window, con);
736
737                     if (con_get_workspace(con) == con_get_workspace(focused)) {
738                         DLOG("UnmapNotify for a managed window on the current workspace, aborting\n");
739                         dragloop->result = DRAG_ABORT;
740                     }
741                 }
742
743                 handle_event(type, event);
744                 break;
745             }
746
747             case XCB_MOTION_NOTIFY:
748                 /* motion_notify events are saved for later */
749                 FREE(last_motion_notify);
750                 last_motion_notify = (xcb_motion_notify_event_t *)event;
751                 break;
752
753             default:
754                 DLOG("Passing to original handler\n");
755                 handle_event(type, event);
756                 break;
757         }
758
759         if (last_motion_notify != (xcb_motion_notify_event_t *)event)
760             free(event);
761
762         if (dragloop->result != DRAGGING) {
763             ev_break(EV_A_ EVBREAK_ONE);
764             if (dragloop->result == DRAG_SUCCESS) {
765                 /* Ensure motion notify events are handled. */
766                 break;
767             } else {
768                 free(last_motion_notify);
769                 return true;
770             }
771         }
772     }
773
774     if (last_motion_notify == NULL) {
775         return true;
776     }
777
778     /* Ensure that we are either dragging the resize handle (con is NULL) or that the
779      * container still exists. The latter might not be true, e.g., if the window closed
780      * for any reason while the user was dragging it. */
781     if (!dragloop->con || con_exists(dragloop->con)) {
782         dragloop->callback(
783             dragloop->con,
784             &(dragloop->old_rect),
785             last_motion_notify->root_x,
786             last_motion_notify->root_y,
787             dragloop->extra);
788     }
789     FREE(last_motion_notify);
790
791     xcb_flush(conn);
792     return dragloop->result != DRAGGING;
793 }
794
795 static void xcb_drag_prepare_cb(EV_P_ ev_prepare *w, int revents) {
796     struct drag_x11_cb *dragloop = (struct drag_x11_cb *)w->data;
797     while (!drain_drag_events(EV_A, dragloop)) {
798         /* repeatedly drain events: draining might produce additional ones */
799     }
800 }
801
802 /*
803  * This function grabs your pointer and keyboard and lets you drag stuff around
804  * (borders). Every time you move your mouse, an XCB_MOTION_NOTIFY event will
805  * be received and the given callback will be called with the parameters
806  * specified (client, border on which the click originally was), the original
807  * rect of the client, the event and the new coordinates (x, y).
808  *
809  */
810 drag_result_t drag_pointer(Con *con, const xcb_button_press_event_t *event, xcb_window_t confine_to,
811                            border_t border, int cursor, callback_t callback, const void *extra) {
812     xcb_cursor_t xcursor = (cursor && xcursor_supported) ? xcursor_get_cursor(cursor) : XCB_NONE;
813
814     /* Grab the pointer */
815     xcb_grab_pointer_cookie_t cookie;
816     xcb_grab_pointer_reply_t *reply;
817     xcb_generic_error_t *error;
818
819     cookie = xcb_grab_pointer(conn,
820                               false,                                                         /* get all pointer events specified by the following mask */
821                               root,                                                          /* grab the root window */
822                               XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION, /* which events to let through */
823                               XCB_GRAB_MODE_ASYNC,                                           /* pointer events should continue as normal */
824                               XCB_GRAB_MODE_ASYNC,                                           /* keyboard mode */
825                               confine_to,                                                    /* confine_to = in which window should the cursor stay */
826                               xcursor,                                                       /* possibly display a special cursor */
827                               XCB_CURRENT_TIME);
828
829     if ((reply = xcb_grab_pointer_reply(conn, cookie, &error)) == NULL) {
830         ELOG("Could not grab pointer (error_code = %d)\n", error->error_code);
831         free(error);
832         return DRAG_ABORT;
833     }
834
835     free(reply);
836
837     /* Grab the keyboard */
838     xcb_grab_keyboard_cookie_t keyb_cookie;
839     xcb_grab_keyboard_reply_t *keyb_reply;
840
841     keyb_cookie = xcb_grab_keyboard(conn,
842                                     false, /* get all keyboard events */
843                                     root,  /* grab the root window */
844                                     XCB_CURRENT_TIME,
845                                     XCB_GRAB_MODE_ASYNC, /* continue processing pointer events as normal */
846                                     XCB_GRAB_MODE_ASYNC  /* keyboard mode */
847                                     );
848
849     if ((keyb_reply = xcb_grab_keyboard_reply(conn, keyb_cookie, &error)) == NULL) {
850         ELOG("Could not grab keyboard (error_code = %d)\n", error->error_code);
851         free(error);
852         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
853         return DRAG_ABORT;
854     }
855
856     free(keyb_reply);
857
858     /* Go into our own event loop */
859     struct drag_x11_cb loop = {
860         .result = DRAGGING,
861         .con = con,
862         .callback = callback,
863         .extra = extra,
864     };
865     ev_prepare *prepare = &loop.prepare;
866     if (con)
867         loop.old_rect = con->rect;
868     ev_prepare_init(prepare, xcb_drag_prepare_cb);
869     prepare->data = &loop;
870     main_set_x11_cb(false);
871     ev_prepare_start(main_loop, prepare);
872
873     ev_loop(main_loop, 0);
874
875     ev_prepare_stop(main_loop, prepare);
876     main_set_x11_cb(true);
877
878     xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
879     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
880     xcb_flush(conn);
881
882     return loop.result;
883 }
884
885 /*
886  * Repositions the CT_FLOATING_CON to have the coordinates specified by
887  * newrect, but only if the coordinates are not out-of-bounds. Also reassigns
888  * the floating con to a different workspace if this move was across different
889  * outputs.
890  *
891  */
892 bool floating_reposition(Con *con, Rect newrect) {
893     /* Sanity check: Are the new coordinates on any output? If not, we
894      * ignore that request. */
895     if (!output_containing_rect(newrect)) {
896         ELOG("No output found at destination coordinates. Not repositioning.\n");
897         return false;
898     }
899
900     con->rect = newrect;
901
902     bool reassigned = floating_maybe_reassign_ws(con);
903
904     /* If this is a scratchpad window, don't auto center it from now on. */
905     if (con->scratchpad_state == SCRATCHPAD_FRESH)
906         con->scratchpad_state = SCRATCHPAD_CHANGED;
907
908     /* Workspace change will already result in a tree_render. */
909     if (!reassigned) {
910         tree_render();
911     }
912     return true;
913 }
914
915 /*
916  * Sets size of the CT_FLOATING_CON to specified dimensions. Might limit the
917  * actual size with regard to size constraints taken from user settings.
918  * Additionally, the dimensions may be upscaled until they're divisible by the
919  * window's size hints.
920  *
921  */
922 void floating_resize(Con *floating_con, int x, int y) {
923     DLOG("floating resize to %dx%d px\n", x, y);
924     Rect *rect = &floating_con->rect;
925     Con *focused_con = con_descend_focused(floating_con);
926     if (focused_con->window == NULL) {
927         DLOG("No window is focused. Not resizing.\n");
928         return;
929     }
930     int wi = focused_con->window->width_increment;
931     int hi = focused_con->window->height_increment;
932     rect->width = x;
933     rect->height = y;
934     if (wi)
935         rect->width += (wi - 1 - rect->width) % wi;
936     if (hi)
937         rect->height += (hi - 1 - rect->height) % hi;
938
939     floating_check_size(floating_con);
940
941     /* If this is a scratchpad window, don't auto center it from now on. */
942     if (floating_con->scratchpad_state == SCRATCHPAD_FRESH)
943         floating_con->scratchpad_state = SCRATCHPAD_CHANGED;
944 }
945
946 /*
947  * Fixes the coordinates of the floating window whenever the window gets
948  * reassigned to a different output (or when the output’s rect changes).
949  *
950  */
951 void floating_fix_coordinates(Con *con, Rect *old_rect, Rect *new_rect) {
952     DLOG("Fixing coordinates of floating window %p (rect (%d, %d), %d x %d)\n",
953          con, con->rect.x, con->rect.y, con->rect.width, con->rect.height);
954     DLOG("old_rect = (%d, %d), %d x %d\n",
955          old_rect->x, old_rect->y, old_rect->width, old_rect->height);
956     DLOG("new_rect = (%d, %d), %d x %d\n",
957          new_rect->x, new_rect->y, new_rect->width, new_rect->height);
958     /* First we get the x/y coordinates relative to the x/y coordinates
959      * of the output on which the window is on */
960     int32_t rel_x = con->rect.x - old_rect->x + (int32_t)(con->rect.width / 2);
961     int32_t rel_y = con->rect.y - old_rect->y + (int32_t)(con->rect.height / 2);
962     /* Then we calculate a fraction, for example 0.63 for a window
963      * which is at y = 1212 of a 1920 px high output */
964     DLOG("rel_x = %d, rel_y = %d, fraction_x = %f, fraction_y = %f, output->w = %d, output->h = %d\n",
965          rel_x, rel_y, (double)rel_x / old_rect->width, (double)rel_y / old_rect->height,
966          old_rect->width, old_rect->height);
967     /* Here we have to multiply at first. Or we will lose precision when not compiled with -msse2 */
968     con->rect.x = (int32_t)new_rect->x + (double)(rel_x * (int32_t)new_rect->width) / (int32_t)old_rect->width - (int32_t)(con->rect.width / 2);
969     con->rect.y = (int32_t)new_rect->y + (double)(rel_y * (int32_t)new_rect->height) / (int32_t)old_rect->height - (int32_t)(con->rect.height / 2);
970     DLOG("Resulting coordinates: x = %d, y = %d\n", con->rect.x, con->rect.y);
971 }