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