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