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