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