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