]> git.sur5r.net Git - i3/i3/blob - src/con.c
explicitly set filenames to $(basename __FILE__)
[i3/i3] / src / con.c
1 #line 2 "con.c"
2 /*
3  * vim:ts=4:sw=4:expandtab
4  *
5  * i3 - an improved dynamic tiling window manager
6  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
7  *
8  * con.c: Functions which deal with containers directly (creating containers,
9  *        searching containers, getting specific properties from containers,
10  *        …).
11  *
12  */
13 #include "all.h"
14
15 char *colors[] = {
16     "#ff0000",
17     "#00FF00",
18     "#0000FF",
19     "#ff00ff",
20     "#00ffff",
21     "#ffff00",
22     "#aa0000",
23     "#00aa00",
24     "#0000aa",
25     "#aa00aa"
26 };
27
28 static void con_on_remove_child(Con *con);
29
30 /*
31  * Create a new container (and attach it to the given parent, if not NULL).
32  * This function initializes the data structures and creates the appropriate
33  * X11 IDs using x_con_init().
34  *
35  */
36 Con *con_new(Con *parent, i3Window *window) {
37     Con *new = scalloc(sizeof(Con));
38     new->on_remove_child = con_on_remove_child;
39     TAILQ_INSERT_TAIL(&all_cons, new, all_cons);
40     new->type = CT_CON;
41     new->window = window;
42     new->border_style = config.default_border;
43     static int cnt = 0;
44     DLOG("opening window %d\n", cnt);
45
46     /* TODO: remove window coloring after test-phase */
47     DLOG("color %s\n", colors[cnt]);
48     new->name = strdup(colors[cnt]);
49     //uint32_t cp = get_colorpixel(colors[cnt]);
50     cnt++;
51     if ((cnt % (sizeof(colors) / sizeof(char*))) == 0)
52         cnt = 0;
53     if (window)
54         x_con_init(new, window->depth);
55     else
56         x_con_init(new, XCB_COPY_FROM_PARENT);
57
58     TAILQ_INIT(&(new->floating_head));
59     TAILQ_INIT(&(new->nodes_head));
60     TAILQ_INIT(&(new->focus_head));
61     TAILQ_INIT(&(new->swallow_head));
62
63     if (parent != NULL)
64         con_attach(new, parent, false);
65
66     return new;
67 }
68
69 /*
70  * Attaches the given container to the given parent. This happens when moving
71  * a container or when inserting a new container at a specific place in the
72  * tree.
73  *
74  * ignore_focus is to just insert the Con at the end (useful when creating a
75  * new split container *around* some containers, that is, detaching and
76  * attaching them in order without wanting to mess with the focus in between).
77  *
78  */
79 void con_attach(Con *con, Con *parent, bool ignore_focus) {
80     con->parent = parent;
81     Con *loop;
82     Con *current = NULL;
83     struct nodes_head *nodes_head = &(parent->nodes_head);
84     struct focus_head *focus_head = &(parent->focus_head);
85
86     /* Workspaces are handled differently: they need to be inserted at the
87      * right position. */
88     if (con->type == CT_WORKSPACE) {
89         DLOG("it's a workspace. num = %d\n", con->num);
90         if (con->num == -1 || TAILQ_EMPTY(nodes_head)) {
91             TAILQ_INSERT_TAIL(nodes_head, con, nodes);
92         } else {
93             current = TAILQ_FIRST(nodes_head);
94             if (con->num < current->num) {
95                 /* we need to insert the container at the beginning */
96                 TAILQ_INSERT_HEAD(nodes_head, con, nodes);
97             } else {
98                 while (current->num != -1 && con->num > current->num) {
99                     current = TAILQ_NEXT(current, nodes);
100                     if (current == TAILQ_END(nodes_head)) {
101                         current = NULL;
102                         break;
103                     }
104                 }
105                 /* we need to insert con after current, if current is not NULL */
106                 if (current)
107                     TAILQ_INSERT_BEFORE(current, con, nodes);
108                 else TAILQ_INSERT_TAIL(nodes_head, con, nodes);
109             }
110         }
111         goto add_to_focus_head;
112     }
113
114     if (con->type == CT_FLOATING_CON) {
115         DLOG("Inserting into floating containers\n");
116         TAILQ_INSERT_TAIL(&(parent->floating_head), con, floating_windows);
117     } else {
118         if (!ignore_focus) {
119             /* Get the first tiling container in focus stack */
120             TAILQ_FOREACH(loop, &(parent->focus_head), focused) {
121                 if (loop->type == CT_FLOATING_CON)
122                     continue;
123                 current = loop;
124                 break;
125             }
126         }
127
128         /* When the container is not a split container (but contains a window)
129          * and is attached to a workspace, we check if the user configured a
130          * workspace_layout. This is done in workspace_attach_to, which will
131          * provide us with the container to which we should attach (either the
132          * workspace or a new split container with the configured
133          * workspace_layout).
134          */
135         if (con->window != NULL &&
136             parent->type == CT_WORKSPACE &&
137             config.default_layout != L_DEFAULT) {
138             DLOG("Parent is a workspace. Applying default layout...\n");
139             Con *target = workspace_attach_to(parent);
140
141             /* Attach the original con to this new split con instead */
142             nodes_head = &(target->nodes_head);
143             focus_head = &(target->focus_head);
144             con->parent = target;
145             current = NULL;
146
147             DLOG("done\n");
148         }
149
150         /* Insert the container after the tiling container, if found.
151          * When adding to a CT_OUTPUT, just append one after another. */
152         if (current && parent->type != CT_OUTPUT) {
153             DLOG("Inserting con = %p after last focused tiling con %p\n",
154                  con, current);
155             TAILQ_INSERT_AFTER(nodes_head, current, con, nodes);
156         } else TAILQ_INSERT_TAIL(nodes_head, con, nodes);
157     }
158
159 add_to_focus_head:
160     /* We insert to the TAIL because con_focus() will correct this.
161      * This way, we have the option to insert Cons without having
162      * to focus them. */
163     TAILQ_INSERT_TAIL(focus_head, con, focused);
164 }
165
166 /*
167  * Detaches the given container from its current parent
168  *
169  */
170 void con_detach(Con *con) {
171     if (con->type == CT_FLOATING_CON) {
172         TAILQ_REMOVE(&(con->parent->floating_head), con, floating_windows);
173         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
174     } else {
175         TAILQ_REMOVE(&(con->parent->nodes_head), con, nodes);
176         TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
177     }
178 }
179
180 /*
181  * Sets input focus to the given container. Will be updated in X11 in the next
182  * run of x_push_changes().
183  *
184  */
185 void con_focus(Con *con) {
186     assert(con != NULL);
187     DLOG("con_focus = %p\n", con);
188
189     /* 1: set focused-pointer to the new con */
190     /* 2: exchange the position of the container in focus stack of the parent all the way up */
191     TAILQ_REMOVE(&(con->parent->focus_head), con, focused);
192     TAILQ_INSERT_HEAD(&(con->parent->focus_head), con, focused);
193     if (con->parent->parent != NULL)
194         con_focus(con->parent);
195
196     focused = con;
197     if (con->urgent) {
198         con->urgent = false;
199         workspace_update_urgent_flag(con_get_workspace(con));
200     }
201 }
202
203 /*
204  * Returns true when this node is a leaf node (has no children)
205  *
206  */
207 bool con_is_leaf(Con *con) {
208     return TAILQ_EMPTY(&(con->nodes_head));
209 }
210
211 /*
212  * Returns true if this node accepts a window (if the node swallows windows,
213  * it might already have swallowed enough and cannot hold any more).
214  *
215  */
216 bool con_accepts_window(Con *con) {
217     /* 1: workspaces never accept direct windows */
218     if (con->type == CT_WORKSPACE)
219         return false;
220
221     if (con->split) {
222         DLOG("container %p does not accept windows, it is a split container.\n", con);
223         return false;
224     }
225
226     /* TODO: if this is a swallowing container, we need to check its max_clients */
227     return (con->window == NULL);
228 }
229
230 /*
231  * Gets the output container (first container with CT_OUTPUT in hierarchy) this
232  * node is on.
233  *
234  */
235 Con *con_get_output(Con *con) {
236     Con *result = con;
237     while (result != NULL && result->type != CT_OUTPUT)
238         result = result->parent;
239     /* We must be able to get an output because focus can never be set higher
240      * in the tree (root node cannot be focused). */
241     assert(result != NULL);
242     return result;
243 }
244
245 /*
246  * Gets the workspace container this node is on.
247  *
248  */
249 Con *con_get_workspace(Con *con) {
250     Con *result = con;
251     while (result != NULL && result->type != CT_WORKSPACE)
252         result = result->parent;
253     return result;
254 }
255
256 /*
257  * Searches parenst of the given 'con' until it reaches one with the specified
258  * 'orientation'. Aborts when it comes across a floating_con.
259  *
260  */
261 Con *con_parent_with_orientation(Con *con, orientation_t orientation) {
262     DLOG("Searching for parent of Con %p with orientation %d\n", con, orientation);
263     Con *parent = con->parent;
264     if (parent->type == CT_FLOATING_CON)
265         return NULL;
266     while (con_orientation(parent) != orientation) {
267         DLOG("Need to go one level further up\n");
268         parent = parent->parent;
269         /* Abort when we reach a floating con, or an output con */
270         if (parent &&
271             (parent->type == CT_FLOATING_CON ||
272              parent->type == CT_OUTPUT ||
273              (parent->parent && parent->parent->type == CT_OUTPUT)))
274             parent = NULL;
275         if (parent == NULL)
276             break;
277     }
278     DLOG("Result: %p\n", parent);
279     return parent;
280 }
281
282 /*
283  * helper data structure for the breadth-first-search in
284  * con_get_fullscreen_con()
285  *
286  */
287 struct bfs_entry {
288     Con *con;
289
290     TAILQ_ENTRY(bfs_entry) entries;
291 };
292
293 /*
294  * Returns the first fullscreen node below this node.
295  *
296  */
297 Con *con_get_fullscreen_con(Con *con, int fullscreen_mode) {
298     Con *current, *child;
299
300     /* TODO: is breadth-first-search really appropriate? (check as soon as
301      * fullscreen levels and fullscreen for containers is implemented) */
302     TAILQ_HEAD(bfs_head, bfs_entry) bfs_head = TAILQ_HEAD_INITIALIZER(bfs_head);
303     struct bfs_entry *entry = smalloc(sizeof(struct bfs_entry));
304     entry->con = con;
305     TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
306
307     while (!TAILQ_EMPTY(&bfs_head)) {
308         entry = TAILQ_FIRST(&bfs_head);
309         current = entry->con;
310         if (current != con && current->fullscreen_mode == fullscreen_mode) {
311             /* empty the queue */
312             while (!TAILQ_EMPTY(&bfs_head)) {
313                 entry = TAILQ_FIRST(&bfs_head);
314                 TAILQ_REMOVE(&bfs_head, entry, entries);
315                 free(entry);
316             }
317             return current;
318         }
319
320         TAILQ_REMOVE(&bfs_head, entry, entries);
321         free(entry);
322
323         TAILQ_FOREACH(child, &(current->nodes_head), nodes) {
324             entry = smalloc(sizeof(struct bfs_entry));
325             entry->con = child;
326             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
327         }
328
329         TAILQ_FOREACH(child, &(current->floating_head), floating_windows) {
330             entry = smalloc(sizeof(struct bfs_entry));
331             entry->con = child;
332             TAILQ_INSERT_TAIL(&bfs_head, entry, entries);
333         }
334     }
335
336     return NULL;
337 }
338
339 /*
340  * Returns true if the node is floating.
341  *
342  */
343 bool con_is_floating(Con *con) {
344     assert(con != NULL);
345     DLOG("checking if con %p is floating\n", con);
346     return (con->floating >= FLOATING_AUTO_ON);
347 }
348
349 /*
350  * Checks if the given container is either floating or inside some floating
351  * container. It returns the FLOATING_CON container.
352  *
353  */
354 Con *con_inside_floating(Con *con) {
355     assert(con != NULL);
356     if (con->type == CT_FLOATING_CON)
357         return con;
358
359     if (con->floating >= FLOATING_AUTO_ON)
360         return con->parent;
361
362     if (con->type == CT_WORKSPACE || con->type == CT_OUTPUT)
363         return NULL;
364
365     return con_inside_floating(con->parent);
366 }
367
368 /*
369  * Checks if the given container is inside a focused container.
370  *
371  */
372 bool con_inside_focused(Con *con) {
373     if (con == focused)
374         return true;
375     if (!con->parent)
376         return false;
377     return con_inside_focused(con->parent);
378 }
379
380 /*
381  * Returns the container with the given client window ID or NULL if no such
382  * container exists.
383  *
384  */
385 Con *con_by_window_id(xcb_window_t window) {
386     Con *con;
387     TAILQ_FOREACH(con, &all_cons, all_cons)
388         if (con->window != NULL && con->window->id == window)
389             return con;
390     return NULL;
391 }
392
393 /*
394  * Returns the container with the given frame ID or NULL if no such container
395  * exists.
396  *
397  */
398 Con *con_by_frame_id(xcb_window_t frame) {
399     Con *con;
400     TAILQ_FOREACH(con, &all_cons, all_cons)
401         if (con->frame == frame)
402             return con;
403     return NULL;
404 }
405
406 /*
407  * Returns the first container below 'con' which wants to swallow this window
408  * TODO: priority
409  *
410  */
411 Con *con_for_window(Con *con, i3Window *window, Match **store_match) {
412     Con *child;
413     Match *match;
414     //DLOG("searching con for window %p starting at con %p\n", window, con);
415     //DLOG("class == %s\n", window->class_class);
416
417     TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
418         TAILQ_FOREACH(match, &(child->swallow_head), matches) {
419             if (!match_matches_window(match, window))
420                 continue;
421             if (store_match != NULL)
422                 *store_match = match;
423             return child;
424         }
425         Con *result = con_for_window(child, window, store_match);
426         if (result != NULL)
427             return result;
428     }
429
430     TAILQ_FOREACH(child, &(con->floating_head), floating_windows) {
431         TAILQ_FOREACH(match, &(child->swallow_head), matches) {
432             if (!match_matches_window(match, window))
433                 continue;
434             if (store_match != NULL)
435                 *store_match = match;
436             return child;
437         }
438         Con *result = con_for_window(child, window, store_match);
439         if (result != NULL)
440             return result;
441     }
442
443     return NULL;
444 }
445
446 /*
447  * Returns the number of children of this container.
448  *
449  */
450 int con_num_children(Con *con) {
451     Con *child;
452     int children = 0;
453
454     TAILQ_FOREACH(child, &(con->nodes_head), nodes)
455         children++;
456
457     return children;
458 }
459
460 /*
461  * Updates the percent attribute of the children of the given container. This
462  * function needs to be called when a window is added or removed from a
463  * container.
464  *
465  */
466 void con_fix_percent(Con *con) {
467     Con *child;
468     int children = con_num_children(con);
469
470     // calculate how much we have distributed and how many containers
471     // with a percentage set we have
472     double total = 0.0;
473     int children_with_percent = 0;
474     TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
475         if (child->percent > 0.0) {
476             total += child->percent;
477             ++children_with_percent;
478         }
479     }
480
481     // if there were children without a percentage set, set to a value that
482     // will make those children proportional to all others
483     if (children_with_percent != children) {
484         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
485             if (child->percent <= 0.0) {
486                 if (children_with_percent == 0)
487                     total += (child->percent = 1.0);
488                 else total += (child->percent = total / children_with_percent);
489             }
490         }
491     }
492
493     // if we got a zero, just distribute the space equally, otherwise
494     // distribute according to the proportions we got
495     if (total == 0.0) {
496         TAILQ_FOREACH(child, &(con->nodes_head), nodes)
497             child->percent = 1.0 / children;
498     } else if (total != 1.0) {
499         TAILQ_FOREACH(child, &(con->nodes_head), nodes)
500             child->percent /= total;
501     }
502 }
503
504 /*
505  * Toggles fullscreen mode for the given container. Fullscreen mode will not be
506  * entered when there already is a fullscreen container on this workspace.
507  *
508  */
509 void con_toggle_fullscreen(Con *con, int fullscreen_mode) {
510     Con *workspace, *fullscreen;
511
512     if (con->type == CT_WORKSPACE) {
513         DLOG("You cannot make a workspace fullscreen.\n");
514         return;
515     }
516
517     DLOG("toggling fullscreen for %p / %s\n", con, con->name);
518     if (con->fullscreen_mode == CF_NONE) {
519         /* 1: check if there already is a fullscreen con */
520         if (fullscreen_mode == CF_GLOBAL)
521             fullscreen = con_get_fullscreen_con(croot, CF_GLOBAL);
522         else {
523             workspace = con_get_workspace(con);
524             fullscreen = con_get_fullscreen_con(workspace, CF_OUTPUT);
525         }
526         if (fullscreen != NULL) {
527             /* Disable fullscreen for the currently fullscreened
528              * container and enable it for the one the user wants
529              * to have in fullscreen mode. */
530             LOG("Disabling fullscreen for (%p/%s) upon user request\n",
531                 fullscreen, fullscreen->name);
532             fullscreen->fullscreen_mode = CF_NONE;
533         }
534
535         /* 2: enable fullscreen */
536         con->fullscreen_mode = fullscreen_mode;
537     } else {
538         /* 1: disable fullscreen */
539         con->fullscreen_mode = CF_NONE;
540     }
541
542     DLOG("mode now: %d\n", con->fullscreen_mode);
543
544     /* update _NET_WM_STATE if this container has a window */
545     /* TODO: when a window is assigned to a container which is already
546      * fullscreened, this state needs to be pushed to the client, too */
547     if (con->window == NULL)
548         return;
549
550     uint32_t values[1];
551     unsigned int num = 0;
552
553     if (con->fullscreen_mode != CF_NONE)
554         values[num++] = A__NET_WM_STATE_FULLSCREEN;
555
556     xcb_change_property(conn, XCB_PROP_MODE_REPLACE, con->window->id,
557                         A__NET_WM_STATE, XCB_ATOM_ATOM, 32, num, values);
558 }
559
560 /*
561  * Moves the given container to the currently focused container on the given
562  * workspace.
563  *
564  * The fix_coordinates flag will translate the current coordinates (offset from
565  * the monitor position basically) to appropriate coordinates on the
566  * destination workspace.
567  * Not enabling this behaviour comes in handy when this function gets called by
568  * floating_maybe_reassign_ws, which will only "move" a floating window when it
569  * *already* changed its coordinates to a different output.
570  *
571  * The dont_warp flag disables pointer warping and will be set when this
572  * function is called while dragging a floating window.
573  *
574  * TODO: is there a better place for this function?
575  *
576  */
577 void con_move_to_workspace(Con *con, Con *workspace, bool fix_coordinates, bool dont_warp) {
578     if (con->type == CT_WORKSPACE) {
579         DLOG("Moving workspaces is not yet implemented.\n");
580         return;
581     }
582
583     /* Prevent moving if this would violate the fullscreen focus restrictions. */
584     if (!con_fullscreen_permits_focusing(workspace)) {
585         LOG("Cannot move out of a fullscreen container");
586         return;
587     }
588
589     if (con_is_floating(con)) {
590         DLOG("Using FLOATINGCON instead\n");
591         con = con->parent;
592     }
593
594     Con *source_ws = con_get_workspace(con);
595     if (workspace == source_ws) {
596         DLOG("Not moving, already there\n");
597         return;
598     }
599
600     /* Save the current workspace. So we can call workspace_show() by the end
601      * of this function. */
602     Con *current_ws = con_get_workspace(focused);
603
604     Con *source_output = con_get_output(con),
605         *dest_output = con_get_output(workspace);
606
607     /* 1: save the container which is going to be focused after the current
608      * container is moved away */
609     Con *focus_next = con_next_focused(con);
610
611     /* 2: get the focused container of this workspace */
612     Con *next = con_descend_focused(workspace);
613
614     /* 3: we go up one level, but only when next is a normal container */
615     if (next->type != CT_WORKSPACE) {
616         DLOG("next originally = %p / %s / type %d\n", next, next->name, next->type);
617         next = next->parent;
618     }
619
620     /* 4: if the target container is floating, we get the workspace instead.
621      * Only tiling windows need to get inserted next to the current container.
622      * */
623     Con *floatingcon = con_inside_floating(next);
624     if (floatingcon != NULL) {
625         DLOG("floatingcon, going up even further\n");
626         next = floatingcon->parent;
627     }
628
629     if (con->type == CT_FLOATING_CON) {
630         Con *ws = con_get_workspace(next);
631         DLOG("This is a floating window, using workspace %p / %s\n", ws, ws->name);
632         next = ws;
633     }
634
635     if (source_output != dest_output) {
636         /* Take the relative coordinates of the current output, then add them
637          * to the coordinate space of the correct output */
638         if (fix_coordinates && con->type == CT_FLOATING_CON) {
639             floating_fix_coordinates(con, &(source_output->rect), &(dest_output->rect));
640         } else DLOG("Not fixing coordinates, fix_coordinates flag = %d\n", fix_coordinates);
641
642         /* If moving to a visible workspace, call show so it can be considered
643          * focused. Must do before attaching because workspace_show checks to see
644          * if focused container is in its area. */
645         if (workspace_is_visible(workspace)) {
646             workspace_show(workspace);
647
648             /* Don’t warp if told so (when dragging floating windows with the
649              * mouse for example) */
650             if (dont_warp)
651                 x_set_warp_to(NULL);
652             else
653                 x_set_warp_to(&(con->rect));
654         }
655     }
656
657     DLOG("Re-attaching container to %p / %s\n", next, next->name);
658     /* 5: re-attach the con to the parent of this focused container */
659     Con *parent = con->parent;
660     con_detach(con);
661     con_attach(con, next, false);
662
663     /* 6: fix the percentages */
664     con_fix_percent(parent);
665     con->percent = 0.0;
666     con_fix_percent(next);
667
668     /* 7: focus the con on the target workspace (the X focus is only updated by
669      * calling tree_render(), so for the "real" focus this is a no-op).
670      * We don’t focus the con for i3 pseudo workspaces like __i3_scratch and
671      * we don’t focus when there is a fullscreen con on that workspace. */
672     if ((workspace->name[0] != '_' || workspace->name[1] != '_') &&
673         con_get_fullscreen_con(workspace, CF_OUTPUT) == NULL)
674         con_focus(con_descend_focused(con));
675
676     /* 8: when moving to a visible workspace on a different output, we keep the
677      * con focused. Otherwise, we leave the focus on the current workspace as we
678      * don’t want to focus invisible workspaces */
679     if (source_output != dest_output &&
680         workspace_is_visible(workspace)) {
681         DLOG("Moved to a different output, focusing target\n");
682     } else {
683         /* Descend focus stack in case focus_next is a workspace which can
684          * occur if we move to the same workspace.  Also show current workspace
685          * to ensure it is focused. */
686         workspace_show(current_ws);
687
688         /* Set focus only if con was on current workspace before moving.
689          * Otherwise we would give focus to some window on different workspace. */
690         if (source_ws == current_ws)
691             con_focus(con_descend_focused(focus_next));
692     }
693
694     CALL(parent, on_remove_child);
695 }
696
697 /*
698  * Returns the orientation of the given container (for stacked containers,
699  * vertical orientation is used regardless of the actual orientation of the
700  * container).
701  *
702  */
703 int con_orientation(Con *con) {
704     switch (con->layout) {
705         case L_SPLITV:
706         /* stacking containers behave like they are in vertical orientation */
707         case L_STACKED:
708             return VERT;
709
710         case L_SPLITH:
711         /* tabbed containers behave like they are in vertical orientation */
712         case L_TABBED:
713             return HORIZ;
714
715         case L_DEFAULT:
716             DLOG("Someone called con_orientation() on a con with L_DEFAULT, this is a bug in the code.\n");
717             assert(false);
718             return HORIZ;
719
720         case L_DOCKAREA:
721         case L_OUTPUT:
722             DLOG("con_orientation() called on dockarea/output (%d) container %p\n", con->layout, con);
723             assert(false);
724             return HORIZ;
725
726         default:
727             DLOG("con_orientation() ran into default\n");
728             assert(false);
729     }
730 }
731
732 /*
733  * Returns the container which will be focused next when the given container
734  * is not available anymore. Called in tree_close and con_move_to_workspace
735  * to properly restore focus.
736  *
737  */
738 Con *con_next_focused(Con *con) {
739     Con *next;
740     /* floating containers are attached to a workspace, so we focus either the
741      * next floating container (if any) or the workspace itself. */
742     if (con->type == CT_FLOATING_CON) {
743         DLOG("selecting next for CT_FLOATING_CON\n");
744         next = TAILQ_NEXT(con, floating_windows);
745         DLOG("next = %p\n", next);
746         if (!next) {
747             next = TAILQ_PREV(con, floating_head, floating_windows);
748             DLOG("using prev, next = %p\n", next);
749         }
750         if (!next) {
751             Con *ws = con_get_workspace(con);
752             next = ws;
753             DLOG("no more floating containers for next = %p, restoring workspace focus\n", next);
754             while (next != TAILQ_END(&(ws->focus_head)) && !TAILQ_EMPTY(&(next->focus_head))) {
755                 next = TAILQ_FIRST(&(next->focus_head));
756                 if (next == con) {
757                     DLOG("skipping container itself, we want the next client\n");
758                     next = TAILQ_NEXT(next, focused);
759                 }
760             }
761             if (next == TAILQ_END(&(ws->focus_head))) {
762                 DLOG("Focus list empty, returning ws\n");
763                 next = ws;
764             }
765         } else {
766             /* Instead of returning the next CT_FLOATING_CON, we descend it to
767              * get an actual window to focus. */
768             next = con_descend_focused(next);
769         }
770         return next;
771     }
772
773     /* dock clients cannot be focused, so we focus the workspace instead */
774     if (con->parent->type == CT_DOCKAREA) {
775         DLOG("selecting workspace for dock client\n");
776         return con_descend_focused(output_get_content(con->parent->parent));
777     }
778
779     /* if 'con' is not the first entry in the focus stack, use the first one as
780      * it’s currently focused already */
781     Con *first = TAILQ_FIRST(&(con->parent->focus_head));
782     if (first != con) {
783         DLOG("Using first entry %p\n", first);
784         next = first;
785     } else {
786         /* try to focus the next container on the same level as this one or fall
787          * back to its parent */
788         if (!(next = TAILQ_NEXT(con, focused)))
789             next = con->parent;
790     }
791
792     /* now go down the focus stack as far as
793      * possible, excluding the current container */
794     while (!TAILQ_EMPTY(&(next->focus_head)) &&
795            TAILQ_FIRST(&(next->focus_head)) != con)
796         next = TAILQ_FIRST(&(next->focus_head));
797
798     return next;
799 }
800
801 /*
802  * Get the next/previous container in the specified orientation. This may
803  * travel up until it finds a container with suitable orientation.
804  *
805  */
806 Con *con_get_next(Con *con, char way, orientation_t orientation) {
807     DLOG("con_get_next(way=%c, orientation=%d)\n", way, orientation);
808     /* 1: get the first parent with the same orientation */
809     Con *cur = con;
810     while (con_orientation(cur->parent) != orientation) {
811         DLOG("need to go one level further up\n");
812         if (cur->parent->type == CT_WORKSPACE) {
813             LOG("that's a workspace, we can't go further up\n");
814             return NULL;
815         }
816         cur = cur->parent;
817     }
818
819     /* 2: chose next (or previous) */
820     Con *next;
821     if (way == 'n') {
822         next = TAILQ_NEXT(cur, nodes);
823         /* if we are at the end of the list, we need to wrap */
824         if (next == TAILQ_END(&(parent->nodes_head)))
825             return NULL;
826     } else {
827         next = TAILQ_PREV(cur, nodes_head, nodes);
828         /* if we are at the end of the list, we need to wrap */
829         if (next == TAILQ_END(&(cur->nodes_head)))
830             return NULL;
831     }
832     DLOG("next = %p\n", next);
833
834     return next;
835 }
836
837 /*
838  * Returns the focused con inside this client, descending the tree as far as
839  * possible. This comes in handy when attaching a con to a workspace at the
840  * currently focused position, for example.
841  *
842  */
843 Con *con_descend_focused(Con *con) {
844     Con *next = con;
845     while (next != focused && !TAILQ_EMPTY(&(next->focus_head)))
846         next = TAILQ_FIRST(&(next->focus_head));
847     return next;
848 }
849
850 /*
851  * Returns the focused con inside this client, descending the tree as far as
852  * possible. This comes in handy when attaching a con to a workspace at the
853  * currently focused position, for example.
854  *
855  * Works like con_descend_focused but considers only tiling cons.
856  *
857  */
858 Con *con_descend_tiling_focused(Con *con) {
859     Con *next = con;
860     Con *before;
861     Con *child;
862     if (next == focused)
863         return next;
864     do {
865         before = next;
866         TAILQ_FOREACH(child, &(next->focus_head), focused) {
867             if (child->type == CT_FLOATING_CON)
868                 continue;
869
870             next = child;
871             break;
872         }
873     } while (before != next && next != focused);
874     return next;
875 }
876
877 /*
878  * Returns the leftmost, rightmost, etc. container in sub-tree. For example, if
879  * direction is D_LEFT, then we return the rightmost container and if direction
880  * is D_RIGHT, we return the leftmost container.  This is because if we are
881  * moving D_LEFT, and thus want the rightmost container.
882  *
883  */
884 Con *con_descend_direction(Con *con, direction_t direction) {
885     Con *most = NULL;
886     int orientation = con_orientation(con);
887     DLOG("con_descend_direction(%p, orientation %d, direction %d)\n", con, orientation, direction);
888     if (direction == D_LEFT || direction == D_RIGHT) {
889         if (orientation == HORIZ) {
890             /* If the direction is horizontal, we can use either the first
891              * (D_RIGHT) or the last con (D_LEFT) */
892             if (direction == D_RIGHT)
893                 most = TAILQ_FIRST(&(con->nodes_head));
894             else most = TAILQ_LAST(&(con->nodes_head), nodes_head);
895         } else if (orientation == VERT) {
896             /* Wrong orientation. We use the last focused con. Within that con,
897              * we recurse to chose the left/right con or at least the last
898              * focused one. */
899             most = TAILQ_FIRST(&(con->focus_head));
900         } else {
901             /* If the con has no orientation set, it’s not a split container
902              * but a container with a client window, so stop recursing */
903             return con;
904         }
905     }
906
907     if (direction == D_UP || direction == D_DOWN) {
908         if (orientation == VERT) {
909             /* If the direction is vertical, we can use either the first
910              * (D_DOWN) or the last con (D_UP) */
911             if (direction == D_UP)
912                 most = TAILQ_LAST(&(con->nodes_head), nodes_head);
913             else most = TAILQ_FIRST(&(con->nodes_head));
914         } else if (orientation == HORIZ) {
915             /* Wrong orientation. We use the last focused con. Within that con,
916              * we recurse to chose the top/bottom con or at least the last
917              * focused one. */
918             most = TAILQ_FIRST(&(con->focus_head));
919         } else {
920             /* If the con has no orientation set, it’s not a split container
921              * but a container with a client window, so stop recursing */
922             return con;
923         }
924     }
925
926     if (!most)
927         return con;
928     return con_descend_direction(most, direction);
929 }
930
931 /*
932  * Returns a "relative" Rect which contains the amount of pixels that need to
933  * be added to the original Rect to get the final position (obviously the
934  * amount of pixels for normal, 1pixel and borderless are different).
935  *
936  */
937 Rect con_border_style_rect(Con *con) {
938     adjacent_t borders_to_hide = ADJ_NONE;
939     Rect result;
940     /* Shortcut to avoid calling con_adjacent_borders() on dock containers. */
941     int border_style = con_border_style(con);
942     if (border_style == BS_NONE)
943         return (Rect){ 0, 0, 0, 0 };
944     borders_to_hide = con_adjacent_borders(con) & config.hide_edge_borders;
945     switch (border_style) {
946     case BS_NORMAL:
947         result = (Rect){2, 0, -(2 * 2), -2};
948         if (borders_to_hide & ADJ_LEFT_SCREEN_EDGE) {
949             result.x -= 2;
950             result.width += 2;
951         }
952         if (borders_to_hide & ADJ_RIGHT_SCREEN_EDGE) {
953             result.width += 2;
954         }
955         /* With normal borders we never hide the upper border */
956         if (borders_to_hide & ADJ_LOWER_SCREEN_EDGE) {
957             result.height += 2;
958         }
959         return result;
960
961     case BS_1PIXEL:
962         result = (Rect){1, 1, -2, -2};
963         if (borders_to_hide & ADJ_LEFT_SCREEN_EDGE) {
964             result.x -= 1;
965             result.width += 1;
966         }
967         if (borders_to_hide & ADJ_RIGHT_SCREEN_EDGE) {
968             result.width += 1;
969         }
970         if (borders_to_hide & ADJ_UPPER_SCREEN_EDGE) {
971             result.y -= 1;
972             result.height += 1;
973         }
974         if (borders_to_hide & ADJ_LOWER_SCREEN_EDGE) {
975             result.height += 1;
976         }
977         return result;
978
979     case BS_NONE:
980         return (Rect){0, 0, 0, 0};
981
982     default:
983         assert(false);
984     }
985 }
986
987 /*
988  * Returns adjacent borders of the window. We need this if hide_edge_borders is
989  * enabled.
990  */
991 adjacent_t con_adjacent_borders(Con *con) {
992     adjacent_t result = ADJ_NONE;
993     Con *workspace = con_get_workspace(con);
994     if (con->rect.x == workspace->rect.x)
995         result |= ADJ_LEFT_SCREEN_EDGE;
996     if (con->rect.x + con->rect.width == workspace->rect.x + workspace->rect.width)
997         result |= ADJ_RIGHT_SCREEN_EDGE;
998     if (con->rect.y == workspace->rect.y)
999         result |= ADJ_UPPER_SCREEN_EDGE;
1000     if (con->rect.y + con->rect.height == workspace->rect.y + workspace->rect.height)
1001         result |= ADJ_LOWER_SCREEN_EDGE;
1002     return result;
1003 }
1004
1005 /*
1006  * Use this function to get a container’s border style. This is important
1007  * because when inside a stack, the border style is always BS_NORMAL.
1008  * For tabbed mode, the same applies, with one exception: when the container is
1009  * borderless and the only element in the tabbed container, the border is not
1010  * rendered.
1011  *
1012  * For children of a CT_DOCKAREA, the border style is always none.
1013  *
1014  */
1015 int con_border_style(Con *con) {
1016     Con *fs = con_get_fullscreen_con(con->parent, CF_OUTPUT);
1017     if (fs == con) {
1018         DLOG("this one is fullscreen! overriding BS_NONE\n");
1019         return BS_NONE;
1020     }
1021
1022     if (con->parent->layout == L_STACKED)
1023         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1024
1025     if (con->parent->layout == L_TABBED && con->border_style != BS_NORMAL)
1026         return (con_num_children(con->parent) == 1 ? con->border_style : BS_NORMAL);
1027
1028     if (con->parent->type == CT_DOCKAREA)
1029         return BS_NONE;
1030
1031     return con->border_style;
1032 }
1033
1034 /*
1035  * Sets the given border style on con, correctly keeping the position/size of a
1036  * floating window.
1037  *
1038  */
1039 void con_set_border_style(Con *con, int border_style) {
1040     /* Handle the simple case: non-floating containerns */
1041     if (!con_is_floating(con)) {
1042         con->border_style = border_style;
1043         return;
1044     }
1045
1046     /* For floating containers, we want to keep the position/size of the
1047      * *window* itself. We first add the border pixels to con->rect to make
1048      * con->rect represent the absolute position of the window. Then, we change
1049      * the border and subtract the new border pixels. Afterwards, we update
1050      * parent->rect to contain con. */
1051     DLOG("This is a floating container\n");
1052
1053     Rect bsr = con_border_style_rect(con);
1054     con->rect.x += bsr.x;
1055     con->rect.y += bsr.y;
1056     con->rect.width += bsr.width;
1057     con->rect.height += bsr.height;
1058
1059     /* Change the border style, get new border/decoration values. */
1060     con->border_style = border_style;
1061     bsr = con_border_style_rect(con);
1062     int deco_height =
1063         (con->border_style == BS_NORMAL ? config.font.height + 5 : 0);
1064
1065     con->rect.x -= bsr.x;
1066     con->rect.y -= bsr.y;
1067     con->rect.width -= bsr.width;
1068     con->rect.height -= bsr.height;
1069
1070     Con *parent = con->parent;
1071     parent->rect.x = con->rect.x;
1072     parent->rect.y = con->rect.y - deco_height;
1073     parent->rect.width = con->rect.width;
1074     parent->rect.height = con->rect.height + deco_height;
1075 }
1076
1077 /*
1078  * This function changes the layout of a given container. Use it to handle
1079  * special cases like changing a whole workspace to stacked/tabbed (creates a
1080  * new split container before).
1081  *
1082  */
1083 void con_set_layout(Con *con, int layout) {
1084     /* We fill in last_split_layout when switching to a different layout
1085      * since there are many places in the code that don’t use
1086      * con_set_layout(). */
1087     if (con->layout == L_SPLITH || con->layout == L_SPLITV)
1088         con->last_split_layout = con->layout;
1089
1090     /* When the container type is CT_WORKSPACE, the user wants to change the
1091      * whole workspace into stacked/tabbed mode. To do this and still allow
1092      * intuitive operations (like level-up and then opening a new window), we
1093      * need to create a new split container. */
1094     if (con->type == CT_WORKSPACE) {
1095         DLOG("Creating new split container\n");
1096         /* 1: create a new split container */
1097         Con *new = con_new(NULL, NULL);
1098         new->parent = con;
1099
1100         /* 2: Set the requested layout on the split container and mark it as
1101          * split. */
1102         con_set_layout(new, layout);
1103         new->last_split_layout = con->last_split_layout;
1104         new->split = true;
1105
1106         Con *old_focused = TAILQ_FIRST(&(con->focus_head));
1107         if (old_focused == TAILQ_END(&(con->focus_head)))
1108             old_focused = NULL;
1109
1110         /* 3: move the existing cons of this workspace below the new con */
1111         DLOG("Moving cons\n");
1112         Con *child;
1113         while (!TAILQ_EMPTY(&(con->nodes_head))) {
1114             child = TAILQ_FIRST(&(con->nodes_head));
1115             con_detach(child);
1116             con_attach(child, new, true);
1117         }
1118
1119         /* 4: attach the new split container to the workspace */
1120         DLOG("Attaching new split to ws\n");
1121         con_attach(new, con, false);
1122
1123         if (old_focused)
1124             con_focus(old_focused);
1125
1126         tree_flatten(croot);
1127
1128         return;
1129     }
1130
1131     if (layout == L_DEFAULT) {
1132         /* Special case: the layout formerly known as "default" (in combination
1133          * with an orientation). Since we switched to splith/splitv layouts,
1134          * using the "default" layout (which "only" should happen when using
1135          * legacy configs) is using the last split layout (either splith or
1136          * splitv) in order to still do the same thing.
1137          *
1138          * Starting from v4.6 though, we will nag users about using "layout
1139          * default", and in v4.9 we will remove it entirely (with an
1140          * appropriate i3-migrate-config mechanism). */
1141         con->layout = con->last_split_layout;
1142         /* In case last_split_layout was not initialized… */
1143         if (con->layout == L_DEFAULT)
1144             con->layout = L_SPLITH;
1145     } else {
1146         con->layout = layout;
1147     }
1148 }
1149
1150 /*
1151  * This function toggles the layout of a given container. toggle_mode can be
1152  * either 'default' (toggle only between stacked/tabbed/last_split_layout),
1153  * 'split' (toggle only between splitv/splith) or 'all' (toggle between all
1154  * layouts).
1155  *
1156  */
1157 void con_toggle_layout(Con *con, const char *toggle_mode) {
1158     if (strcmp(toggle_mode, "split") == 0) {
1159         /* Toggle between splits. When the current layout is not a split
1160          * layout, we just switch back to last_split_layout. Otherwise, we
1161          * change to the opposite split layout. */
1162         if (con->layout != L_SPLITH && con->layout != L_SPLITV)
1163             con_set_layout(con, con->last_split_layout);
1164         else {
1165             if (con->layout == L_SPLITH)
1166                 con_set_layout(con, L_SPLITV);
1167             else con_set_layout(con, L_SPLITH);
1168         }
1169     } else {
1170         if (con->layout == L_STACKED)
1171             con_set_layout(con, L_TABBED);
1172         else if (con->layout == L_TABBED) {
1173             if (strcmp(toggle_mode, "all") == 0)
1174                 con_set_layout(con, L_SPLITH);
1175             else con_set_layout(con, con->last_split_layout);
1176         } else if (con->layout == L_SPLITH || con->layout == L_SPLITV) {
1177             if (strcmp(toggle_mode, "all") == 0) {
1178                 /* When toggling through all modes, we toggle between
1179                  * splith/splitv, whereas normally we just directly jump to
1180                  * stacked. */
1181                 if (con->layout == L_SPLITH)
1182                     con_set_layout(con, L_SPLITV);
1183                 else con_set_layout(con, L_STACKED);
1184             } else {
1185                 con_set_layout(con, L_STACKED);
1186             }
1187         }
1188     }
1189 }
1190
1191 /*
1192  * Callback which will be called when removing a child from the given con.
1193  * Kills the container if it is empty and replaces it with the child if there
1194  * is exactly one child.
1195  *
1196  */
1197 static void con_on_remove_child(Con *con) {
1198     DLOG("on_remove_child\n");
1199
1200     /* Every container 'above' (in the hierarchy) the workspace content should
1201      * not be closed when the last child was removed */
1202     if (con->type == CT_OUTPUT ||
1203         con->type == CT_ROOT ||
1204         con->type == CT_DOCKAREA) {
1205         DLOG("not handling, type = %d\n", con->type);
1206         return;
1207     }
1208
1209     /* For workspaces, close them only if they're not visible anymore */
1210     if (con->type == CT_WORKSPACE) {
1211         if (TAILQ_EMPTY(&(con->focus_head)) && !workspace_is_visible(con)) {
1212             LOG("Closing old workspace (%p / %s), it is empty\n", con, con->name);
1213             tree_close(con, DONT_KILL_WINDOW, false, false);
1214             ipc_send_event("workspace", I3_IPC_EVENT_WORKSPACE, "{\"change\":\"empty\"}");
1215         }
1216         return;
1217     }
1218
1219     /* TODO: check if this container would swallow any other client and
1220      * don’t close it automatically. */
1221     int children = con_num_children(con);
1222     if (children == 0) {
1223         DLOG("Container empty, closing\n");
1224         tree_close(con, DONT_KILL_WINDOW, false, false);
1225         return;
1226     }
1227 }
1228
1229 /*
1230  * Determines the minimum size of the given con by looking at its children (for
1231  * split/stacked/tabbed cons). Will be called when resizing floating cons
1232  *
1233  */
1234 Rect con_minimum_size(Con *con) {
1235     DLOG("Determining minimum size for con %p\n", con);
1236
1237     if (con_is_leaf(con)) {
1238         DLOG("leaf node, returning 75x50\n");
1239         return (Rect){ 0, 0, 75, 50 };
1240     }
1241
1242     if (con->type == CT_FLOATING_CON) {
1243         DLOG("floating con\n");
1244         Con *child = TAILQ_FIRST(&(con->nodes_head));
1245         return con_minimum_size(child);
1246     }
1247
1248     if (con->layout == L_STACKED || con->layout == L_TABBED) {
1249         uint32_t max_width = 0, max_height = 0, deco_height = 0;
1250         Con *child;
1251         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
1252             Rect min = con_minimum_size(child);
1253             deco_height += child->deco_rect.height;
1254             max_width = max(max_width, min.width);
1255             max_height = max(max_height, min.height);
1256         }
1257         DLOG("stacked/tabbed now, returning %d x %d + deco_rect = %d\n",
1258              max_width, max_height, deco_height);
1259         return (Rect){ 0, 0, max_width, max_height + deco_height };
1260     }
1261
1262     /* For horizontal/vertical split containers we sum up the width (h-split)
1263      * or height (v-split) and use the maximum of the height (h-split) or width
1264      * (v-split) as minimum size. */
1265     if (con->split) {
1266         uint32_t width = 0, height = 0;
1267         Con *child;
1268         TAILQ_FOREACH(child, &(con->nodes_head), nodes) {
1269             Rect min = con_minimum_size(child);
1270             if (con->layout == L_SPLITH) {
1271                 width += min.width;
1272                 height = max(height, min.height);
1273             } else {
1274                 height += min.height;
1275                 width = max(width, min.width);
1276             }
1277         }
1278         DLOG("split container, returning width = %d x height = %d\n", width, height);
1279         return (Rect){ 0, 0, width, height };
1280     }
1281
1282     ELOG("Unhandled case, type = %d, layout = %d, split = %d\n",
1283          con->type, con->layout, con->split);
1284     assert(false);
1285 }
1286
1287 /*
1288  * Returns true if changing the focus to con would be allowed considering
1289  * the fullscreen focus constraints. Specifically, if a fullscreen container or
1290  * any of its descendants is focused, this function returns true if and only if
1291  * focusing con would mean that focus would still be visible on screen, i.e.,
1292  * the newly focused container would not be obscured by a fullscreen container.
1293  *
1294  * In the simplest case, if a fullscreen container or any of its descendants is
1295  * fullscreen, this functions returns true if con is the fullscreen container
1296  * itself or any of its descendants, as this means focus wouldn't escape the
1297  * boundaries of the fullscreen container.
1298  *
1299  * In case the fullscreen container is of type CF_OUTPUT, this function returns
1300  * true if con is on a different workspace, as focus wouldn't be obscured by
1301  * the fullscreen container that is constrained to a different workspace.
1302  *
1303  * Note that this same logic can be applied to moving containers. If a
1304  * container can be focused under the fullscreen focus constraints, it can also
1305  * become a parent or sibling to the currently focused container.
1306  *
1307  */
1308 bool con_fullscreen_permits_focusing(Con *con) {
1309     /* No focus, no problem. */
1310     if (!focused)
1311         return true;
1312
1313     /* Find the first fullscreen ascendent. */
1314     Con *fs = focused;
1315     while (fs && fs->fullscreen_mode == CF_NONE)
1316         fs = fs->parent;
1317
1318     /* fs must be non-NULL since the workspace con doesn’t have CF_NONE and
1319      * there always has to be a workspace con in the hierarchy. */
1320     assert(fs != NULL);
1321     /* The most common case is we hit the workspace level. In this
1322      * situation, changing focus is also harmless. */
1323     assert(fs->fullscreen_mode != CF_NONE);
1324     if (fs->type == CT_WORKSPACE)
1325         return true;
1326
1327     /* Allow it if the container itself is the fullscreen container. */
1328     if (con == fs)
1329         return true;
1330
1331     /* If fullscreen is per-output, the focus being in a different workspace is
1332      * sufficient to guarantee that change won't leave fullscreen in bad shape. */
1333     if (fs->fullscreen_mode == CF_OUTPUT &&
1334         con_get_workspace(con) != con_get_workspace(fs)) {
1335             return true;
1336     }
1337
1338     /* Allow it only if the container to be focused is contained within the
1339      * current fullscreen container. */
1340     do {
1341         if (con->parent == fs)
1342             return true;
1343         con = con->parent;
1344     } while (con);
1345
1346     /* Focusing con would hide it behind a fullscreen window, disallow it. */
1347     return false;
1348 }