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