]> git.sur5r.net Git - i3/i3/blob - src/floating.c
Use con_detach instead of TAILQ_REMOVE in floating
[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     const bool set_focus = (con == focused);
331
332     Con *ws = con_get_workspace(con);
333     Con *parent = con->parent;
334
335     /* 1: detach from parent container */
336     con_detach(con);
337
338     /* 2: kill parent container */
339     con_detach(con->parent);
340     /* clear the pointer before calling tree_close_internal in which the memory is freed */
341     con->parent = NULL;
342     tree_close_internal(parent, DONT_KILL_WINDOW, true, false);
343
344     /* 3: re-attach to the parent of the currently focused con on the workspace
345      * this floating con was on */
346     Con *focused = con_descend_tiling_focused(ws);
347
348     /* if there is no other container on this workspace, focused will be the
349      * workspace itself */
350     if (focused->type == CT_WORKSPACE)
351         con->parent = focused;
352     else
353         con->parent = focused->parent;
354
355     /* con_fix_percent will adjust the percent value */
356     con->percent = 0.0;
357
358     con->floating = FLOATING_USER_OFF;
359
360     con_attach(con, con->parent, false);
361
362     con_fix_percent(con->parent);
363
364     if (set_focus)
365         con_activate(con);
366
367     floating_set_hint_atom(con, false);
368     ipc_send_window_event("floating", con);
369 }
370
371 /*
372  * Toggles floating mode for the given container.
373  *
374  * If the automatic flag is set to true, this was an automatic update by a change of the
375  * window class from the application which can be overwritten by the user.
376  *
377  */
378 void toggle_floating_mode(Con *con, bool automatic) {
379     /* forbid the command to toggle floating on a CT_FLOATING_CON */
380     if (con->type == CT_FLOATING_CON) {
381         ELOG("Cannot toggle floating mode on con = %p because it is of type CT_FLOATING_CON.\n", con);
382         return;
383     }
384
385     /* see if the client is already floating */
386     if (con_is_floating(con)) {
387         LOG("already floating, re-setting to tiling\n");
388
389         floating_disable(con, automatic);
390         return;
391     }
392
393     floating_enable(con, automatic);
394 }
395
396 /*
397  * Raises the given container in the list of floating containers
398  *
399  */
400 void floating_raise_con(Con *con) {
401     DLOG("Raising floating con %p / %s\n", con, con->name);
402     TAILQ_REMOVE(&(con->parent->floating_head), con, floating_windows);
403     TAILQ_INSERT_TAIL(&(con->parent->floating_head), con, floating_windows);
404 }
405
406 /*
407  * Checks if con’s coordinates are within its workspace and re-assigns it to
408  * the actual workspace if not.
409  *
410  */
411 bool floating_maybe_reassign_ws(Con *con) {
412     Output *output = get_output_from_rect(con->rect);
413
414     if (!output) {
415         ELOG("No output found at destination coordinates?\n");
416         return false;
417     }
418
419     if (con_get_output(con) == output->con) {
420         DLOG("still the same ws\n");
421         return false;
422     }
423
424     DLOG("Need to re-assign!\n");
425
426     Con *content = output_get_content(output->con);
427     Con *ws = TAILQ_FIRST(&(content->focus_head));
428     DLOG("Moving con %p / %s to workspace %p / %s\n", con, con->name, ws, ws->name);
429     con_move_to_workspace(con, ws, false, true, false);
430     workspace_show(ws);
431     con_activate(con_descend_focused(con));
432     return true;
433 }
434
435 /*
436  * Centers a floating con above the specified rect.
437  *
438  */
439 void floating_center(Con *con, Rect rect) {
440     con->rect.x = rect.x + (rect.width / 2) - (con->rect.width / 2);
441     con->rect.y = rect.y + (rect.height / 2) - (con->rect.height / 2);
442 }
443
444 /*
445  * Moves the given floating con to the current pointer position.
446  *
447  */
448 void floating_move_to_pointer(Con *con) {
449     assert(con->type == CT_FLOATING_CON);
450
451     xcb_query_pointer_reply_t *reply = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL);
452     if (reply == NULL) {
453         ELOG("could not query pointer position, not moving this container\n");
454         return;
455     }
456
457     Output *output = get_output_containing(reply->root_x, reply->root_y);
458     if (output == NULL) {
459         ELOG("The pointer is not on any output, cannot move the container here.\n");
460         return;
461     }
462
463     /* Determine where to put the window. */
464     int32_t x = reply->root_x - con->rect.width / 2;
465     int32_t y = reply->root_y - con->rect.height / 2;
466     FREE(reply);
467
468     /* Correct target coordinates to be in-bounds. */
469     x = MAX(x, (int32_t)output->rect.x);
470     y = MAX(y, (int32_t)output->rect.y);
471     if (x + con->rect.width > output->rect.x + output->rect.width)
472         x = output->rect.x + output->rect.width - con->rect.width;
473     if (y + con->rect.height > output->rect.y + output->rect.height)
474         y = output->rect.y + output->rect.height - con->rect.height;
475
476     /* Update container's coordinates to position it correctly. */
477     floating_reposition(con, (Rect){x, y, con->rect.width, con->rect.height});
478 }
479
480 DRAGGING_CB(drag_window_callback) {
481     const struct xcb_button_press_event_t *event = extra;
482
483     /* Reposition the client correctly while moving */
484     con->rect.x = old_rect->x + (new_x - event->root_x);
485     con->rect.y = old_rect->y + (new_y - event->root_y);
486
487     render_con(con, false);
488     x_push_node(con);
489     xcb_flush(conn);
490
491     /* Check if we cross workspace boundaries while moving */
492     if (!floating_maybe_reassign_ws(con))
493         return;
494     /* Ensure not to warp the pointer while dragging */
495     x_set_warp_to(NULL);
496     tree_render();
497 }
498
499 /*
500  * Called when the user clicked on the titlebar of a floating window.
501  * Calls the drag_pointer function with the drag_window callback
502  *
503  */
504 void floating_drag_window(Con *con, const xcb_button_press_event_t *event) {
505     DLOG("floating_drag_window\n");
506
507     /* Push changes before dragging, so that the window gets raised now and not
508      * after the user releases the mouse button */
509     tree_render();
510
511     /* Store the initial rect in case of user revert/cancel */
512     Rect initial_rect = con->rect;
513
514     /* Drag the window */
515     drag_result_t drag_result = drag_pointer(con, event, XCB_NONE, BORDER_TOP /* irrelevant */, XCURSOR_CURSOR_MOVE, drag_window_callback, event);
516
517     if (!con_exists(con)) {
518         DLOG("The container has been closed in the meantime.\n");
519         return;
520     }
521
522     /* If the user cancelled, undo the changes. */
523     if (drag_result == DRAG_REVERT)
524         floating_reposition(con, initial_rect);
525
526     /* If this is a scratchpad window, don't auto center it from now on. */
527     if (con->scratchpad_state == SCRATCHPAD_FRESH)
528         con->scratchpad_state = SCRATCHPAD_CHANGED;
529
530     tree_render();
531 }
532
533 /*
534  * This is an ugly data structure which we need because there is no standard
535  * way of having nested functions (only available as a gcc extension at the
536  * moment, clang doesn’t support it) or blocks (only available as a clang
537  * extension and only on Mac OS X systems at the moment).
538  *
539  */
540 struct resize_window_callback_params {
541     const border_t corner;
542     const bool proportional;
543     const xcb_button_press_event_t *event;
544 };
545
546 DRAGGING_CB(resize_window_callback) {
547     const struct resize_window_callback_params *params = extra;
548     const xcb_button_press_event_t *event = params->event;
549     border_t corner = params->corner;
550
551     int32_t dest_x = con->rect.x;
552     int32_t dest_y = con->rect.y;
553     uint32_t dest_width;
554     uint32_t dest_height;
555
556     double ratio = (double)old_rect->width / old_rect->height;
557
558     /* First guess: We resize by exactly the amount the mouse moved,
559      * taking into account in which corner the client was grabbed */
560     if (corner & BORDER_LEFT)
561         dest_width = old_rect->width - (new_x - event->root_x);
562     else
563         dest_width = old_rect->width + (new_x - event->root_x);
564
565     if (corner & BORDER_TOP)
566         dest_height = old_rect->height - (new_y - event->root_y);
567     else
568         dest_height = old_rect->height + (new_y - event->root_y);
569
570     /* User wants to keep proportions, so we may have to adjust our values */
571     if (params->proportional) {
572         dest_width = max(dest_width, (int)(dest_height * ratio));
573         dest_height = max(dest_height, (int)(dest_width / ratio));
574     }
575
576     con->rect = (Rect){dest_x, dest_y, dest_width, dest_height};
577
578     /* Obey window size */
579     floating_check_size(con);
580
581     /* If not the lower right corner is grabbed, we must also reposition
582      * the client by exactly the amount we resized it */
583     if (corner & BORDER_LEFT)
584         dest_x = old_rect->x + (old_rect->width - con->rect.width);
585
586     if (corner & BORDER_TOP)
587         dest_y = old_rect->y + (old_rect->height - con->rect.height);
588
589     con->rect.x = dest_x;
590     con->rect.y = dest_y;
591
592     /* TODO: don’t re-render the whole tree just because we change
593      * coordinates of a floating window */
594     tree_render();
595     x_push_changes(croot);
596 }
597
598 /*
599  * Called when the user clicked on a floating window while holding the
600  * floating_modifier and the right mouse button.
601  * Calls the drag_pointer function with the resize_window callback
602  *
603  */
604 void floating_resize_window(Con *con, const bool proportional,
605                             const xcb_button_press_event_t *event) {
606     DLOG("floating_resize_window\n");
607
608     /* corner saves the nearest corner to the original click. It contains
609      * a bitmask of the nearest borders (BORDER_LEFT, BORDER_RIGHT, …) */
610     border_t corner = 0;
611
612     if (event->event_x <= (int16_t)(con->rect.width / 2))
613         corner |= BORDER_LEFT;
614     else
615         corner |= BORDER_RIGHT;
616
617     int cursor = 0;
618     if (event->event_y <= (int16_t)(con->rect.height / 2)) {
619         corner |= BORDER_TOP;
620         cursor = (corner & BORDER_LEFT) ? XCURSOR_CURSOR_TOP_LEFT_CORNER : XCURSOR_CURSOR_TOP_RIGHT_CORNER;
621     } else {
622         corner |= BORDER_BOTTOM;
623         cursor = (corner & BORDER_LEFT) ? XCURSOR_CURSOR_BOTTOM_LEFT_CORNER : XCURSOR_CURSOR_BOTTOM_RIGHT_CORNER;
624     }
625
626     struct resize_window_callback_params params = {corner, proportional, event};
627
628     /* get the initial rect in case of revert/cancel */
629     Rect initial_rect = con->rect;
630
631     drag_result_t drag_result = drag_pointer(con, event, XCB_NONE, BORDER_TOP /* irrelevant */, cursor, resize_window_callback, &params);
632
633     if (!con_exists(con)) {
634         DLOG("The container has been closed in the meantime.\n");
635         return;
636     }
637
638     /* If the user cancels, undo the resize */
639     if (drag_result == DRAG_REVERT)
640         floating_reposition(con, initial_rect);
641
642     /* If this is a scratchpad window, don't auto center it from now on. */
643     if (con->scratchpad_state == SCRATCHPAD_FRESH)
644         con->scratchpad_state = SCRATCHPAD_CHANGED;
645 }
646
647 /* Custom data structure used to track dragging-related events. */
648 struct drag_x11_cb {
649     ev_prepare prepare;
650
651     /* Whether this modal event loop should be exited and with which result. */
652     drag_result_t result;
653
654     /* The container that is being dragged or resized, or NULL if this is a
655      * drag of the resize handle. */
656     Con *con;
657
658     /* The dimensions of con when the loop was started. */
659     Rect old_rect;
660
661     /* The callback to invoke after every pointer movement. */
662     callback_t callback;
663
664     /* User data pointer for callback. */
665     const void *extra;
666 };
667
668 static bool drain_drag_events(EV_P, struct drag_x11_cb *dragloop) {
669     xcb_motion_notify_event_t *last_motion_notify = NULL;
670     xcb_generic_event_t *event;
671
672     while ((event = xcb_poll_for_event(conn)) != NULL) {
673         if (event->response_type == 0) {
674             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
675             DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
676                  error->sequence, error->error_code);
677             free(event);
678             continue;
679         }
680
681         /* Strip off the highest bit (set if the event is generated) */
682         int type = (event->response_type & 0x7F);
683
684         switch (type) {
685             case XCB_BUTTON_RELEASE:
686                 dragloop->result = DRAG_SUCCESS;
687                 break;
688
689             case XCB_KEY_PRESS:
690                 DLOG("A key was pressed during drag, reverting changes.\n");
691                 dragloop->result = DRAG_REVERT;
692                 handle_event(type, event);
693                 break;
694
695             case XCB_UNMAP_NOTIFY: {
696                 xcb_unmap_notify_event_t *unmap_event = (xcb_unmap_notify_event_t *)event;
697                 Con *con = con_by_window_id(unmap_event->window);
698
699                 if (con != NULL) {
700                     DLOG("UnmapNotify for window 0x%08x (container %p)\n", unmap_event->window, con);
701
702                     if (con_get_workspace(con) == con_get_workspace(focused)) {
703                         DLOG("UnmapNotify for a managed window on the current workspace, aborting\n");
704                         dragloop->result = DRAG_ABORT;
705                     }
706                 }
707
708                 handle_event(type, event);
709                 break;
710             }
711
712             case XCB_MOTION_NOTIFY:
713                 /* motion_notify events are saved for later */
714                 FREE(last_motion_notify);
715                 last_motion_notify = (xcb_motion_notify_event_t *)event;
716                 break;
717
718             default:
719                 DLOG("Passing to original handler\n");
720                 handle_event(type, event);
721                 break;
722         }
723
724         if (last_motion_notify != (xcb_motion_notify_event_t *)event)
725             free(event);
726
727         if (dragloop->result != DRAGGING) {
728             free(last_motion_notify);
729             ev_break(EV_A_ EVBREAK_ONE);
730             return true;
731         }
732     }
733
734     if (last_motion_notify == NULL) {
735         return true;
736     }
737
738     /* Ensure that we are either dragging the resize handle (con is NULL) or that the
739      * container still exists. The latter might not be true, e.g., if the window closed
740      * for any reason while the user was dragging it. */
741     if (!dragloop->con || con_exists(dragloop->con)) {
742         dragloop->callback(
743             dragloop->con,
744             &(dragloop->old_rect),
745             last_motion_notify->root_x,
746             last_motion_notify->root_y,
747             dragloop->extra);
748     }
749     FREE(last_motion_notify);
750
751     xcb_flush(conn);
752     return false;
753 }
754
755 static void xcb_drag_prepare_cb(EV_P_ ev_prepare *w, int revents) {
756     struct drag_x11_cb *dragloop = (struct drag_x11_cb *)w->data;
757     while (!drain_drag_events(EV_A, dragloop)) {
758         /* repeatedly drain events: draining might produce additional ones */
759     }
760 }
761
762 /*
763  * This function grabs your pointer and keyboard and lets you drag stuff around
764  * (borders). Every time you move your mouse, an XCB_MOTION_NOTIFY event will
765  * be received and the given callback will be called with the parameters
766  * specified (client, border on which the click originally was), the original
767  * rect of the client, the event and the new coordinates (x, y).
768  *
769  */
770 drag_result_t drag_pointer(Con *con, const xcb_button_press_event_t *event, xcb_window_t
771                                                                                 confine_to,
772                            border_t border, int cursor, callback_t callback, const void *extra) {
773     xcb_cursor_t xcursor = (cursor && xcursor_supported) ? xcursor_get_cursor(cursor) : XCB_NONE;
774
775     /* Grab the pointer */
776     xcb_grab_pointer_cookie_t cookie;
777     xcb_grab_pointer_reply_t *reply;
778     xcb_generic_error_t *error;
779
780     cookie = xcb_grab_pointer(conn,
781                               false,                                                         /* get all pointer events specified by the following mask */
782                               root,                                                          /* grab the root window */
783                               XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION, /* which events to let through */
784                               XCB_GRAB_MODE_ASYNC,                                           /* pointer events should continue as normal */
785                               XCB_GRAB_MODE_ASYNC,                                           /* keyboard mode */
786                               confine_to,                                                    /* confine_to = in which window should the cursor stay */
787                               xcursor,                                                       /* possibly display a special cursor */
788                               XCB_CURRENT_TIME);
789
790     if ((reply = xcb_grab_pointer_reply(conn, cookie, &error)) == NULL) {
791         ELOG("Could not grab pointer (error_code = %d)\n", error->error_code);
792         free(error);
793         return DRAG_ABORT;
794     }
795
796     free(reply);
797
798     /* Grab the keyboard */
799     xcb_grab_keyboard_cookie_t keyb_cookie;
800     xcb_grab_keyboard_reply_t *keyb_reply;
801
802     keyb_cookie = xcb_grab_keyboard(conn,
803                                     false, /* get all keyboard events */
804                                     root,  /* grab the root window */
805                                     XCB_CURRENT_TIME,
806                                     XCB_GRAB_MODE_ASYNC, /* continue processing pointer events as normal */
807                                     XCB_GRAB_MODE_ASYNC  /* keyboard mode */
808                                     );
809
810     if ((keyb_reply = xcb_grab_keyboard_reply(conn, keyb_cookie, &error)) == NULL) {
811         ELOG("Could not grab keyboard (error_code = %d)\n", error->error_code);
812         free(error);
813         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
814         return DRAG_ABORT;
815     }
816
817     free(keyb_reply);
818
819     /* Go into our own event loop */
820     struct drag_x11_cb loop = {
821         .result = DRAGGING,
822         .con = con,
823         .callback = callback,
824         .extra = extra,
825     };
826     ev_prepare *prepare = &loop.prepare;
827     if (con)
828         loop.old_rect = con->rect;
829     ev_prepare_init(prepare, xcb_drag_prepare_cb);
830     prepare->data = &loop;
831     main_set_x11_cb(false);
832     ev_prepare_start(main_loop, prepare);
833
834     ev_loop(main_loop, 0);
835
836     ev_prepare_stop(main_loop, prepare);
837     main_set_x11_cb(true);
838
839     xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
840     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
841     xcb_flush(conn);
842
843     return loop.result;
844 }
845
846 /*
847  * Repositions the CT_FLOATING_CON to have the coordinates specified by
848  * newrect, but only if the coordinates are not out-of-bounds. Also reassigns
849  * the floating con to a different workspace if this move was across different
850  * outputs.
851  *
852  */
853 bool floating_reposition(Con *con, Rect newrect) {
854     /* Sanity check: Are the new coordinates on any output? If not, we
855      * ignore that request. */
856     if (!output_containing_rect(newrect)) {
857         ELOG("No output found at destination coordinates. Not repositioning.\n");
858         return false;
859     }
860
861     con->rect = newrect;
862
863     floating_maybe_reassign_ws(con);
864
865     /* If this is a scratchpad window, don't auto center it from now on. */
866     if (con->scratchpad_state == SCRATCHPAD_FRESH)
867         con->scratchpad_state = SCRATCHPAD_CHANGED;
868
869     tree_render();
870     return true;
871 }
872
873 /*
874  * Sets size of the CT_FLOATING_CON to specified dimensions. Might limit the
875  * actual size with regard to size constraints taken from user settings.
876  * Additionally, the dimensions may be upscaled until they're divisible by the
877  * window's size hints.
878  *
879  */
880 void floating_resize(Con *floating_con, int x, int y) {
881     DLOG("floating resize to %dx%d px\n", x, y);
882     Rect *rect = &floating_con->rect;
883     Con *focused_con = con_descend_focused(floating_con);
884     if (focused_con->window == NULL) {
885         DLOG("No window is focused. Not resizing.\n");
886         return;
887     }
888     int wi = focused_con->window->width_increment;
889     int hi = focused_con->window->height_increment;
890     rect->width = x;
891     rect->height = y;
892     if (wi)
893         rect->width += (wi - 1 - rect->width) % wi;
894     if (hi)
895         rect->height += (hi - 1 - rect->height) % hi;
896
897     floating_check_size(floating_con);
898
899     /* If this is a scratchpad window, don't auto center it from now on. */
900     if (floating_con->scratchpad_state == SCRATCHPAD_FRESH)
901         floating_con->scratchpad_state = SCRATCHPAD_CHANGED;
902 }
903
904 /*
905  * Fixes the coordinates of the floating window whenever the window gets
906  * reassigned to a different output (or when the output’s rect changes).
907  *
908  */
909 void floating_fix_coordinates(Con *con, Rect *old_rect, Rect *new_rect) {
910     DLOG("Fixing coordinates of floating window %p (rect (%d, %d), %d x %d)\n",
911          con, con->rect.x, con->rect.y, con->rect.width, con->rect.height);
912     DLOG("old_rect = (%d, %d), %d x %d\n",
913          old_rect->x, old_rect->y, old_rect->width, old_rect->height);
914     DLOG("new_rect = (%d, %d), %d x %d\n",
915          new_rect->x, new_rect->y, new_rect->width, new_rect->height);
916     /* First we get the x/y coordinates relative to the x/y coordinates
917      * of the output on which the window is on */
918     int32_t rel_x = con->rect.x - old_rect->x + (int32_t)(con->rect.width / 2);
919     int32_t rel_y = con->rect.y - old_rect->y + (int32_t)(con->rect.height / 2);
920     /* Then we calculate a fraction, for example 0.63 for a window
921      * which is at y = 1212 of a 1920 px high output */
922     DLOG("rel_x = %d, rel_y = %d, fraction_x = %f, fraction_y = %f, output->w = %d, output->h = %d\n",
923          rel_x, rel_y, (double)rel_x / old_rect->width, (double)rel_y / old_rect->height,
924          old_rect->width, old_rect->height);
925     /* Here we have to multiply at first. Or we will lose precision when not compiled with -msse2 */
926     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);
927     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);
928     DLOG("Resulting coordinates: x = %d, y = %d\n", con->rect.x, con->rect.y);
929 }