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