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