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