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