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