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