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